34fd6f239d2f0409efafbce260a9db8bec4877d2
[dotfiles/.git] / .config / coc / extensions / node_modules / coc-tsserver / 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 __makeTemplateObject = (this && this.__makeTemplateObject) || function (cooked, raw) {
37     if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
38     return cooked;
39 };
40 var __generator = (this && this.__generator) || function (thisArg, body) {
41     var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
42     return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
43     function verb(n) { return function (v) { return step([n, v]); }; }
44     function step(op) {
45         if (f) throw new TypeError("Generator is already executing.");
46         while (_) try {
47             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;
48             if (y = 0, t) op = [op[0] & 2, t.value];
49             switch (op[0]) {
50                 case 0: case 1: t = op; break;
51                 case 4: _.label++; return { value: op[1], done: false };
52                 case 5: _.label++; y = op[1]; op = [0]; continue;
53                 case 7: op = _.ops.pop(); _.trys.pop(); continue;
54                 default:
55                     if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
56                     if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
57                     if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
58                     if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
59                     if (t[2]) _.ops.pop();
60                     _.trys.pop(); continue;
61             }
62             op = body.call(thisArg, _);
63         } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
64         if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
65     }
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 (Object.prototype.hasOwnProperty.call(b, 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 = "4.1";
85     /** The version of the TypeScript compiler release */
86     ts.version = "4.1.2";
87     /* @internal */
88     var Comparison;
89     (function (Comparison) {
90         Comparison[Comparison["LessThan"] = -1] = "LessThan";
91         Comparison[Comparison["EqualTo"] = 0] = "EqualTo";
92         Comparison[Comparison["GreaterThan"] = 1] = "GreaterThan";
93     })(Comparison = ts.Comparison || (ts.Comparison = {}));
94     /* @internal */
95     var NativeCollections;
96     (function (NativeCollections) {
97         /**
98          * Returns the native Map implementation if it is available and compatible (i.e. supports iteration).
99          */
100         function tryGetNativeMap() {
101             // Internet Explorer's Map doesn't support iteration, so don't use it.
102             // eslint-disable-next-line no-in-operator
103             return typeof Map !== "undefined" && "entries" in Map.prototype && new Map([[0, 0]]).size === 1 ? Map : undefined;
104         }
105         NativeCollections.tryGetNativeMap = tryGetNativeMap;
106         /**
107          * Returns the native Set implementation if it is available and compatible (i.e. supports iteration).
108          */
109         function tryGetNativeSet() {
110             // Internet Explorer's Set doesn't support iteration, so don't use it.
111             // eslint-disable-next-line no-in-operator
112             return typeof Set !== "undefined" && "entries" in Set.prototype && new Set([0]).size === 1 ? Set : undefined;
113         }
114         NativeCollections.tryGetNativeSet = tryGetNativeSet;
115     })(NativeCollections = ts.NativeCollections || (ts.NativeCollections = {}));
116 })(ts || (ts = {}));
117 /* @internal */
118 var ts;
119 (function (ts) {
120     function getCollectionImplementation(name, nativeFactory, shimFactory) {
121         var _a;
122         // NOTE: ts.ShimCollections will be defined for typescriptServices.js but not for tsc.js, so we must test for it.
123         var constructor = (_a = ts.NativeCollections[nativeFactory]()) !== null && _a !== void 0 ? _a : ts.ShimCollections === null || ts.ShimCollections === void 0 ? void 0 : ts.ShimCollections[shimFactory](getIterator);
124         if (constructor)
125             return constructor;
126         throw new Error("TypeScript requires an environment that provides a compatible native " + name + " implementation.");
127     }
128     ts.Map = getCollectionImplementation("Map", "tryGetNativeMap", "createMapShim");
129     ts.Set = getCollectionImplementation("Set", "tryGetNativeSet", "createSetShim");
130     function getIterator(iterable) {
131         if (iterable) {
132             if (isArray(iterable))
133                 return arrayIterator(iterable);
134             if (iterable instanceof ts.Map)
135                 return iterable.entries();
136             if (iterable instanceof ts.Set)
137                 return iterable.values();
138             throw new Error("Iteration not supported.");
139         }
140     }
141     ts.getIterator = getIterator;
142     ts.emptyArray = [];
143     ts.emptyMap = new ts.Map();
144     ts.emptySet = new ts.Set();
145     function createMap() {
146         return new ts.Map();
147     }
148     ts.createMap = createMap;
149     /**
150      * Create a new map from a template object is provided, the map will copy entries from it.
151      * @deprecated Use `new Map(getEntries(template))` instead.
152      */
153     function createMapFromTemplate(template) {
154         var map = new ts.Map();
155         // Copies keys/values from template. Note that for..in will not throw if
156         // template is undefined, and instead will just exit the loop.
157         for (var key in template) {
158             if (hasOwnProperty.call(template, key)) {
159                 map.set(key, template[key]);
160             }
161         }
162         return map;
163     }
164     ts.createMapFromTemplate = createMapFromTemplate;
165     function length(array) {
166         return array ? array.length : 0;
167     }
168     ts.length = length;
169     /**
170      * Iterates through 'array' by index and performs the callback on each element of array until the callback
171      * returns a truthy value, then returns that value.
172      * If no such value is found, the callback is applied to each element of array and undefined is returned.
173      */
174     function forEach(array, callback) {
175         if (array) {
176             for (var i = 0; i < array.length; i++) {
177                 var result = callback(array[i], i);
178                 if (result) {
179                     return result;
180                 }
181             }
182         }
183         return undefined;
184     }
185     ts.forEach = forEach;
186     /**
187      * Like `forEach`, but iterates in reverse order.
188      */
189     function forEachRight(array, callback) {
190         if (array) {
191             for (var i = array.length - 1; i >= 0; i--) {
192                 var result = callback(array[i], i);
193                 if (result) {
194                     return result;
195                 }
196             }
197         }
198         return undefined;
199     }
200     ts.forEachRight = forEachRight;
201     /** Like `forEach`, but suitable for use with numbers and strings (which may be falsy). */
202     function firstDefined(array, callback) {
203         if (array === undefined) {
204             return undefined;
205         }
206         for (var i = 0; i < array.length; i++) {
207             var result = callback(array[i], i);
208             if (result !== undefined) {
209                 return result;
210             }
211         }
212         return undefined;
213     }
214     ts.firstDefined = firstDefined;
215     function firstDefinedIterator(iter, callback) {
216         while (true) {
217             var iterResult = iter.next();
218             if (iterResult.done) {
219                 return undefined;
220             }
221             var result = callback(iterResult.value);
222             if (result !== undefined) {
223                 return result;
224             }
225         }
226     }
227     ts.firstDefinedIterator = firstDefinedIterator;
228     function reduceLeftIterator(iterator, f, initial) {
229         var result = initial;
230         if (iterator) {
231             for (var step = iterator.next(), pos = 0; !step.done; step = iterator.next(), pos++) {
232                 result = f(result, step.value, pos);
233             }
234         }
235         return result;
236     }
237     ts.reduceLeftIterator = reduceLeftIterator;
238     function zipWith(arrayA, arrayB, callback) {
239         var result = [];
240         ts.Debug.assertEqual(arrayA.length, arrayB.length);
241         for (var i = 0; i < arrayA.length; i++) {
242             result.push(callback(arrayA[i], arrayB[i], i));
243         }
244         return result;
245     }
246     ts.zipWith = zipWith;
247     function zipToIterator(arrayA, arrayB) {
248         ts.Debug.assertEqual(arrayA.length, arrayB.length);
249         var i = 0;
250         return {
251             next: function () {
252                 if (i === arrayA.length) {
253                     return { value: undefined, done: true };
254                 }
255                 i++;
256                 return { value: [arrayA[i - 1], arrayB[i - 1]], done: false };
257             }
258         };
259     }
260     ts.zipToIterator = zipToIterator;
261     function zipToMap(keys, values) {
262         ts.Debug.assert(keys.length === values.length);
263         var map = new ts.Map();
264         for (var i = 0; i < keys.length; ++i) {
265             map.set(keys[i], values[i]);
266         }
267         return map;
268     }
269     ts.zipToMap = zipToMap;
270     /**
271      * Creates a new array with `element` interspersed in between each element of `input`
272      * if there is more than 1 value in `input`. Otherwise, returns the existing array.
273      */
274     function intersperse(input, element) {
275         if (input.length <= 1) {
276             return input;
277         }
278         var result = [];
279         for (var i = 0, n = input.length; i < n; i++) {
280             if (i)
281                 result.push(element);
282             result.push(input[i]);
283         }
284         return result;
285     }
286     ts.intersperse = intersperse;
287     /**
288      * Iterates through `array` by index and performs the callback on each element of array until the callback
289      * returns a falsey value, then returns false.
290      * If no such value is found, the callback is applied to each element of array and `true` is returned.
291      */
292     function every(array, callback) {
293         if (array) {
294             for (var i = 0; i < array.length; i++) {
295                 if (!callback(array[i], i)) {
296                     return false;
297                 }
298             }
299         }
300         return true;
301     }
302     ts.every = every;
303     function find(array, predicate) {
304         for (var i = 0; i < array.length; i++) {
305             var value = array[i];
306             if (predicate(value, i)) {
307                 return value;
308             }
309         }
310         return undefined;
311     }
312     ts.find = find;
313     function findLast(array, predicate) {
314         for (var i = array.length - 1; i >= 0; i--) {
315             var value = array[i];
316             if (predicate(value, i)) {
317                 return value;
318             }
319         }
320         return undefined;
321     }
322     ts.findLast = findLast;
323     /** Works like Array.prototype.findIndex, returning `-1` if no element satisfying the predicate is found. */
324     function findIndex(array, predicate, startIndex) {
325         for (var i = startIndex || 0; i < array.length; i++) {
326             if (predicate(array[i], i)) {
327                 return i;
328             }
329         }
330         return -1;
331     }
332     ts.findIndex = findIndex;
333     function findLastIndex(array, predicate, startIndex) {
334         for (var i = startIndex === undefined ? array.length - 1 : startIndex; i >= 0; i--) {
335             if (predicate(array[i], i)) {
336                 return i;
337             }
338         }
339         return -1;
340     }
341     ts.findLastIndex = findLastIndex;
342     /**
343      * Returns the first truthy result of `callback`, or else fails.
344      * This is like `forEach`, but never returns undefined.
345      */
346     function findMap(array, callback) {
347         for (var i = 0; i < array.length; i++) {
348             var result = callback(array[i], i);
349             if (result) {
350                 return result;
351             }
352         }
353         return ts.Debug.fail();
354     }
355     ts.findMap = findMap;
356     function contains(array, value, equalityComparer) {
357         if (equalityComparer === void 0) { equalityComparer = equateValues; }
358         if (array) {
359             for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
360                 var v = array_1[_i];
361                 if (equalityComparer(v, value)) {
362                     return true;
363                 }
364             }
365         }
366         return false;
367     }
368     ts.contains = contains;
369     function arraysEqual(a, b, equalityComparer) {
370         if (equalityComparer === void 0) { equalityComparer = equateValues; }
371         return a.length === b.length && a.every(function (x, i) { return equalityComparer(x, b[i]); });
372     }
373     ts.arraysEqual = arraysEqual;
374     function indexOfAnyCharCode(text, charCodes, start) {
375         for (var i = start || 0; i < text.length; i++) {
376             if (contains(charCodes, text.charCodeAt(i))) {
377                 return i;
378             }
379         }
380         return -1;
381     }
382     ts.indexOfAnyCharCode = indexOfAnyCharCode;
383     function countWhere(array, predicate) {
384         var count = 0;
385         if (array) {
386             for (var i = 0; i < array.length; i++) {
387                 var v = array[i];
388                 if (predicate(v, i)) {
389                     count++;
390                 }
391             }
392         }
393         return count;
394     }
395     ts.countWhere = countWhere;
396     function filter(array, f) {
397         if (array) {
398             var len = array.length;
399             var i = 0;
400             while (i < len && f(array[i]))
401                 i++;
402             if (i < len) {
403                 var result = array.slice(0, i);
404                 i++;
405                 while (i < len) {
406                     var item = array[i];
407                     if (f(item)) {
408                         result.push(item);
409                     }
410                     i++;
411                 }
412                 return result;
413             }
414         }
415         return array;
416     }
417     ts.filter = filter;
418     function filterMutate(array, f) {
419         var outIndex = 0;
420         for (var i = 0; i < array.length; i++) {
421             if (f(array[i], i, array)) {
422                 array[outIndex] = array[i];
423                 outIndex++;
424             }
425         }
426         array.length = outIndex;
427     }
428     ts.filterMutate = filterMutate;
429     function clear(array) {
430         array.length = 0;
431     }
432     ts.clear = clear;
433     function map(array, f) {
434         var result;
435         if (array) {
436             result = [];
437             for (var i = 0; i < array.length; i++) {
438                 result.push(f(array[i], i));
439             }
440         }
441         return result;
442     }
443     ts.map = map;
444     function mapIterator(iter, mapFn) {
445         return {
446             next: function () {
447                 var iterRes = iter.next();
448                 return iterRes.done ? iterRes : { value: mapFn(iterRes.value), done: false };
449             }
450         };
451     }
452     ts.mapIterator = mapIterator;
453     function sameMap(array, f) {
454         if (array) {
455             for (var i = 0; i < array.length; i++) {
456                 var item = array[i];
457                 var mapped = f(item, i);
458                 if (item !== mapped) {
459                     var result = array.slice(0, i);
460                     result.push(mapped);
461                     for (i++; i < array.length; i++) {
462                         result.push(f(array[i], i));
463                     }
464                     return result;
465                 }
466             }
467         }
468         return array;
469     }
470     ts.sameMap = sameMap;
471     /**
472      * Flattens an array containing a mix of array or non-array elements.
473      *
474      * @param array The array to flatten.
475      */
476     function flatten(array) {
477         var result = [];
478         for (var _i = 0, array_2 = array; _i < array_2.length; _i++) {
479             var v = array_2[_i];
480             if (v) {
481                 if (isArray(v)) {
482                     addRange(result, v);
483                 }
484                 else {
485                     result.push(v);
486                 }
487             }
488         }
489         return result;
490     }
491     ts.flatten = flatten;
492     /**
493      * Maps an array. If the mapped value is an array, it is spread into the result.
494      *
495      * @param array The array to map.
496      * @param mapfn The callback used to map the result into one or more values.
497      */
498     function flatMap(array, mapfn) {
499         var result;
500         if (array) {
501             for (var i = 0; i < array.length; i++) {
502                 var v = mapfn(array[i], i);
503                 if (v) {
504                     if (isArray(v)) {
505                         result = addRange(result, v);
506                     }
507                     else {
508                         result = append(result, v);
509                     }
510                 }
511             }
512         }
513         return result || ts.emptyArray;
514     }
515     ts.flatMap = flatMap;
516     function flatMapToMutable(array, mapfn) {
517         var result = [];
518         if (array) {
519             for (var i = 0; i < array.length; i++) {
520                 var v = mapfn(array[i], i);
521                 if (v) {
522                     if (isArray(v)) {
523                         addRange(result, v);
524                     }
525                     else {
526                         result.push(v);
527                     }
528                 }
529             }
530         }
531         return result;
532     }
533     ts.flatMapToMutable = flatMapToMutable;
534     function flatMapIterator(iter, mapfn) {
535         var first = iter.next();
536         if (first.done) {
537             return ts.emptyIterator;
538         }
539         var currentIter = getIterator(first.value);
540         return {
541             next: function () {
542                 while (true) {
543                     var currentRes = currentIter.next();
544                     if (!currentRes.done) {
545                         return currentRes;
546                     }
547                     var iterRes = iter.next();
548                     if (iterRes.done) {
549                         return iterRes;
550                     }
551                     currentIter = getIterator(iterRes.value);
552                 }
553             },
554         };
555         function getIterator(x) {
556             var res = mapfn(x);
557             return res === undefined ? ts.emptyIterator : isArray(res) ? arrayIterator(res) : res;
558         }
559     }
560     ts.flatMapIterator = flatMapIterator;
561     function sameFlatMap(array, mapfn) {
562         var result;
563         if (array) {
564             for (var i = 0; i < array.length; i++) {
565                 var item = array[i];
566                 var mapped = mapfn(item, i);
567                 if (result || item !== mapped || isArray(mapped)) {
568                     if (!result) {
569                         result = array.slice(0, i);
570                     }
571                     if (isArray(mapped)) {
572                         addRange(result, mapped);
573                     }
574                     else {
575                         result.push(mapped);
576                     }
577                 }
578             }
579         }
580         return result || array;
581     }
582     ts.sameFlatMap = sameFlatMap;
583     function mapAllOrFail(array, mapFn) {
584         var result = [];
585         for (var i = 0; i < array.length; i++) {
586             var mapped = mapFn(array[i], i);
587             if (mapped === undefined) {
588                 return undefined;
589             }
590             result.push(mapped);
591         }
592         return result;
593     }
594     ts.mapAllOrFail = mapAllOrFail;
595     function mapDefined(array, mapFn) {
596         var result = [];
597         if (array) {
598             for (var i = 0; i < array.length; i++) {
599                 var mapped = mapFn(array[i], i);
600                 if (mapped !== undefined) {
601                     result.push(mapped);
602                 }
603             }
604         }
605         return result;
606     }
607     ts.mapDefined = mapDefined;
608     function mapDefinedIterator(iter, mapFn) {
609         return {
610             next: function () {
611                 while (true) {
612                     var res = iter.next();
613                     if (res.done) {
614                         return res;
615                     }
616                     var value = mapFn(res.value);
617                     if (value !== undefined) {
618                         return { value: value, done: false };
619                     }
620                 }
621             }
622         };
623     }
624     ts.mapDefinedIterator = mapDefinedIterator;
625     function mapDefinedEntries(map, f) {
626         if (!map) {
627             return undefined;
628         }
629         var result = new ts.Map();
630         map.forEach(function (value, key) {
631             var entry = f(key, value);
632             if (entry !== undefined) {
633                 var newKey = entry[0], newValue = entry[1];
634                 if (newKey !== undefined && newValue !== undefined) {
635                     result.set(newKey, newValue);
636                 }
637             }
638         });
639         return result;
640     }
641     ts.mapDefinedEntries = mapDefinedEntries;
642     function mapDefinedValues(set, f) {
643         if (set) {
644             var result_1 = new ts.Set();
645             set.forEach(function (value) {
646                 var newValue = f(value);
647                 if (newValue !== undefined) {
648                     result_1.add(newValue);
649                 }
650             });
651             return result_1;
652         }
653     }
654     ts.mapDefinedValues = mapDefinedValues;
655     function getOrUpdate(map, key, callback) {
656         if (map.has(key)) {
657             return map.get(key);
658         }
659         var value = callback();
660         map.set(key, value);
661         return value;
662     }
663     ts.getOrUpdate = getOrUpdate;
664     function tryAddToSet(set, value) {
665         if (!set.has(value)) {
666             set.add(value);
667             return true;
668         }
669         return false;
670     }
671     ts.tryAddToSet = tryAddToSet;
672     ts.emptyIterator = { next: function () { return ({ value: undefined, done: true }); } };
673     function singleIterator(value) {
674         var done = false;
675         return {
676             next: function () {
677                 var wasDone = done;
678                 done = true;
679                 return wasDone ? { value: undefined, done: true } : { value: value, done: false };
680             }
681         };
682     }
683     ts.singleIterator = singleIterator;
684     function spanMap(array, keyfn, mapfn) {
685         var result;
686         if (array) {
687             result = [];
688             var len = array.length;
689             var previousKey = void 0;
690             var key = void 0;
691             var start = 0;
692             var pos = 0;
693             while (start < len) {
694                 while (pos < len) {
695                     var value = array[pos];
696                     key = keyfn(value, pos);
697                     if (pos === 0) {
698                         previousKey = key;
699                     }
700                     else if (key !== previousKey) {
701                         break;
702                     }
703                     pos++;
704                 }
705                 if (start < pos) {
706                     var v = mapfn(array.slice(start, pos), previousKey, start, pos);
707                     if (v) {
708                         result.push(v);
709                     }
710                     start = pos;
711                 }
712                 previousKey = key;
713                 pos++;
714             }
715         }
716         return result;
717     }
718     ts.spanMap = spanMap;
719     function mapEntries(map, f) {
720         if (!map) {
721             return undefined;
722         }
723         var result = new ts.Map();
724         map.forEach(function (value, key) {
725             var _a = f(key, value), newKey = _a[0], newValue = _a[1];
726             result.set(newKey, newValue);
727         });
728         return result;
729     }
730     ts.mapEntries = mapEntries;
731     function some(array, predicate) {
732         if (array) {
733             if (predicate) {
734                 for (var _i = 0, array_3 = array; _i < array_3.length; _i++) {
735                     var v = array_3[_i];
736                     if (predicate(v)) {
737                         return true;
738                     }
739                 }
740             }
741             else {
742                 return array.length > 0;
743             }
744         }
745         return false;
746     }
747     ts.some = some;
748     /** Calls the callback with (start, afterEnd) index pairs for each range where 'pred' is true. */
749     function getRangesWhere(arr, pred, cb) {
750         var start;
751         for (var i = 0; i < arr.length; i++) {
752             if (pred(arr[i])) {
753                 start = start === undefined ? i : start;
754             }
755             else {
756                 if (start !== undefined) {
757                     cb(start, i);
758                     start = undefined;
759                 }
760             }
761         }
762         if (start !== undefined)
763             cb(start, arr.length);
764     }
765     ts.getRangesWhere = getRangesWhere;
766     function concatenate(array1, array2) {
767         if (!some(array2))
768             return array1;
769         if (!some(array1))
770             return array2;
771         return __spreadArrays(array1, array2);
772     }
773     ts.concatenate = concatenate;
774     function selectIndex(_, i) {
775         return i;
776     }
777     function indicesOf(array) {
778         return array.map(selectIndex);
779     }
780     ts.indicesOf = indicesOf;
781     function deduplicateRelational(array, equalityComparer, comparer) {
782         // Perform a stable sort of the array. This ensures the first entry in a list of
783         // duplicates remains the first entry in the result.
784         var indices = indicesOf(array);
785         stableSortIndices(array, indices, comparer);
786         var last = array[indices[0]];
787         var deduplicated = [indices[0]];
788         for (var i = 1; i < indices.length; i++) {
789             var index = indices[i];
790             var item = array[index];
791             if (!equalityComparer(last, item)) {
792                 deduplicated.push(index);
793                 last = item;
794             }
795         }
796         // restore original order
797         deduplicated.sort();
798         return deduplicated.map(function (i) { return array[i]; });
799     }
800     function deduplicateEquality(array, equalityComparer) {
801         var result = [];
802         for (var _i = 0, array_4 = array; _i < array_4.length; _i++) {
803             var item = array_4[_i];
804             pushIfUnique(result, item, equalityComparer);
805         }
806         return result;
807     }
808     /**
809      * Deduplicates an unsorted array.
810      * @param equalityComparer An `EqualityComparer` used to determine if two values are duplicates.
811      * @param comparer An optional `Comparer` used to sort entries before comparison, though the
812      * result will remain in the original order in `array`.
813      */
814     function deduplicate(array, equalityComparer, comparer) {
815         return array.length === 0 ? [] :
816             array.length === 1 ? array.slice() :
817                 comparer ? deduplicateRelational(array, equalityComparer, comparer) :
818                     deduplicateEquality(array, equalityComparer);
819     }
820     ts.deduplicate = deduplicate;
821     /**
822      * Deduplicates an array that has already been sorted.
823      */
824     function deduplicateSorted(array, comparer) {
825         if (array.length === 0)
826             return ts.emptyArray;
827         var last = array[0];
828         var deduplicated = [last];
829         for (var i = 1; i < array.length; i++) {
830             var next = array[i];
831             switch (comparer(next, last)) {
832                 // equality comparison
833                 case true:
834                 // relational comparison
835                 // falls through
836                 case 0 /* EqualTo */:
837                     continue;
838                 case -1 /* LessThan */:
839                     // If `array` is sorted, `next` should **never** be less than `last`.
840                     return ts.Debug.fail("Array is unsorted.");
841             }
842             deduplicated.push(last = next);
843         }
844         return deduplicated;
845     }
846     function insertSorted(array, insert, compare) {
847         if (array.length === 0) {
848             array.push(insert);
849             return;
850         }
851         var insertIndex = binarySearch(array, insert, identity, compare);
852         if (insertIndex < 0) {
853             array.splice(~insertIndex, 0, insert);
854         }
855     }
856     ts.insertSorted = insertSorted;
857     function sortAndDeduplicate(array, comparer, equalityComparer) {
858         return deduplicateSorted(sort(array, comparer), equalityComparer || comparer || compareStringsCaseSensitive);
859     }
860     ts.sortAndDeduplicate = sortAndDeduplicate;
861     function arrayIsSorted(array, comparer) {
862         if (array.length < 2)
863             return true;
864         var prevElement = array[0];
865         for (var _i = 0, _a = array.slice(1); _i < _a.length; _i++) {
866             var element = _a[_i];
867             if (comparer(prevElement, element) === 1 /* GreaterThan */) {
868                 return false;
869             }
870             prevElement = element;
871         }
872         return true;
873     }
874     ts.arrayIsSorted = arrayIsSorted;
875     function arrayIsEqualTo(array1, array2, equalityComparer) {
876         if (equalityComparer === void 0) { equalityComparer = equateValues; }
877         if (!array1 || !array2) {
878             return array1 === array2;
879         }
880         if (array1.length !== array2.length) {
881             return false;
882         }
883         for (var i = 0; i < array1.length; i++) {
884             if (!equalityComparer(array1[i], array2[i], i)) {
885                 return false;
886             }
887         }
888         return true;
889     }
890     ts.arrayIsEqualTo = arrayIsEqualTo;
891     function compact(array) {
892         var result;
893         if (array) {
894             for (var i = 0; i < array.length; i++) {
895                 var v = array[i];
896                 if (result || !v) {
897                     if (!result) {
898                         result = array.slice(0, i);
899                     }
900                     if (v) {
901                         result.push(v);
902                     }
903                 }
904             }
905         }
906         return result || array;
907     }
908     ts.compact = compact;
909     /**
910      * Gets the relative complement of `arrayA` with respect to `arrayB`, returning the elements that
911      * are not present in `arrayA` but are present in `arrayB`. Assumes both arrays are sorted
912      * based on the provided comparer.
913      */
914     function relativeComplement(arrayA, arrayB, comparer) {
915         if (!arrayB || !arrayA || arrayB.length === 0 || arrayA.length === 0)
916             return arrayB;
917         var result = [];
918         loopB: for (var offsetA = 0, offsetB = 0; offsetB < arrayB.length; offsetB++) {
919             if (offsetB > 0) {
920                 // Ensure `arrayB` is properly sorted.
921                 ts.Debug.assertGreaterThanOrEqual(comparer(arrayB[offsetB], arrayB[offsetB - 1]), 0 /* EqualTo */);
922             }
923             loopA: for (var startA = offsetA; offsetA < arrayA.length; offsetA++) {
924                 if (offsetA > startA) {
925                     // Ensure `arrayA` is properly sorted. We only need to perform this check if
926                     // `offsetA` has changed since we entered the loop.
927                     ts.Debug.assertGreaterThanOrEqual(comparer(arrayA[offsetA], arrayA[offsetA - 1]), 0 /* EqualTo */);
928                 }
929                 switch (comparer(arrayB[offsetB], arrayA[offsetA])) {
930                     case -1 /* LessThan */:
931                         // If B is less than A, B does not exist in arrayA. Add B to the result and
932                         // move to the next element in arrayB without changing the current position
933                         // in arrayA.
934                         result.push(arrayB[offsetB]);
935                         continue loopB;
936                     case 0 /* EqualTo */:
937                         // If B is equal to A, B exists in arrayA. Move to the next element in
938                         // arrayB without adding B to the result or changing the current position
939                         // in arrayA.
940                         continue loopB;
941                     case 1 /* GreaterThan */:
942                         // If B is greater than A, we need to keep looking for B in arrayA. Move to
943                         // the next element in arrayA and recheck.
944                         continue loopA;
945                 }
946             }
947         }
948         return result;
949     }
950     ts.relativeComplement = relativeComplement;
951     function sum(array, prop) {
952         var result = 0;
953         for (var _i = 0, array_5 = array; _i < array_5.length; _i++) {
954             var v = array_5[_i];
955             result += v[prop];
956         }
957         return result;
958     }
959     ts.sum = sum;
960     function append(to, value) {
961         if (value === undefined)
962             return to;
963         if (to === undefined)
964             return [value];
965         to.push(value);
966         return to;
967     }
968     ts.append = append;
969     function combine(xs, ys) {
970         if (xs === undefined)
971             return ys;
972         if (ys === undefined)
973             return xs;
974         if (isArray(xs))
975             return isArray(ys) ? concatenate(xs, ys) : append(xs, ys);
976         if (isArray(ys))
977             return append(ys, xs);
978         return [xs, ys];
979     }
980     ts.combine = combine;
981     /**
982      * Gets the actual offset into an array for a relative offset. Negative offsets indicate a
983      * position offset from the end of the array.
984      */
985     function toOffset(array, offset) {
986         return offset < 0 ? array.length + offset : offset;
987     }
988     function addRange(to, from, start, end) {
989         if (from === undefined || from.length === 0)
990             return to;
991         if (to === undefined)
992             return from.slice(start, end);
993         start = start === undefined ? 0 : toOffset(from, start);
994         end = end === undefined ? from.length : toOffset(from, end);
995         for (var i = start; i < end && i < from.length; i++) {
996             if (from[i] !== undefined) {
997                 to.push(from[i]);
998             }
999         }
1000         return to;
1001     }
1002     ts.addRange = addRange;
1003     /**
1004      * @return Whether the value was added.
1005      */
1006     function pushIfUnique(array, toAdd, equalityComparer) {
1007         if (contains(array, toAdd, equalityComparer)) {
1008             return false;
1009         }
1010         else {
1011             array.push(toAdd);
1012             return true;
1013         }
1014     }
1015     ts.pushIfUnique = pushIfUnique;
1016     /**
1017      * Unlike `pushIfUnique`, this can take `undefined` as an input, and returns a new array.
1018      */
1019     function appendIfUnique(array, toAdd, equalityComparer) {
1020         if (array) {
1021             pushIfUnique(array, toAdd, equalityComparer);
1022             return array;
1023         }
1024         else {
1025             return [toAdd];
1026         }
1027     }
1028     ts.appendIfUnique = appendIfUnique;
1029     function stableSortIndices(array, indices, comparer) {
1030         // sort indices by value then position
1031         indices.sort(function (x, y) { return comparer(array[x], array[y]) || compareValues(x, y); });
1032     }
1033     /**
1034      * Returns a new sorted array.
1035      */
1036     function sort(array, comparer) {
1037         return (array.length === 0 ? array : array.slice().sort(comparer));
1038     }
1039     ts.sort = sort;
1040     function arrayIterator(array) {
1041         var i = 0;
1042         return { next: function () {
1043                 if (i === array.length) {
1044                     return { value: undefined, done: true };
1045                 }
1046                 else {
1047                     i++;
1048                     return { value: array[i - 1], done: false };
1049                 }
1050             } };
1051     }
1052     ts.arrayIterator = arrayIterator;
1053     function arrayReverseIterator(array) {
1054         var i = array.length;
1055         return {
1056             next: function () {
1057                 if (i === 0) {
1058                     return { value: undefined, done: true };
1059                 }
1060                 else {
1061                     i--;
1062                     return { value: array[i], done: false };
1063                 }
1064             }
1065         };
1066     }
1067     ts.arrayReverseIterator = arrayReverseIterator;
1068     /**
1069      * Stable sort of an array. Elements equal to each other maintain their relative position in the array.
1070      */
1071     function stableSort(array, comparer) {
1072         var indices = indicesOf(array);
1073         stableSortIndices(array, indices, comparer);
1074         return indices.map(function (i) { return array[i]; });
1075     }
1076     ts.stableSort = stableSort;
1077     function rangeEquals(array1, array2, pos, end) {
1078         while (pos < end) {
1079             if (array1[pos] !== array2[pos]) {
1080                 return false;
1081             }
1082             pos++;
1083         }
1084         return true;
1085     }
1086     ts.rangeEquals = rangeEquals;
1087     /**
1088      * Returns the element at a specific offset in an array if non-empty, `undefined` otherwise.
1089      * A negative offset indicates the element should be retrieved from the end of the array.
1090      */
1091     function elementAt(array, offset) {
1092         if (array) {
1093             offset = toOffset(array, offset);
1094             if (offset < array.length) {
1095                 return array[offset];
1096             }
1097         }
1098         return undefined;
1099     }
1100     ts.elementAt = elementAt;
1101     /**
1102      * Returns the first element of an array if non-empty, `undefined` otherwise.
1103      */
1104     function firstOrUndefined(array) {
1105         return array.length === 0 ? undefined : array[0];
1106     }
1107     ts.firstOrUndefined = firstOrUndefined;
1108     function first(array) {
1109         ts.Debug.assert(array.length !== 0);
1110         return array[0];
1111     }
1112     ts.first = first;
1113     /**
1114      * Returns the last element of an array if non-empty, `undefined` otherwise.
1115      */
1116     function lastOrUndefined(array) {
1117         return array.length === 0 ? undefined : array[array.length - 1];
1118     }
1119     ts.lastOrUndefined = lastOrUndefined;
1120     function last(array) {
1121         ts.Debug.assert(array.length !== 0);
1122         return array[array.length - 1];
1123     }
1124     ts.last = last;
1125     /**
1126      * Returns the only element of an array if it contains only one element, `undefined` otherwise.
1127      */
1128     function singleOrUndefined(array) {
1129         return array && array.length === 1
1130             ? array[0]
1131             : undefined;
1132     }
1133     ts.singleOrUndefined = singleOrUndefined;
1134     function singleOrMany(array) {
1135         return array && array.length === 1
1136             ? array[0]
1137             : array;
1138     }
1139     ts.singleOrMany = singleOrMany;
1140     function replaceElement(array, index, value) {
1141         var result = array.slice(0);
1142         result[index] = value;
1143         return result;
1144     }
1145     ts.replaceElement = replaceElement;
1146     /**
1147      * Performs a binary search, finding the index at which `value` occurs in `array`.
1148      * If no such index is found, returns the 2's-complement of first index at which
1149      * `array[index]` exceeds `value`.
1150      * @param array A sorted array whose first element must be no larger than number
1151      * @param value The value to be searched for in the array.
1152      * @param keySelector A callback used to select the search key from `value` and each element of
1153      * `array`.
1154      * @param keyComparer A callback used to compare two keys in a sorted array.
1155      * @param offset An offset into `array` at which to start the search.
1156      */
1157     function binarySearch(array, value, keySelector, keyComparer, offset) {
1158         return binarySearchKey(array, keySelector(value), keySelector, keyComparer, offset);
1159     }
1160     ts.binarySearch = binarySearch;
1161     /**
1162      * Performs a binary search, finding the index at which an object with `key` occurs in `array`.
1163      * If no such index is found, returns the 2's-complement of first index at which
1164      * `array[index]` exceeds `key`.
1165      * @param array A sorted array whose first element must be no larger than number
1166      * @param key The key to be searched for in the array.
1167      * @param keySelector A callback used to select the search key from each element of `array`.
1168      * @param keyComparer A callback used to compare two keys in a sorted array.
1169      * @param offset An offset into `array` at which to start the search.
1170      */
1171     function binarySearchKey(array, key, keySelector, keyComparer, offset) {
1172         if (!some(array)) {
1173             return -1;
1174         }
1175         var low = offset || 0;
1176         var high = array.length - 1;
1177         while (low <= high) {
1178             var middle = low + ((high - low) >> 1);
1179             var midKey = keySelector(array[middle], middle);
1180             switch (keyComparer(midKey, key)) {
1181                 case -1 /* LessThan */:
1182                     low = middle + 1;
1183                     break;
1184                 case 0 /* EqualTo */:
1185                     return middle;
1186                 case 1 /* GreaterThan */:
1187                     high = middle - 1;
1188                     break;
1189             }
1190         }
1191         return ~low;
1192     }
1193     ts.binarySearchKey = binarySearchKey;
1194     function reduceLeft(array, f, initial, start, count) {
1195         if (array && array.length > 0) {
1196             var size = array.length;
1197             if (size > 0) {
1198                 var pos = start === undefined || start < 0 ? 0 : start;
1199                 var end = count === undefined || pos + count > size - 1 ? size - 1 : pos + count;
1200                 var result = void 0;
1201                 if (arguments.length <= 2) {
1202                     result = array[pos];
1203                     pos++;
1204                 }
1205                 else {
1206                     result = initial;
1207                 }
1208                 while (pos <= end) {
1209                     result = f(result, array[pos], pos);
1210                     pos++;
1211                 }
1212                 return result;
1213             }
1214         }
1215         return initial;
1216     }
1217     ts.reduceLeft = reduceLeft;
1218     var hasOwnProperty = Object.prototype.hasOwnProperty;
1219     /**
1220      * Indicates whether a map-like contains an own property with the specified key.
1221      *
1222      * @param map A map-like.
1223      * @param key A property key.
1224      */
1225     function hasProperty(map, key) {
1226         return hasOwnProperty.call(map, key);
1227     }
1228     ts.hasProperty = hasProperty;
1229     /**
1230      * Gets the value of an owned property in a map-like.
1231      *
1232      * @param map A map-like.
1233      * @param key A property key.
1234      */
1235     function getProperty(map, key) {
1236         return hasOwnProperty.call(map, key) ? map[key] : undefined;
1237     }
1238     ts.getProperty = getProperty;
1239     /**
1240      * Gets the owned, enumerable property keys of a map-like.
1241      */
1242     function getOwnKeys(map) {
1243         var keys = [];
1244         for (var key in map) {
1245             if (hasOwnProperty.call(map, key)) {
1246                 keys.push(key);
1247             }
1248         }
1249         return keys;
1250     }
1251     ts.getOwnKeys = getOwnKeys;
1252     function getAllKeys(obj) {
1253         var result = [];
1254         do {
1255             var names = Object.getOwnPropertyNames(obj);
1256             for (var _i = 0, names_1 = names; _i < names_1.length; _i++) {
1257                 var name = names_1[_i];
1258                 pushIfUnique(result, name);
1259             }
1260         } while (obj = Object.getPrototypeOf(obj));
1261         return result;
1262     }
1263     ts.getAllKeys = getAllKeys;
1264     function getOwnValues(sparseArray) {
1265         var values = [];
1266         for (var key in sparseArray) {
1267             if (hasOwnProperty.call(sparseArray, key)) {
1268                 values.push(sparseArray[key]);
1269             }
1270         }
1271         return values;
1272     }
1273     ts.getOwnValues = getOwnValues;
1274     var _entries = Object.entries || (function (obj) {
1275         var keys = getOwnKeys(obj);
1276         var result = Array(keys.length);
1277         for (var i = 0; i < keys.length; i++) {
1278             result[i] = [keys[i], obj[keys[i]]];
1279         }
1280         return result;
1281     });
1282     function getEntries(obj) {
1283         return obj ? _entries(obj) : [];
1284     }
1285     ts.getEntries = getEntries;
1286     function arrayOf(count, f) {
1287         var result = new Array(count);
1288         for (var i = 0; i < count; i++) {
1289             result[i] = f(i);
1290         }
1291         return result;
1292     }
1293     ts.arrayOf = arrayOf;
1294     function arrayFrom(iterator, map) {
1295         var result = [];
1296         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
1297             result.push(map ? map(iterResult.value) : iterResult.value);
1298         }
1299         return result;
1300     }
1301     ts.arrayFrom = arrayFrom;
1302     function assign(t) {
1303         var args = [];
1304         for (var _i = 1; _i < arguments.length; _i++) {
1305             args[_i - 1] = arguments[_i];
1306         }
1307         for (var _a = 0, args_1 = args; _a < args_1.length; _a++) {
1308             var arg = args_1[_a];
1309             if (arg === undefined)
1310                 continue;
1311             for (var p in arg) {
1312                 if (hasProperty(arg, p)) {
1313                     t[p] = arg[p];
1314                 }
1315             }
1316         }
1317         return t;
1318     }
1319     ts.assign = assign;
1320     /**
1321      * Performs a shallow equality comparison of the contents of two map-likes.
1322      *
1323      * @param left A map-like whose properties should be compared.
1324      * @param right A map-like whose properties should be compared.
1325      */
1326     function equalOwnProperties(left, right, equalityComparer) {
1327         if (equalityComparer === void 0) { equalityComparer = equateValues; }
1328         if (left === right)
1329             return true;
1330         if (!left || !right)
1331             return false;
1332         for (var key in left) {
1333             if (hasOwnProperty.call(left, key)) {
1334                 if (!hasOwnProperty.call(right, key))
1335                     return false;
1336                 if (!equalityComparer(left[key], right[key]))
1337                     return false;
1338             }
1339         }
1340         for (var key in right) {
1341             if (hasOwnProperty.call(right, key)) {
1342                 if (!hasOwnProperty.call(left, key))
1343                     return false;
1344             }
1345         }
1346         return true;
1347     }
1348     ts.equalOwnProperties = equalOwnProperties;
1349     function arrayToMap(array, makeKey, makeValue) {
1350         if (makeValue === void 0) { makeValue = identity; }
1351         var result = new ts.Map();
1352         for (var _i = 0, array_6 = array; _i < array_6.length; _i++) {
1353             var value = array_6[_i];
1354             var key = makeKey(value);
1355             if (key !== undefined)
1356                 result.set(key, makeValue(value));
1357         }
1358         return result;
1359     }
1360     ts.arrayToMap = arrayToMap;
1361     function arrayToNumericMap(array, makeKey, makeValue) {
1362         if (makeValue === void 0) { makeValue = identity; }
1363         var result = [];
1364         for (var _i = 0, array_7 = array; _i < array_7.length; _i++) {
1365             var value = array_7[_i];
1366             result[makeKey(value)] = makeValue(value);
1367         }
1368         return result;
1369     }
1370     ts.arrayToNumericMap = arrayToNumericMap;
1371     function arrayToMultiMap(values, makeKey, makeValue) {
1372         if (makeValue === void 0) { makeValue = identity; }
1373         var result = createMultiMap();
1374         for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
1375             var value = values_1[_i];
1376             result.add(makeKey(value), makeValue(value));
1377         }
1378         return result;
1379     }
1380     ts.arrayToMultiMap = arrayToMultiMap;
1381     function group(values, getGroupId, resultSelector) {
1382         if (resultSelector === void 0) { resultSelector = identity; }
1383         return arrayFrom(arrayToMultiMap(values, getGroupId).values(), resultSelector);
1384     }
1385     ts.group = group;
1386     function clone(object) {
1387         var result = {};
1388         for (var id in object) {
1389             if (hasOwnProperty.call(object, id)) {
1390                 result[id] = object[id];
1391             }
1392         }
1393         return result;
1394     }
1395     ts.clone = clone;
1396     /**
1397      * Creates a new object by adding the own properties of `second`, then the own properties of `first`.
1398      *
1399      * NOTE: This means that if a property exists in both `first` and `second`, the property in `first` will be chosen.
1400      */
1401     function extend(first, second) {
1402         var result = {};
1403         for (var id in second) {
1404             if (hasOwnProperty.call(second, id)) {
1405                 result[id] = second[id];
1406             }
1407         }
1408         for (var id in first) {
1409             if (hasOwnProperty.call(first, id)) {
1410                 result[id] = first[id];
1411             }
1412         }
1413         return result;
1414     }
1415     ts.extend = extend;
1416     function copyProperties(first, second) {
1417         for (var id in second) {
1418             if (hasOwnProperty.call(second, id)) {
1419                 first[id] = second[id];
1420             }
1421         }
1422     }
1423     ts.copyProperties = copyProperties;
1424     function maybeBind(obj, fn) {
1425         return fn ? fn.bind(obj) : undefined;
1426     }
1427     ts.maybeBind = maybeBind;
1428     function createMultiMap() {
1429         var map = new ts.Map();
1430         map.add = multiMapAdd;
1431         map.remove = multiMapRemove;
1432         return map;
1433     }
1434     ts.createMultiMap = createMultiMap;
1435     function multiMapAdd(key, value) {
1436         var values = this.get(key);
1437         if (values) {
1438             values.push(value);
1439         }
1440         else {
1441             this.set(key, values = [value]);
1442         }
1443         return values;
1444     }
1445     function multiMapRemove(key, value) {
1446         var values = this.get(key);
1447         if (values) {
1448             unorderedRemoveItem(values, value);
1449             if (!values.length) {
1450                 this.delete(key);
1451             }
1452         }
1453     }
1454     function createUnderscoreEscapedMultiMap() {
1455         return createMultiMap();
1456     }
1457     ts.createUnderscoreEscapedMultiMap = createUnderscoreEscapedMultiMap;
1458     /**
1459      * Tests whether a value is an array.
1460      */
1461     function isArray(value) {
1462         return Array.isArray ? Array.isArray(value) : value instanceof Array;
1463     }
1464     ts.isArray = isArray;
1465     function toArray(value) {
1466         return isArray(value) ? value : [value];
1467     }
1468     ts.toArray = toArray;
1469     /**
1470      * Tests whether a value is string
1471      */
1472     function isString(text) {
1473         return typeof text === "string";
1474     }
1475     ts.isString = isString;
1476     function isNumber(x) {
1477         return typeof x === "number";
1478     }
1479     ts.isNumber = isNumber;
1480     function tryCast(value, test) {
1481         return value !== undefined && test(value) ? value : undefined;
1482     }
1483     ts.tryCast = tryCast;
1484     function cast(value, test) {
1485         if (value !== undefined && test(value))
1486             return value;
1487         return ts.Debug.fail("Invalid cast. The supplied value " + value + " did not pass the test '" + ts.Debug.getFunctionName(test) + "'.");
1488     }
1489     ts.cast = cast;
1490     /** Does nothing. */
1491     function noop(_) { }
1492     ts.noop = noop;
1493     /** Do nothing and return false */
1494     function returnFalse() { return false; }
1495     ts.returnFalse = returnFalse;
1496     /** Do nothing and return true */
1497     function returnTrue() { return true; }
1498     ts.returnTrue = returnTrue;
1499     /** Do nothing and return undefined */
1500     function returnUndefined() { return undefined; }
1501     ts.returnUndefined = returnUndefined;
1502     /** Returns its argument. */
1503     function identity(x) { return x; }
1504     ts.identity = identity;
1505     /** Returns lower case string */
1506     function toLowerCase(x) { return x.toLowerCase(); }
1507     ts.toLowerCase = toLowerCase;
1508     // We convert the file names to lower case as key for file name on case insensitive file system
1509     // While doing so we need to handle special characters (eg \u0130) to ensure that we dont convert
1510     // it to lower case, fileName with its lowercase form can exist along side it.
1511     // Handle special characters and make those case sensitive instead
1512     //
1513     // |-#--|-Unicode--|-Char code-|-Desc-------------------------------------------------------------------|
1514     // | 1. | i        | 105       | Ascii i                                                                |
1515     // | 2. | I        | 73        | Ascii I                                                                |
1516     // |-------- Special characters ------------------------------------------------------------------------|
1517     // | 3. | \u0130   | 304       | Uppper case I with dot above                                           |
1518     // | 4. | i,\u0307 | 105,775   | i, followed by 775: Lower case of (3rd item)                           |
1519     // | 5. | I,\u0307 | 73,775    | I, followed by 775: Upper case of (4th item), lower case is (4th item) |
1520     // | 6. | \u0131   | 305       | Lower case i without dot, upper case is I (2nd item)                   |
1521     // | 7. | \u00DF   | 223       | Lower case sharp s                                                     |
1522     //
1523     // Because item 3 is special where in its lowercase character has its own
1524     // upper case form we cant convert its case.
1525     // Rest special characters are either already in lower case format or
1526     // they have corresponding upper case character so they dont need special handling
1527     //
1528     // But to avoid having to do string building for most common cases, also ignore
1529     // a-z, 0-9, \u0131, \u00DF, \, /, ., : and space
1530     var fileNameLowerCaseRegExp = /[^\u0130\u0131\u00DFa-z0-9\\/:\-_\. ]+/g;
1531     /**
1532      * Case insensitive file systems have descripencies in how they handle some characters (eg. turkish Upper case I with dot on top - \u0130)
1533      * This function is used in places where we want to make file name as a key on these systems
1534      * 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
1535      * 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
1536      * Technically we would want this function to be platform sepcific as well but
1537      * 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
1538      * We could use upper case and we would still need to deal with the descripencies but
1539      * 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
1540      * 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
1541      */
1542     function toFileNameLowerCase(x) {
1543         return fileNameLowerCaseRegExp.test(x) ?
1544             x.replace(fileNameLowerCaseRegExp, toLowerCase) :
1545             x;
1546     }
1547     ts.toFileNameLowerCase = toFileNameLowerCase;
1548     /** Throws an error because a function is not implemented. */
1549     function notImplemented() {
1550         throw new Error("Not implemented");
1551     }
1552     ts.notImplemented = notImplemented;
1553     function memoize(callback) {
1554         var value;
1555         return function () {
1556             if (callback) {
1557                 value = callback();
1558                 callback = undefined;
1559             }
1560             return value;
1561         };
1562     }
1563     ts.memoize = memoize;
1564     /** A version of `memoize` that supports a single primitive argument */
1565     function memoizeOne(callback) {
1566         var map = new ts.Map();
1567         return function (arg) {
1568             var key = typeof arg + ":" + arg;
1569             var value = map.get(key);
1570             if (value === undefined && !map.has(key)) {
1571                 value = callback(arg);
1572                 map.set(key, value);
1573             }
1574             return value;
1575         };
1576     }
1577     ts.memoizeOne = memoizeOne;
1578     function compose(a, b, c, d, e) {
1579         if (!!e) {
1580             var args_2 = [];
1581             for (var i = 0; i < arguments.length; i++) {
1582                 args_2[i] = arguments[i];
1583             }
1584             return function (t) { return reduceLeft(args_2, function (u, f) { return f(u); }, t); };
1585         }
1586         else if (d) {
1587             return function (t) { return d(c(b(a(t)))); };
1588         }
1589         else if (c) {
1590             return function (t) { return c(b(a(t))); };
1591         }
1592         else if (b) {
1593             return function (t) { return b(a(t)); };
1594         }
1595         else if (a) {
1596             return function (t) { return a(t); };
1597         }
1598         else {
1599             return function (t) { return t; };
1600         }
1601     }
1602     ts.compose = compose;
1603     var AssertionLevel;
1604     (function (AssertionLevel) {
1605         AssertionLevel[AssertionLevel["None"] = 0] = "None";
1606         AssertionLevel[AssertionLevel["Normal"] = 1] = "Normal";
1607         AssertionLevel[AssertionLevel["Aggressive"] = 2] = "Aggressive";
1608         AssertionLevel[AssertionLevel["VeryAggressive"] = 3] = "VeryAggressive";
1609     })(AssertionLevel = ts.AssertionLevel || (ts.AssertionLevel = {}));
1610     function equateValues(a, b) {
1611         return a === b;
1612     }
1613     ts.equateValues = equateValues;
1614     /**
1615      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1616      *
1617      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1618      * value of each code-point after applying `toUpperCase` to each string. We always map both
1619      * strings to their upper-case form as some unicode characters do not properly round-trip to
1620      * lowercase (such as `ẞ` (German sharp capital s)).
1621      */
1622     function equateStringsCaseInsensitive(a, b) {
1623         return a === b
1624             || a !== undefined
1625                 && b !== undefined
1626                 && a.toUpperCase() === b.toUpperCase();
1627     }
1628     ts.equateStringsCaseInsensitive = equateStringsCaseInsensitive;
1629     /**
1630      * Compare the equality of two strings using a case-sensitive ordinal comparison.
1631      *
1632      * Case-sensitive comparisons compare both strings one code-point at a time using the
1633      * integer value of each code-point.
1634      */
1635     function equateStringsCaseSensitive(a, b) {
1636         return equateValues(a, b);
1637     }
1638     ts.equateStringsCaseSensitive = equateStringsCaseSensitive;
1639     function compareComparableValues(a, b) {
1640         return a === b ? 0 /* EqualTo */ :
1641             a === undefined ? -1 /* LessThan */ :
1642                 b === undefined ? 1 /* GreaterThan */ :
1643                     a < b ? -1 /* LessThan */ :
1644                         1 /* GreaterThan */;
1645     }
1646     /**
1647      * Compare two numeric values for their order relative to each other.
1648      * To compare strings, use any of the `compareStrings` functions.
1649      */
1650     function compareValues(a, b) {
1651         return compareComparableValues(a, b);
1652     }
1653     ts.compareValues = compareValues;
1654     /**
1655      * Compare two TextSpans, first by `start`, then by `length`.
1656      */
1657     function compareTextSpans(a, b) {
1658         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);
1659     }
1660     ts.compareTextSpans = compareTextSpans;
1661     function min(a, b, compare) {
1662         return compare(a, b) === -1 /* LessThan */ ? a : b;
1663     }
1664     ts.min = min;
1665     /**
1666      * Compare two strings using a case-insensitive ordinal comparison.
1667      *
1668      * Ordinal comparisons are based on the difference between the unicode code points of both
1669      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1670      * comparisons provide predictable ordering, but place "a" after "B".
1671      *
1672      * Case-insensitive comparisons compare both strings one code-point at a time using the integer
1673      * value of each code-point after applying `toUpperCase` to each string. We always map both
1674      * strings to their upper-case form as some unicode characters do not properly round-trip to
1675      * lowercase (such as `ẞ` (German sharp capital s)).
1676      */
1677     function compareStringsCaseInsensitive(a, b) {
1678         if (a === b)
1679             return 0 /* EqualTo */;
1680         if (a === undefined)
1681             return -1 /* LessThan */;
1682         if (b === undefined)
1683             return 1 /* GreaterThan */;
1684         a = a.toUpperCase();
1685         b = b.toUpperCase();
1686         return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1687     }
1688     ts.compareStringsCaseInsensitive = compareStringsCaseInsensitive;
1689     /**
1690      * Compare two strings using a case-sensitive ordinal comparison.
1691      *
1692      * Ordinal comparisons are based on the difference between the unicode code points of both
1693      * strings. Characters with multiple unicode representations are considered unequal. Ordinal
1694      * comparisons provide predictable ordering, but place "a" after "B".
1695      *
1696      * Case-sensitive comparisons compare both strings one code-point at a time using the integer
1697      * value of each code-point.
1698      */
1699     function compareStringsCaseSensitive(a, b) {
1700         return compareComparableValues(a, b);
1701     }
1702     ts.compareStringsCaseSensitive = compareStringsCaseSensitive;
1703     function getStringComparer(ignoreCase) {
1704         return ignoreCase ? compareStringsCaseInsensitive : compareStringsCaseSensitive;
1705     }
1706     ts.getStringComparer = getStringComparer;
1707     /**
1708      * Creates a string comparer for use with string collation in the UI.
1709      */
1710     var createUIStringComparer = (function () {
1711         var defaultComparer;
1712         var enUSComparer;
1713         var stringComparerFactory = getStringComparerFactory();
1714         return createStringComparer;
1715         function compareWithCallback(a, b, comparer) {
1716             if (a === b)
1717                 return 0 /* EqualTo */;
1718             if (a === undefined)
1719                 return -1 /* LessThan */;
1720             if (b === undefined)
1721                 return 1 /* GreaterThan */;
1722             var value = comparer(a, b);
1723             return value < 0 ? -1 /* LessThan */ : value > 0 ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1724         }
1725         function createIntlCollatorStringComparer(locale) {
1726             // Intl.Collator.prototype.compare is bound to the collator. See NOTE in
1727             // http://www.ecma-international.org/ecma-402/2.0/#sec-Intl.Collator.prototype.compare
1728             var comparer = new Intl.Collator(locale, { usage: "sort", sensitivity: "variant" }).compare;
1729             return function (a, b) { return compareWithCallback(a, b, comparer); };
1730         }
1731         function createLocaleCompareStringComparer(locale) {
1732             // if the locale is not the default locale (`undefined`), use the fallback comparer.
1733             if (locale !== undefined)
1734                 return createFallbackStringComparer();
1735             return function (a, b) { return compareWithCallback(a, b, compareStrings); };
1736             function compareStrings(a, b) {
1737                 return a.localeCompare(b);
1738             }
1739         }
1740         function createFallbackStringComparer() {
1741             // An ordinal comparison puts "A" after "b", but for the UI we want "A" before "b".
1742             // We first sort case insensitively.  So "Aaa" will come before "baa".
1743             // Then we sort case sensitively, so "aaa" will come before "Aaa".
1744             //
1745             // For case insensitive comparisons we always map both strings to their
1746             // upper-case form as some unicode characters do not properly round-trip to
1747             // lowercase (such as `ẞ` (German sharp capital s)).
1748             return function (a, b) { return compareWithCallback(a, b, compareDictionaryOrder); };
1749             function compareDictionaryOrder(a, b) {
1750                 return compareStrings(a.toUpperCase(), b.toUpperCase()) || compareStrings(a, b);
1751             }
1752             function compareStrings(a, b) {
1753                 return a < b ? -1 /* LessThan */ : a > b ? 1 /* GreaterThan */ : 0 /* EqualTo */;
1754             }
1755         }
1756         function getStringComparerFactory() {
1757             // If the host supports Intl, we use it for comparisons using the default locale.
1758             if (typeof Intl === "object" && typeof Intl.Collator === "function") {
1759                 return createIntlCollatorStringComparer;
1760             }
1761             // If the host does not support Intl, we fall back to localeCompare.
1762             // localeCompare in Node v0.10 is just an ordinal comparison, so don't use it.
1763             if (typeof String.prototype.localeCompare === "function" &&
1764                 typeof String.prototype.toLocaleUpperCase === "function" &&
1765                 "a".localeCompare("B") < 0) {
1766                 return createLocaleCompareStringComparer;
1767             }
1768             // Otherwise, fall back to ordinal comparison:
1769             return createFallbackStringComparer;
1770         }
1771         function createStringComparer(locale) {
1772             // Hold onto common string comparers. This avoids constantly reallocating comparers during
1773             // tests.
1774             if (locale === undefined) {
1775                 return defaultComparer || (defaultComparer = stringComparerFactory(locale));
1776             }
1777             else if (locale === "en-US") {
1778                 return enUSComparer || (enUSComparer = stringComparerFactory(locale));
1779             }
1780             else {
1781                 return stringComparerFactory(locale);
1782             }
1783         }
1784     })();
1785     var uiComparerCaseSensitive;
1786     var uiLocale;
1787     function getUILocale() {
1788         return uiLocale;
1789     }
1790     ts.getUILocale = getUILocale;
1791     function setUILocale(value) {
1792         if (uiLocale !== value) {
1793             uiLocale = value;
1794             uiComparerCaseSensitive = undefined;
1795         }
1796     }
1797     ts.setUILocale = setUILocale;
1798     /**
1799      * Compare two strings in a using the case-sensitive sort behavior of the UI locale.
1800      *
1801      * Ordering is not predictable between different host locales, but is best for displaying
1802      * ordered data for UI presentation. Characters with multiple unicode representations may
1803      * be considered equal.
1804      *
1805      * Case-sensitive comparisons compare strings that differ in base characters, or
1806      * accents/diacritic marks, or case as unequal.
1807      */
1808     function compareStringsCaseSensitiveUI(a, b) {
1809         var comparer = uiComparerCaseSensitive || (uiComparerCaseSensitive = createUIStringComparer(uiLocale));
1810         return comparer(a, b);
1811     }
1812     ts.compareStringsCaseSensitiveUI = compareStringsCaseSensitiveUI;
1813     function compareProperties(a, b, key, comparer) {
1814         return a === b ? 0 /* EqualTo */ :
1815             a === undefined ? -1 /* LessThan */ :
1816                 b === undefined ? 1 /* GreaterThan */ :
1817                     comparer(a[key], b[key]);
1818     }
1819     ts.compareProperties = compareProperties;
1820     /** True is greater than false. */
1821     function compareBooleans(a, b) {
1822         return compareValues(a ? 1 : 0, b ? 1 : 0);
1823     }
1824     ts.compareBooleans = compareBooleans;
1825     /**
1826      * 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.
1827      * Names less than length 3 only check for case-insensitive equality, not Levenshtein distance.
1828      *
1829      * If there is a candidate that's the same except for case, return that.
1830      * If there is a candidate that's within one edit of the name, return that.
1831      * Otherwise, return the candidate with the smallest Levenshtein distance,
1832      *    except for candidates:
1833      *      * With no name
1834      *      * Whose length differs from the target name by more than 0.34 of the length of the name.
1835      *      * Whose levenshtein distance is more than 0.4 of the length of the name
1836      *        (0.4 allows 1 substitution/transposition for every 5 characters,
1837      *         and 1 insertion/deletion at 3 characters)
1838      */
1839     function getSpellingSuggestion(name, candidates, getName) {
1840         var maximumLengthDifference = Math.min(2, Math.floor(name.length * 0.34));
1841         var bestDistance = Math.floor(name.length * 0.4) + 1; // If the best result isn't better than this, don't bother.
1842         var bestCandidate;
1843         var justCheckExactMatches = false;
1844         var nameLowerCase = name.toLowerCase();
1845         for (var _i = 0, candidates_1 = candidates; _i < candidates_1.length; _i++) {
1846             var candidate = candidates_1[_i];
1847             var candidateName = getName(candidate);
1848             if (candidateName !== undefined && Math.abs(candidateName.length - nameLowerCase.length) <= maximumLengthDifference) {
1849                 var candidateNameLowerCase = candidateName.toLowerCase();
1850                 if (candidateNameLowerCase === nameLowerCase) {
1851                     if (candidateName === name) {
1852                         continue;
1853                     }
1854                     return candidate;
1855                 }
1856                 if (justCheckExactMatches) {
1857                     continue;
1858                 }
1859                 if (candidateName.length < 3) {
1860                     // Don't bother, user would have noticed a 2-character name having an extra character
1861                     continue;
1862                 }
1863                 // Only care about a result better than the best so far.
1864                 var distance = levenshteinWithMax(nameLowerCase, candidateNameLowerCase, bestDistance - 1);
1865                 if (distance === undefined) {
1866                     continue;
1867                 }
1868                 if (distance < 3) {
1869                     justCheckExactMatches = true;
1870                     bestCandidate = candidate;
1871                 }
1872                 else {
1873                     ts.Debug.assert(distance < bestDistance); // Else `levenshteinWithMax` should return undefined
1874                     bestDistance = distance;
1875                     bestCandidate = candidate;
1876                 }
1877             }
1878         }
1879         return bestCandidate;
1880     }
1881     ts.getSpellingSuggestion = getSpellingSuggestion;
1882     function levenshteinWithMax(s1, s2, max) {
1883         var previous = new Array(s2.length + 1);
1884         var current = new Array(s2.length + 1);
1885         /** Represents any value > max. We don't care about the particular value. */
1886         var big = max + 1;
1887         for (var i = 0; i <= s2.length; i++) {
1888             previous[i] = i;
1889         }
1890         for (var i = 1; i <= s1.length; i++) {
1891             var c1 = s1.charCodeAt(i - 1);
1892             var minJ = i > max ? i - max : 1;
1893             var maxJ = s2.length > max + i ? max + i : s2.length;
1894             current[0] = i;
1895             /** Smallest value of the matrix in the ith column. */
1896             var colMin = i;
1897             for (var j = 1; j < minJ; j++) {
1898                 current[j] = big;
1899             }
1900             for (var j = minJ; j <= maxJ; j++) {
1901                 var dist = c1 === s2.charCodeAt(j - 1)
1902                     ? previous[j - 1]
1903                     : Math.min(/*delete*/ previous[j] + 1, /*insert*/ current[j - 1] + 1, /*substitute*/ previous[j - 1] + 2);
1904                 current[j] = dist;
1905                 colMin = Math.min(colMin, dist);
1906             }
1907             for (var j = maxJ + 1; j <= s2.length; j++) {
1908                 current[j] = big;
1909             }
1910             if (colMin > max) {
1911                 // Give up -- everything in this column is > max and it can't get better in future columns.
1912                 return undefined;
1913             }
1914             var temp = previous;
1915             previous = current;
1916             current = temp;
1917         }
1918         var res = previous[s2.length];
1919         return res > max ? undefined : res;
1920     }
1921     function endsWith(str, suffix) {
1922         var expectedPos = str.length - suffix.length;
1923         return expectedPos >= 0 && str.indexOf(suffix, expectedPos) === expectedPos;
1924     }
1925     ts.endsWith = endsWith;
1926     function removeSuffix(str, suffix) {
1927         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : str;
1928     }
1929     ts.removeSuffix = removeSuffix;
1930     function tryRemoveSuffix(str, suffix) {
1931         return endsWith(str, suffix) ? str.slice(0, str.length - suffix.length) : undefined;
1932     }
1933     ts.tryRemoveSuffix = tryRemoveSuffix;
1934     function stringContains(str, substring) {
1935         return str.indexOf(substring) !== -1;
1936     }
1937     ts.stringContains = stringContains;
1938     /**
1939      * Takes a string like "jquery-min.4.2.3" and returns "jquery"
1940      */
1941     function removeMinAndVersionNumbers(fileName) {
1942         // Match a "." or "-" followed by a version number or 'min' at the end of the name
1943         var trailingMinOrVersion = /[.-]((min)|(\d+(\.\d+)*))$/;
1944         // The "min" or version may both be present, in either order, so try applying the above twice.
1945         return fileName.replace(trailingMinOrVersion, "").replace(trailingMinOrVersion, "");
1946     }
1947     ts.removeMinAndVersionNumbers = removeMinAndVersionNumbers;
1948     /** Remove an item from an array, moving everything to its right one space left. */
1949     function orderedRemoveItem(array, item) {
1950         for (var i = 0; i < array.length; i++) {
1951             if (array[i] === item) {
1952                 orderedRemoveItemAt(array, i);
1953                 return true;
1954             }
1955         }
1956         return false;
1957     }
1958     ts.orderedRemoveItem = orderedRemoveItem;
1959     /** Remove an item by index from an array, moving everything to its right one space left. */
1960     function orderedRemoveItemAt(array, index) {
1961         // This seems to be faster than either `array.splice(i, 1)` or `array.copyWithin(i, i+ 1)`.
1962         for (var i = index; i < array.length - 1; i++) {
1963             array[i] = array[i + 1];
1964         }
1965         array.pop();
1966     }
1967     ts.orderedRemoveItemAt = orderedRemoveItemAt;
1968     function unorderedRemoveItemAt(array, index) {
1969         // Fill in the "hole" left at `index`.
1970         array[index] = array[array.length - 1];
1971         array.pop();
1972     }
1973     ts.unorderedRemoveItemAt = unorderedRemoveItemAt;
1974     /** Remove the *first* occurrence of `item` from the array. */
1975     function unorderedRemoveItem(array, item) {
1976         return unorderedRemoveFirstItemWhere(array, function (element) { return element === item; });
1977     }
1978     ts.unorderedRemoveItem = unorderedRemoveItem;
1979     /** Remove the *first* element satisfying `predicate`. */
1980     function unorderedRemoveFirstItemWhere(array, predicate) {
1981         for (var i = 0; i < array.length; i++) {
1982             if (predicate(array[i])) {
1983                 unorderedRemoveItemAt(array, i);
1984                 return true;
1985             }
1986         }
1987         return false;
1988     }
1989     function createGetCanonicalFileName(useCaseSensitiveFileNames) {
1990         return useCaseSensitiveFileNames ? identity : toFileNameLowerCase;
1991     }
1992     ts.createGetCanonicalFileName = createGetCanonicalFileName;
1993     function patternText(_a) {
1994         var prefix = _a.prefix, suffix = _a.suffix;
1995         return prefix + "*" + suffix;
1996     }
1997     ts.patternText = patternText;
1998     /**
1999      * Given that candidate matches pattern, returns the text matching the '*'.
2000      * E.g.: matchedText(tryParsePattern("foo*baz"), "foobarbaz") === "bar"
2001      */
2002     function matchedText(pattern, candidate) {
2003         ts.Debug.assert(isPatternMatch(pattern, candidate));
2004         return candidate.substring(pattern.prefix.length, candidate.length - pattern.suffix.length);
2005     }
2006     ts.matchedText = matchedText;
2007     /** Return the object corresponding to the best pattern to match `candidate`. */
2008     function findBestPatternMatch(values, getPattern, candidate) {
2009         var matchedValue;
2010         // use length of prefix as betterness criteria
2011         var longestMatchPrefixLength = -1;
2012         for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
2013             var v = values_2[_i];
2014             var pattern = getPattern(v);
2015             if (isPatternMatch(pattern, candidate) && pattern.prefix.length > longestMatchPrefixLength) {
2016                 longestMatchPrefixLength = pattern.prefix.length;
2017                 matchedValue = v;
2018             }
2019         }
2020         return matchedValue;
2021     }
2022     ts.findBestPatternMatch = findBestPatternMatch;
2023     function startsWith(str, prefix) {
2024         return str.lastIndexOf(prefix, 0) === 0;
2025     }
2026     ts.startsWith = startsWith;
2027     function removePrefix(str, prefix) {
2028         return startsWith(str, prefix) ? str.substr(prefix.length) : str;
2029     }
2030     ts.removePrefix = removePrefix;
2031     function tryRemovePrefix(str, prefix, getCanonicalFileName) {
2032         if (getCanonicalFileName === void 0) { getCanonicalFileName = identity; }
2033         return startsWith(getCanonicalFileName(str), getCanonicalFileName(prefix)) ? str.substring(prefix.length) : undefined;
2034     }
2035     ts.tryRemovePrefix = tryRemovePrefix;
2036     function isPatternMatch(_a, candidate) {
2037         var prefix = _a.prefix, suffix = _a.suffix;
2038         return candidate.length >= prefix.length + suffix.length &&
2039             startsWith(candidate, prefix) &&
2040             endsWith(candidate, suffix);
2041     }
2042     function and(f, g) {
2043         return function (arg) { return f(arg) && g(arg); };
2044     }
2045     ts.and = and;
2046     function or() {
2047         var fs = [];
2048         for (var _i = 0; _i < arguments.length; _i++) {
2049             fs[_i] = arguments[_i];
2050         }
2051         return function () {
2052             var args = [];
2053             for (var _i = 0; _i < arguments.length; _i++) {
2054                 args[_i] = arguments[_i];
2055             }
2056             for (var _a = 0, fs_1 = fs; _a < fs_1.length; _a++) {
2057                 var f = fs_1[_a];
2058                 if (f.apply(void 0, args)) {
2059                     return true;
2060                 }
2061             }
2062             return false;
2063         };
2064     }
2065     ts.or = or;
2066     function not(fn) {
2067         return function () {
2068             var args = [];
2069             for (var _i = 0; _i < arguments.length; _i++) {
2070                 args[_i] = arguments[_i];
2071             }
2072             return !fn.apply(void 0, args);
2073         };
2074     }
2075     ts.not = not;
2076     function assertType(_) { }
2077     ts.assertType = assertType;
2078     function singleElementArray(t) {
2079         return t === undefined ? undefined : [t];
2080     }
2081     ts.singleElementArray = singleElementArray;
2082     function enumerateInsertsAndDeletes(newItems, oldItems, comparer, inserted, deleted, unchanged) {
2083         unchanged = unchanged || noop;
2084         var newIndex = 0;
2085         var oldIndex = 0;
2086         var newLen = newItems.length;
2087         var oldLen = oldItems.length;
2088         var hasChanges = false;
2089         while (newIndex < newLen && oldIndex < oldLen) {
2090             var newItem = newItems[newIndex];
2091             var oldItem = oldItems[oldIndex];
2092             var compareResult = comparer(newItem, oldItem);
2093             if (compareResult === -1 /* LessThan */) {
2094                 inserted(newItem);
2095                 newIndex++;
2096                 hasChanges = true;
2097             }
2098             else if (compareResult === 1 /* GreaterThan */) {
2099                 deleted(oldItem);
2100                 oldIndex++;
2101                 hasChanges = true;
2102             }
2103             else {
2104                 unchanged(oldItem, newItem);
2105                 newIndex++;
2106                 oldIndex++;
2107             }
2108         }
2109         while (newIndex < newLen) {
2110             inserted(newItems[newIndex++]);
2111             hasChanges = true;
2112         }
2113         while (oldIndex < oldLen) {
2114             deleted(oldItems[oldIndex++]);
2115             hasChanges = true;
2116         }
2117         return hasChanges;
2118     }
2119     ts.enumerateInsertsAndDeletes = enumerateInsertsAndDeletes;
2120     function fill(length, cb) {
2121         var result = Array(length);
2122         for (var i = 0; i < length; i++) {
2123             result[i] = cb(i);
2124         }
2125         return result;
2126     }
2127     ts.fill = fill;
2128     function cartesianProduct(arrays) {
2129         var result = [];
2130         cartesianProductWorker(arrays, result, /*outer*/ undefined, 0);
2131         return result;
2132     }
2133     ts.cartesianProduct = cartesianProduct;
2134     function cartesianProductWorker(arrays, result, outer, index) {
2135         for (var _i = 0, _a = arrays[index]; _i < _a.length; _i++) {
2136             var element = _a[_i];
2137             var inner = void 0;
2138             if (outer) {
2139                 inner = outer.slice();
2140                 inner.push(element);
2141             }
2142             else {
2143                 inner = [element];
2144             }
2145             if (index === arrays.length - 1) {
2146                 result.push(inner);
2147             }
2148             else {
2149                 cartesianProductWorker(arrays, result, inner, index + 1);
2150             }
2151         }
2152     }
2153     /**
2154      * Returns string left-padded with spaces or zeros until it reaches the given length.
2155      *
2156      * @param s String to pad.
2157      * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
2158      * @param padString Character to use as padding (default " ").
2159      */
2160     function padLeft(s, length, padString) {
2161         if (padString === void 0) { padString = " "; }
2162         return length <= s.length ? s : padString.repeat(length - s.length) + s;
2163     }
2164     ts.padLeft = padLeft;
2165     /**
2166      * Returns string right-padded with spaces until it reaches the given length.
2167      *
2168      * @param s String to pad.
2169      * @param length Final padded length. If less than or equal to 's.length', returns 's' unchanged.
2170      * @param padString Character to use as padding (default " ").
2171      */
2172     function padRight(s, length, padString) {
2173         if (padString === void 0) { padString = " "; }
2174         return length <= s.length ? s : s + padString.repeat(length - s.length);
2175     }
2176     ts.padRight = padRight;
2177     function takeWhile(array, predicate) {
2178         var len = array.length;
2179         var index = 0;
2180         while (index < len && predicate(array[index])) {
2181             index++;
2182         }
2183         return array.slice(0, index);
2184     }
2185     ts.takeWhile = takeWhile;
2186 })(ts || (ts = {}));
2187 /* @internal */
2188 var ts;
2189 (function (ts) {
2190     var LogLevel;
2191     (function (LogLevel) {
2192         LogLevel[LogLevel["Off"] = 0] = "Off";
2193         LogLevel[LogLevel["Error"] = 1] = "Error";
2194         LogLevel[LogLevel["Warning"] = 2] = "Warning";
2195         LogLevel[LogLevel["Info"] = 3] = "Info";
2196         LogLevel[LogLevel["Verbose"] = 4] = "Verbose";
2197     })(LogLevel = ts.LogLevel || (ts.LogLevel = {}));
2198     var Debug;
2199     (function (Debug) {
2200         var typeScriptVersion;
2201         /* eslint-disable prefer-const */
2202         var currentAssertionLevel = 0 /* None */;
2203         Debug.currentLogLevel = LogLevel.Warning;
2204         Debug.isDebugging = false;
2205         function getTypeScriptVersion() {
2206             return typeScriptVersion !== null && typeScriptVersion !== void 0 ? typeScriptVersion : (typeScriptVersion = new ts.Version(ts.version));
2207         }
2208         Debug.getTypeScriptVersion = getTypeScriptVersion;
2209         function shouldLog(level) {
2210             return Debug.currentLogLevel <= level;
2211         }
2212         Debug.shouldLog = shouldLog;
2213         function logMessage(level, s) {
2214             if (Debug.loggingHost && shouldLog(level)) {
2215                 Debug.loggingHost.log(level, s);
2216             }
2217         }
2218         function log(s) {
2219             logMessage(LogLevel.Info, s);
2220         }
2221         Debug.log = log;
2222         (function (log_1) {
2223             function error(s) {
2224                 logMessage(LogLevel.Error, s);
2225             }
2226             log_1.error = error;
2227             function warn(s) {
2228                 logMessage(LogLevel.Warning, s);
2229             }
2230             log_1.warn = warn;
2231             function log(s) {
2232                 logMessage(LogLevel.Info, s);
2233             }
2234             log_1.log = log;
2235             function trace(s) {
2236                 logMessage(LogLevel.Verbose, s);
2237             }
2238             log_1.trace = trace;
2239         })(log = Debug.log || (Debug.log = {}));
2240         var assertionCache = {};
2241         function getAssertionLevel() {
2242             return currentAssertionLevel;
2243         }
2244         Debug.getAssertionLevel = getAssertionLevel;
2245         function setAssertionLevel(level) {
2246             var prevAssertionLevel = currentAssertionLevel;
2247             currentAssertionLevel = level;
2248             if (level > prevAssertionLevel) {
2249                 // restore assertion functions for the current assertion level (see `shouldAssertFunction`).
2250                 for (var _i = 0, _a = ts.getOwnKeys(assertionCache); _i < _a.length; _i++) {
2251                     var key = _a[_i];
2252                     var cachedFunc = assertionCache[key];
2253                     if (cachedFunc !== undefined && Debug[key] !== cachedFunc.assertion && level >= cachedFunc.level) {
2254                         Debug[key] = cachedFunc;
2255                         assertionCache[key] = undefined;
2256                     }
2257                 }
2258             }
2259         }
2260         Debug.setAssertionLevel = setAssertionLevel;
2261         function shouldAssert(level) {
2262             return currentAssertionLevel >= level;
2263         }
2264         Debug.shouldAssert = shouldAssert;
2265         /**
2266          * Tests whether an assertion function should be executed. If it shouldn't, it is cached and replaced with `ts.noop`.
2267          * Replaced assertion functions are restored when `Debug.setAssertionLevel` is set to a high enough level.
2268          * @param level The minimum assertion level required.
2269          * @param name The name of the current assertion function.
2270          */
2271         function shouldAssertFunction(level, name) {
2272             if (!shouldAssert(level)) {
2273                 assertionCache[name] = { level: level, assertion: Debug[name] };
2274                 Debug[name] = ts.noop;
2275                 return false;
2276             }
2277             return true;
2278         }
2279         function fail(message, stackCrawlMark) {
2280             debugger;
2281             var e = new Error(message ? "Debug Failure. " + message : "Debug Failure.");
2282             if (Error.captureStackTrace) {
2283                 Error.captureStackTrace(e, stackCrawlMark || fail);
2284             }
2285             throw e;
2286         }
2287         Debug.fail = fail;
2288         function failBadSyntaxKind(node, message, stackCrawlMark) {
2289             return fail((message || "Unexpected node.") + "\r\nNode " + formatSyntaxKind(node.kind) + " was unexpected.", stackCrawlMark || failBadSyntaxKind);
2290         }
2291         Debug.failBadSyntaxKind = failBadSyntaxKind;
2292         function assert(expression, message, verboseDebugInfo, stackCrawlMark) {
2293             if (!expression) {
2294                 message = message ? "False expression: " + message : "False expression.";
2295                 if (verboseDebugInfo) {
2296                     message += "\r\nVerbose Debug Information: " + (typeof verboseDebugInfo === "string" ? verboseDebugInfo : verboseDebugInfo());
2297                 }
2298                 fail(message, stackCrawlMark || assert);
2299             }
2300         }
2301         Debug.assert = assert;
2302         function assertEqual(a, b, msg, msg2, stackCrawlMark) {
2303             if (a !== b) {
2304                 var message = msg ? msg2 ? msg + " " + msg2 : msg : "";
2305                 fail("Expected " + a + " === " + b + ". " + message, stackCrawlMark || assertEqual);
2306             }
2307         }
2308         Debug.assertEqual = assertEqual;
2309         function assertLessThan(a, b, msg, stackCrawlMark) {
2310             if (a >= b) {
2311                 fail("Expected " + a + " < " + b + ". " + (msg || ""), stackCrawlMark || assertLessThan);
2312             }
2313         }
2314         Debug.assertLessThan = assertLessThan;
2315         function assertLessThanOrEqual(a, b, stackCrawlMark) {
2316             if (a > b) {
2317                 fail("Expected " + a + " <= " + b, stackCrawlMark || assertLessThanOrEqual);
2318             }
2319         }
2320         Debug.assertLessThanOrEqual = assertLessThanOrEqual;
2321         function assertGreaterThanOrEqual(a, b, stackCrawlMark) {
2322             if (a < b) {
2323                 fail("Expected " + a + " >= " + b, stackCrawlMark || assertGreaterThanOrEqual);
2324             }
2325         }
2326         Debug.assertGreaterThanOrEqual = assertGreaterThanOrEqual;
2327         function assertIsDefined(value, message, stackCrawlMark) {
2328             // eslint-disable-next-line no-null/no-null
2329             if (value === undefined || value === null) {
2330                 fail(message, stackCrawlMark || assertIsDefined);
2331             }
2332         }
2333         Debug.assertIsDefined = assertIsDefined;
2334         function checkDefined(value, message, stackCrawlMark) {
2335             assertIsDefined(value, message, stackCrawlMark || checkDefined);
2336             return value;
2337         }
2338         Debug.checkDefined = checkDefined;
2339         /**
2340          * @deprecated Use `checkDefined` to check whether a value is defined inline. Use `assertIsDefined` to check whether
2341          * a value is defined at the statement level.
2342          */
2343         Debug.assertDefined = checkDefined;
2344         function assertEachIsDefined(value, message, stackCrawlMark) {
2345             for (var _i = 0, value_1 = value; _i < value_1.length; _i++) {
2346                 var v = value_1[_i];
2347                 assertIsDefined(v, message, stackCrawlMark || assertEachIsDefined);
2348             }
2349         }
2350         Debug.assertEachIsDefined = assertEachIsDefined;
2351         function checkEachDefined(value, message, stackCrawlMark) {
2352             assertEachIsDefined(value, message, stackCrawlMark || checkEachDefined);
2353             return value;
2354         }
2355         Debug.checkEachDefined = checkEachDefined;
2356         /**
2357          * @deprecated Use `checkEachDefined` to check whether the elements of an array are defined inline. Use `assertEachIsDefined` to check whether
2358          * the elements of an array are defined at the statement level.
2359          */
2360         Debug.assertEachDefined = checkEachDefined;
2361         function assertNever(member, message, stackCrawlMark) {
2362             if (message === void 0) { message = "Illegal value:"; }
2363             var detail = typeof member === "object" && ts.hasProperty(member, "kind") && ts.hasProperty(member, "pos") && formatSyntaxKind ? "SyntaxKind: " + formatSyntaxKind(member.kind) : JSON.stringify(member);
2364             return fail(message + " " + detail, stackCrawlMark || assertNever);
2365         }
2366         Debug.assertNever = assertNever;
2367         function assertEachNode(nodes, test, message, stackCrawlMark) {
2368             if (shouldAssertFunction(1 /* Normal */, "assertEachNode")) {
2369                 assert(test === undefined || ts.every(nodes, test), message || "Unexpected node.", function () { return "Node array did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertEachNode);
2370             }
2371         }
2372         Debug.assertEachNode = assertEachNode;
2373         function assertNode(node, test, message, stackCrawlMark) {
2374             if (shouldAssertFunction(1 /* Normal */, "assertNode")) {
2375                 assert(node !== undefined && (test === undefined || test(node)), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertNode);
2376             }
2377         }
2378         Debug.assertNode = assertNode;
2379         function assertNotNode(node, test, message, stackCrawlMark) {
2380             if (shouldAssertFunction(1 /* Normal */, "assertNotNode")) {
2381                 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);
2382             }
2383         }
2384         Debug.assertNotNode = assertNotNode;
2385         function assertOptionalNode(node, test, message, stackCrawlMark) {
2386             if (shouldAssertFunction(1 /* Normal */, "assertOptionalNode")) {
2387                 assert(test === undefined || node === undefined || test(node), message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " did not pass test '" + getFunctionName(test) + "'."; }, stackCrawlMark || assertOptionalNode);
2388             }
2389         }
2390         Debug.assertOptionalNode = assertOptionalNode;
2391         function assertOptionalToken(node, kind, message, stackCrawlMark) {
2392             if (shouldAssertFunction(1 /* Normal */, "assertOptionalToken")) {
2393                 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);
2394             }
2395         }
2396         Debug.assertOptionalToken = assertOptionalToken;
2397         function assertMissingNode(node, message, stackCrawlMark) {
2398             if (shouldAssertFunction(1 /* Normal */, "assertMissingNode")) {
2399                 assert(node === undefined, message || "Unexpected node.", function () { return "Node " + formatSyntaxKind(node.kind) + " was unexpected'."; }, stackCrawlMark || assertMissingNode);
2400             }
2401         }
2402         Debug.assertMissingNode = assertMissingNode;
2403         function getFunctionName(func) {
2404             if (typeof func !== "function") {
2405                 return "";
2406             }
2407             else if (func.hasOwnProperty("name")) {
2408                 return func.name;
2409             }
2410             else {
2411                 var text = Function.prototype.toString.call(func);
2412                 var match = /^function\s+([\w\$]+)\s*\(/.exec(text);
2413                 return match ? match[1] : "";
2414             }
2415         }
2416         Debug.getFunctionName = getFunctionName;
2417         function formatSymbol(symbol) {
2418             return "{ name: " + ts.unescapeLeadingUnderscores(symbol.escapedName) + "; flags: " + formatSymbolFlags(symbol.flags) + "; declarations: " + ts.map(symbol.declarations, function (node) { return formatSyntaxKind(node.kind); }) + " }";
2419         }
2420         Debug.formatSymbol = formatSymbol;
2421         /**
2422          * Formats an enum value as a string for debugging and debug assertions.
2423          */
2424         function formatEnum(value, enumObject, isFlags) {
2425             if (value === void 0) { value = 0; }
2426             var members = getEnumMembers(enumObject);
2427             if (value === 0) {
2428                 return members.length > 0 && members[0][0] === 0 ? members[0][1] : "0";
2429             }
2430             if (isFlags) {
2431                 var result = "";
2432                 var remainingFlags = value;
2433                 for (var _i = 0, members_1 = members; _i < members_1.length; _i++) {
2434                     var _a = members_1[_i], enumValue = _a[0], enumName = _a[1];
2435                     if (enumValue > value) {
2436                         break;
2437                     }
2438                     if (enumValue !== 0 && enumValue & value) {
2439                         result = "" + result + (result ? "|" : "") + enumName;
2440                         remainingFlags &= ~enumValue;
2441                     }
2442                 }
2443                 if (remainingFlags === 0) {
2444                     return result;
2445                 }
2446             }
2447             else {
2448                 for (var _b = 0, members_2 = members; _b < members_2.length; _b++) {
2449                     var _c = members_2[_b], enumValue = _c[0], enumName = _c[1];
2450                     if (enumValue === value) {
2451                         return enumName;
2452                     }
2453                 }
2454             }
2455             return value.toString();
2456         }
2457         Debug.formatEnum = formatEnum;
2458         function getEnumMembers(enumObject) {
2459             var result = [];
2460             for (var name in enumObject) {
2461                 var value = enumObject[name];
2462                 if (typeof value === "number") {
2463                     result.push([value, name]);
2464                 }
2465             }
2466             return ts.stableSort(result, function (x, y) { return ts.compareValues(x[0], y[0]); });
2467         }
2468         function formatSyntaxKind(kind) {
2469             return formatEnum(kind, ts.SyntaxKind, /*isFlags*/ false);
2470         }
2471         Debug.formatSyntaxKind = formatSyntaxKind;
2472         function formatNodeFlags(flags) {
2473             return formatEnum(flags, ts.NodeFlags, /*isFlags*/ true);
2474         }
2475         Debug.formatNodeFlags = formatNodeFlags;
2476         function formatModifierFlags(flags) {
2477             return formatEnum(flags, ts.ModifierFlags, /*isFlags*/ true);
2478         }
2479         Debug.formatModifierFlags = formatModifierFlags;
2480         function formatTransformFlags(flags) {
2481             return formatEnum(flags, ts.TransformFlags, /*isFlags*/ true);
2482         }
2483         Debug.formatTransformFlags = formatTransformFlags;
2484         function formatEmitFlags(flags) {
2485             return formatEnum(flags, ts.EmitFlags, /*isFlags*/ true);
2486         }
2487         Debug.formatEmitFlags = formatEmitFlags;
2488         function formatSymbolFlags(flags) {
2489             return formatEnum(flags, ts.SymbolFlags, /*isFlags*/ true);
2490         }
2491         Debug.formatSymbolFlags = formatSymbolFlags;
2492         function formatTypeFlags(flags) {
2493             return formatEnum(flags, ts.TypeFlags, /*isFlags*/ true);
2494         }
2495         Debug.formatTypeFlags = formatTypeFlags;
2496         function formatObjectFlags(flags) {
2497             return formatEnum(flags, ts.ObjectFlags, /*isFlags*/ true);
2498         }
2499         Debug.formatObjectFlags = formatObjectFlags;
2500         function formatFlowFlags(flags) {
2501             return formatEnum(flags, ts.FlowFlags, /*isFlags*/ true);
2502         }
2503         Debug.formatFlowFlags = formatFlowFlags;
2504         var isDebugInfoEnabled = false;
2505         var extendedDebugModule;
2506         function extendedDebug() {
2507             enableDebugInfo();
2508             if (!extendedDebugModule) {
2509                 throw new Error("Debugging helpers could not be loaded.");
2510             }
2511             return extendedDebugModule;
2512         }
2513         function printControlFlowGraph(flowNode) {
2514             return console.log(formatControlFlowGraph(flowNode));
2515         }
2516         Debug.printControlFlowGraph = printControlFlowGraph;
2517         function formatControlFlowGraph(flowNode) {
2518             return extendedDebug().formatControlFlowGraph(flowNode);
2519         }
2520         Debug.formatControlFlowGraph = formatControlFlowGraph;
2521         var flowNodeProto;
2522         function attachFlowNodeDebugInfoWorker(flowNode) {
2523             if (!("__debugFlowFlags" in flowNode)) { // eslint-disable-line no-in-operator
2524                 Object.defineProperties(flowNode, {
2525                     // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2526                     __tsDebuggerDisplay: {
2527                         value: function () {
2528                             var flowHeader = this.flags & 2 /* Start */ ? "FlowStart" :
2529                                 this.flags & 4 /* BranchLabel */ ? "FlowBranchLabel" :
2530                                     this.flags & 8 /* LoopLabel */ ? "FlowLoopLabel" :
2531                                         this.flags & 16 /* Assignment */ ? "FlowAssignment" :
2532                                             this.flags & 32 /* TrueCondition */ ? "FlowTrueCondition" :
2533                                                 this.flags & 64 /* FalseCondition */ ? "FlowFalseCondition" :
2534                                                     this.flags & 128 /* SwitchClause */ ? "FlowSwitchClause" :
2535                                                         this.flags & 256 /* ArrayMutation */ ? "FlowArrayMutation" :
2536                                                             this.flags & 512 /* Call */ ? "FlowCall" :
2537                                                                 this.flags & 1024 /* ReduceLabel */ ? "FlowReduceLabel" :
2538                                                                     this.flags & 1 /* Unreachable */ ? "FlowUnreachable" :
2539                                                                         "UnknownFlow";
2540                             var remainingFlags = this.flags & ~(2048 /* Referenced */ - 1);
2541                             return "" + flowHeader + (remainingFlags ? " (" + formatFlowFlags(remainingFlags) + ")" : "");
2542                         }
2543                     },
2544                     __debugFlowFlags: { get: function () { return formatEnum(this.flags, ts.FlowFlags, /*isFlags*/ true); } },
2545                     __debugToString: { value: function () { return formatControlFlowGraph(this); } }
2546                 });
2547             }
2548         }
2549         function attachFlowNodeDebugInfo(flowNode) {
2550             if (isDebugInfoEnabled) {
2551                 if (typeof Object.setPrototypeOf === "function") {
2552                     // if we're in es2015, attach the method to a shared prototype for `FlowNode`
2553                     // so the method doesn't show up in the watch window.
2554                     if (!flowNodeProto) {
2555                         flowNodeProto = Object.create(Object.prototype);
2556                         attachFlowNodeDebugInfoWorker(flowNodeProto);
2557                     }
2558                     Object.setPrototypeOf(flowNode, flowNodeProto);
2559                 }
2560                 else {
2561                     // not running in an es2015 environment, attach the method directly.
2562                     attachFlowNodeDebugInfoWorker(flowNode);
2563                 }
2564             }
2565         }
2566         Debug.attachFlowNodeDebugInfo = attachFlowNodeDebugInfo;
2567         var nodeArrayProto;
2568         function attachNodeArrayDebugInfoWorker(array) {
2569             if (!("__tsDebuggerDisplay" in array)) { // eslint-disable-line no-in-operator
2570                 Object.defineProperties(array, {
2571                     __tsDebuggerDisplay: {
2572                         value: function (defaultValue) {
2573                             // An `Array` with extra properties is rendered as `[A, B, prop1: 1, prop2: 2]`. Most of
2574                             // these aren't immediately useful so we trim off the `prop1: ..., prop2: ...` part from the
2575                             // formatted string.
2576                             defaultValue = String(defaultValue).replace(/(?:,[\s\w\d_]+:[^,]+)+\]$/, "]");
2577                             return "NodeArray " + defaultValue;
2578                         }
2579                     }
2580                 });
2581             }
2582         }
2583         function attachNodeArrayDebugInfo(array) {
2584             if (isDebugInfoEnabled) {
2585                 if (typeof Object.setPrototypeOf === "function") {
2586                     // if we're in es2015, attach the method to a shared prototype for `NodeArray`
2587                     // so the method doesn't show up in the watch window.
2588                     if (!nodeArrayProto) {
2589                         nodeArrayProto = Object.create(Array.prototype);
2590                         attachNodeArrayDebugInfoWorker(nodeArrayProto);
2591                     }
2592                     Object.setPrototypeOf(array, nodeArrayProto);
2593                 }
2594                 else {
2595                     // not running in an es2015 environment, attach the method directly.
2596                     attachNodeArrayDebugInfoWorker(array);
2597                 }
2598             }
2599         }
2600         Debug.attachNodeArrayDebugInfo = attachNodeArrayDebugInfo;
2601         /**
2602          * Injects debug information into frequently used types.
2603          */
2604         function enableDebugInfo() {
2605             if (isDebugInfoEnabled)
2606                 return;
2607             // avoid recomputing
2608             var weakTypeTextMap;
2609             var weakNodeTextMap;
2610             function getWeakTypeTextMap() {
2611                 if (weakTypeTextMap === undefined) {
2612                     if (typeof WeakMap === "function")
2613                         weakTypeTextMap = new WeakMap();
2614                 }
2615                 return weakTypeTextMap;
2616             }
2617             function getWeakNodeTextMap() {
2618                 if (weakNodeTextMap === undefined) {
2619                     if (typeof WeakMap === "function")
2620                         weakNodeTextMap = new WeakMap();
2621                 }
2622                 return weakNodeTextMap;
2623             }
2624             // Add additional properties in debug mode to assist with debugging.
2625             Object.defineProperties(ts.objectAllocator.getSymbolConstructor().prototype, {
2626                 // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2627                 __tsDebuggerDisplay: {
2628                     value: function () {
2629                         var symbolHeader = this.flags & 33554432 /* Transient */ ? "TransientSymbol" :
2630                             "Symbol";
2631                         var remainingSymbolFlags = this.flags & ~33554432 /* Transient */;
2632                         return symbolHeader + " '" + ts.symbolName(this) + "'" + (remainingSymbolFlags ? " (" + formatSymbolFlags(remainingSymbolFlags) + ")" : "");
2633                     }
2634                 },
2635                 __debugFlags: { get: function () { return formatSymbolFlags(this.flags); } }
2636             });
2637             Object.defineProperties(ts.objectAllocator.getTypeConstructor().prototype, {
2638                 // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2639                 __tsDebuggerDisplay: {
2640                     value: function () {
2641                         var typeHeader = this.flags & 98304 /* Nullable */ ? "NullableType" :
2642                             this.flags & 384 /* StringOrNumberLiteral */ ? "LiteralType " + JSON.stringify(this.value) :
2643                                 this.flags & 2048 /* BigIntLiteral */ ? "LiteralType " + (this.value.negative ? "-" : "") + this.value.base10Value + "n" :
2644                                     this.flags & 8192 /* UniqueESSymbol */ ? "UniqueESSymbolType" :
2645                                         this.flags & 32 /* Enum */ ? "EnumType" :
2646                                             this.flags & 67359327 /* Intrinsic */ ? "IntrinsicType " + this.intrinsicName :
2647                                                 this.flags & 1048576 /* Union */ ? "UnionType" :
2648                                                     this.flags & 2097152 /* Intersection */ ? "IntersectionType" :
2649                                                         this.flags & 4194304 /* Index */ ? "IndexType" :
2650                                                             this.flags & 8388608 /* IndexedAccess */ ? "IndexedAccessType" :
2651                                                                 this.flags & 16777216 /* Conditional */ ? "ConditionalType" :
2652                                                                     this.flags & 33554432 /* Substitution */ ? "SubstitutionType" :
2653                                                                         this.flags & 262144 /* TypeParameter */ ? "TypeParameter" :
2654                                                                             this.flags & 524288 /* Object */ ?
2655                                                                                 this.objectFlags & 3 /* ClassOrInterface */ ? "InterfaceType" :
2656                                                                                     this.objectFlags & 4 /* Reference */ ? "TypeReference" :
2657                                                                                         this.objectFlags & 8 /* Tuple */ ? "TupleType" :
2658                                                                                             this.objectFlags & 16 /* Anonymous */ ? "AnonymousType" :
2659                                                                                                 this.objectFlags & 32 /* Mapped */ ? "MappedType" :
2660                                                                                                     this.objectFlags & 2048 /* ReverseMapped */ ? "ReverseMappedType" :
2661                                                                                                         this.objectFlags & 256 /* EvolvingArray */ ? "EvolvingArrayType" :
2662                                                                                                             "ObjectType" :
2663                                                                                 "Type";
2664                         var remainingObjectFlags = this.flags & 524288 /* Object */ ? this.objectFlags & ~2367 /* ObjectTypeKindMask */ : 0;
2665                         return "" + typeHeader + (this.symbol ? " '" + ts.symbolName(this.symbol) + "'" : "") + (remainingObjectFlags ? " (" + formatObjectFlags(remainingObjectFlags) + ")" : "");
2666                     }
2667                 },
2668                 __debugFlags: { get: function () { return formatTypeFlags(this.flags); } },
2669                 __debugObjectFlags: { get: function () { return this.flags & 524288 /* Object */ ? formatObjectFlags(this.objectFlags) : ""; } },
2670                 __debugTypeToString: {
2671                     value: function () {
2672                         // avoid recomputing
2673                         var map = getWeakTypeTextMap();
2674                         var text = map === null || map === void 0 ? void 0 : map.get(this);
2675                         if (text === undefined) {
2676                             text = this.checker.typeToString(this);
2677                             map === null || map === void 0 ? void 0 : map.set(this, text);
2678                         }
2679                         return text;
2680                     }
2681                 },
2682             });
2683             var nodeConstructors = [
2684                 ts.objectAllocator.getNodeConstructor(),
2685                 ts.objectAllocator.getIdentifierConstructor(),
2686                 ts.objectAllocator.getTokenConstructor(),
2687                 ts.objectAllocator.getSourceFileConstructor()
2688             ];
2689             for (var _i = 0, nodeConstructors_1 = nodeConstructors; _i < nodeConstructors_1.length; _i++) {
2690                 var ctor = nodeConstructors_1[_i];
2691                 if (!ctor.prototype.hasOwnProperty("__debugKind")) {
2692                     Object.defineProperties(ctor.prototype, {
2693                         // for use with vscode-js-debug's new customDescriptionGenerator in launch.json
2694                         __tsDebuggerDisplay: {
2695                             value: function () {
2696                                 var nodeHeader = ts.isGeneratedIdentifier(this) ? "GeneratedIdentifier" :
2697                                     ts.isIdentifier(this) ? "Identifier '" + ts.idText(this) + "'" :
2698                                         ts.isPrivateIdentifier(this) ? "PrivateIdentifier '" + ts.idText(this) + "'" :
2699                                             ts.isStringLiteral(this) ? "StringLiteral " + JSON.stringify(this.text.length < 10 ? this.text : this.text.slice(10) + "...") :
2700                                                 ts.isNumericLiteral(this) ? "NumericLiteral " + this.text :
2701                                                     ts.isBigIntLiteral(this) ? "BigIntLiteral " + this.text + "n" :
2702                                                         ts.isTypeParameterDeclaration(this) ? "TypeParameterDeclaration" :
2703                                                             ts.isParameter(this) ? "ParameterDeclaration" :
2704                                                                 ts.isConstructorDeclaration(this) ? "ConstructorDeclaration" :
2705                                                                     ts.isGetAccessorDeclaration(this) ? "GetAccessorDeclaration" :
2706                                                                         ts.isSetAccessorDeclaration(this) ? "SetAccessorDeclaration" :
2707                                                                             ts.isCallSignatureDeclaration(this) ? "CallSignatureDeclaration" :
2708                                                                                 ts.isConstructSignatureDeclaration(this) ? "ConstructSignatureDeclaration" :
2709                                                                                     ts.isIndexSignatureDeclaration(this) ? "IndexSignatureDeclaration" :
2710                                                                                         ts.isTypePredicateNode(this) ? "TypePredicateNode" :
2711                                                                                             ts.isTypeReferenceNode(this) ? "TypeReferenceNode" :
2712                                                                                                 ts.isFunctionTypeNode(this) ? "FunctionTypeNode" :
2713                                                                                                     ts.isConstructorTypeNode(this) ? "ConstructorTypeNode" :
2714                                                                                                         ts.isTypeQueryNode(this) ? "TypeQueryNode" :
2715                                                                                                             ts.isTypeLiteralNode(this) ? "TypeLiteralNode" :
2716                                                                                                                 ts.isArrayTypeNode(this) ? "ArrayTypeNode" :
2717                                                                                                                     ts.isTupleTypeNode(this) ? "TupleTypeNode" :
2718                                                                                                                         ts.isOptionalTypeNode(this) ? "OptionalTypeNode" :
2719                                                                                                                             ts.isRestTypeNode(this) ? "RestTypeNode" :
2720                                                                                                                                 ts.isUnionTypeNode(this) ? "UnionTypeNode" :
2721                                                                                                                                     ts.isIntersectionTypeNode(this) ? "IntersectionTypeNode" :
2722                                                                                                                                         ts.isConditionalTypeNode(this) ? "ConditionalTypeNode" :
2723                                                                                                                                             ts.isInferTypeNode(this) ? "InferTypeNode" :
2724                                                                                                                                                 ts.isParenthesizedTypeNode(this) ? "ParenthesizedTypeNode" :
2725                                                                                                                                                     ts.isThisTypeNode(this) ? "ThisTypeNode" :
2726                                                                                                                                                         ts.isTypeOperatorNode(this) ? "TypeOperatorNode" :
2727                                                                                                                                                             ts.isIndexedAccessTypeNode(this) ? "IndexedAccessTypeNode" :
2728                                                                                                                                                                 ts.isMappedTypeNode(this) ? "MappedTypeNode" :
2729                                                                                                                                                                     ts.isLiteralTypeNode(this) ? "LiteralTypeNode" :
2730                                                                                                                                                                         ts.isNamedTupleMember(this) ? "NamedTupleMember" :
2731                                                                                                                                                                             ts.isImportTypeNode(this) ? "ImportTypeNode" :
2732                                                                                                                                                                                 formatSyntaxKind(this.kind);
2733                                 return "" + nodeHeader + (this.flags ? " (" + formatNodeFlags(this.flags) + ")" : "");
2734                             }
2735                         },
2736                         __debugKind: { get: function () { return formatSyntaxKind(this.kind); } },
2737                         __debugNodeFlags: { get: function () { return formatNodeFlags(this.flags); } },
2738                         __debugModifierFlags: { get: function () { return formatModifierFlags(ts.getEffectiveModifierFlagsNoCache(this)); } },
2739                         __debugTransformFlags: { get: function () { return formatTransformFlags(this.transformFlags); } },
2740                         __debugIsParseTreeNode: { get: function () { return ts.isParseTreeNode(this); } },
2741                         __debugEmitFlags: { get: function () { return formatEmitFlags(ts.getEmitFlags(this)); } },
2742                         __debugGetText: {
2743                             value: function (includeTrivia) {
2744                                 if (ts.nodeIsSynthesized(this))
2745                                     return "";
2746                                 // avoid recomputing
2747                                 var map = getWeakNodeTextMap();
2748                                 var text = map === null || map === void 0 ? void 0 : map.get(this);
2749                                 if (text === undefined) {
2750                                     var parseNode = ts.getParseTreeNode(this);
2751                                     var sourceFile = parseNode && ts.getSourceFileOfNode(parseNode);
2752                                     text = sourceFile ? ts.getSourceTextOfNodeFromSourceFile(sourceFile, parseNode, includeTrivia) : "";
2753                                     map === null || map === void 0 ? void 0 : map.set(this, text);
2754                                 }
2755                                 return text;
2756                             }
2757                         }
2758                     });
2759                 }
2760             }
2761             // attempt to load extended debugging information
2762             try {
2763                 if (ts.sys && ts.sys.require) {
2764                     var basePath = ts.getDirectoryPath(ts.resolvePath(ts.sys.getExecutingFilePath()));
2765                     var result = ts.sys.require(basePath, "./compiler-debug");
2766                     if (!result.error) {
2767                         result.module.init(ts);
2768                         extendedDebugModule = result.module;
2769                     }
2770                 }
2771             }
2772             catch (_a) {
2773                 // do nothing
2774             }
2775             isDebugInfoEnabled = true;
2776         }
2777         Debug.enableDebugInfo = enableDebugInfo;
2778         function formatDeprecationMessage(name, error, errorAfter, since, message) {
2779             var deprecationMessage = error ? "DeprecationError: " : "DeprecationWarning: ";
2780             deprecationMessage += "'" + name + "' ";
2781             deprecationMessage += since ? "has been deprecated since v" + since : "is deprecated";
2782             deprecationMessage += error ? " and can no longer be used." : errorAfter ? " and will no longer be usable after v" + errorAfter + "." : ".";
2783             deprecationMessage += message ? " " + ts.formatStringFromArgs(message, [name], 0) : "";
2784             return deprecationMessage;
2785         }
2786         function createErrorDeprecation(name, errorAfter, since, message) {
2787             var deprecationMessage = formatDeprecationMessage(name, /*error*/ true, errorAfter, since, message);
2788             return function () {
2789                 throw new TypeError(deprecationMessage);
2790             };
2791         }
2792         function createWarningDeprecation(name, errorAfter, since, message) {
2793             var hasWrittenDeprecation = false;
2794             return function () {
2795                 if (!hasWrittenDeprecation) {
2796                     log.warn(formatDeprecationMessage(name, /*error*/ false, errorAfter, since, message));
2797                     hasWrittenDeprecation = true;
2798                 }
2799             };
2800         }
2801         function createDeprecation(name, options) {
2802             var _a, _b;
2803             if (options === void 0) { options = {}; }
2804             var version = typeof options.typeScriptVersion === "string" ? new ts.Version(options.typeScriptVersion) : (_a = options.typeScriptVersion) !== null && _a !== void 0 ? _a : getTypeScriptVersion();
2805             var errorAfter = typeof options.errorAfter === "string" ? new ts.Version(options.errorAfter) : options.errorAfter;
2806             var warnAfter = typeof options.warnAfter === "string" ? new ts.Version(options.warnAfter) : options.warnAfter;
2807             var since = typeof options.since === "string" ? new ts.Version(options.since) : (_b = options.since) !== null && _b !== void 0 ? _b : warnAfter;
2808             var error = options.error || errorAfter && version.compareTo(errorAfter) <= 0;
2809             var warn = !warnAfter || version.compareTo(warnAfter) >= 0;
2810             return error ? createErrorDeprecation(name, errorAfter, since, options.message) :
2811                 warn ? createWarningDeprecation(name, errorAfter, since, options.message) :
2812                     ts.noop;
2813         }
2814         function wrapFunction(deprecation, func) {
2815             return function () {
2816                 deprecation();
2817                 return func.apply(this, arguments);
2818             };
2819         }
2820         function deprecate(func, options) {
2821             var deprecation = createDeprecation(getFunctionName(func), options);
2822             return wrapFunction(deprecation, func);
2823         }
2824         Debug.deprecate = deprecate;
2825     })(Debug = ts.Debug || (ts.Debug = {}));
2826 })(ts || (ts = {}));
2827 /* @internal */
2828 var ts;
2829 (function (ts) {
2830     // https://semver.org/#spec-item-2
2831     // > A normal version number MUST take the form X.Y.Z where X, Y, and Z are non-negative
2832     // > integers, and MUST NOT contain leading zeroes. X is the major version, Y is the minor
2833     // > version, and Z is the patch version. Each element MUST increase numerically.
2834     //
2835     // NOTE: We differ here in that we allow X and X.Y, with missing parts having the default
2836     // value of `0`.
2837     var versionRegExp = /^(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*)(?:\-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
2838     // https://semver.org/#spec-item-9
2839     // > A pre-release version MAY be denoted by appending a hyphen and a series of dot separated
2840     // > identifiers immediately following the patch version. Identifiers MUST comprise only ASCII
2841     // > alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty. Numeric identifiers
2842     // > MUST NOT include leading zeroes.
2843     var prereleaseRegExp = /^(?:0|[1-9]\d*|[a-z-][a-z0-9-]*)(?:\.(?:0|[1-9]\d*|[a-z-][a-z0-9-]*))*$/i;
2844     // https://semver.org/#spec-item-10
2845     // > Build metadata MAY be denoted by appending a plus sign and a series of dot separated
2846     // > identifiers immediately following the patch or pre-release version. Identifiers MUST
2847     // > comprise only ASCII alphanumerics and hyphen [0-9A-Za-z-]. Identifiers MUST NOT be empty.
2848     var buildRegExp = /^[a-z0-9-]+(?:\.[a-z0-9-]+)*$/i;
2849     // https://semver.org/#spec-item-9
2850     // > Numeric identifiers MUST NOT include leading zeroes.
2851     var numericIdentifierRegExp = /^(0|[1-9]\d*)$/;
2852     /**
2853      * Describes a precise semantic version number, https://semver.org
2854      */
2855     var Version = /** @class */ (function () {
2856         function Version(major, minor, patch, prerelease, build) {
2857             if (minor === void 0) { minor = 0; }
2858             if (patch === void 0) { patch = 0; }
2859             if (prerelease === void 0) { prerelease = ""; }
2860             if (build === void 0) { build = ""; }
2861             if (typeof major === "string") {
2862                 var result = ts.Debug.checkDefined(tryParseComponents(major), "Invalid version");
2863                 (major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build);
2864             }
2865             ts.Debug.assert(major >= 0, "Invalid argument: major");
2866             ts.Debug.assert(minor >= 0, "Invalid argument: minor");
2867             ts.Debug.assert(patch >= 0, "Invalid argument: patch");
2868             ts.Debug.assert(!prerelease || prereleaseRegExp.test(prerelease), "Invalid argument: prerelease");
2869             ts.Debug.assert(!build || buildRegExp.test(build), "Invalid argument: build");
2870             this.major = major;
2871             this.minor = minor;
2872             this.patch = patch;
2873             this.prerelease = prerelease ? prerelease.split(".") : ts.emptyArray;
2874             this.build = build ? build.split(".") : ts.emptyArray;
2875         }
2876         Version.tryParse = function (text) {
2877             var result = tryParseComponents(text);
2878             if (!result)
2879                 return undefined;
2880             var major = result.major, minor = result.minor, patch = result.patch, prerelease = result.prerelease, build = result.build;
2881             return new Version(major, minor, patch, prerelease, build);
2882         };
2883         Version.prototype.compareTo = function (other) {
2884             // https://semver.org/#spec-item-11
2885             // > Precedence is determined by the first difference when comparing each of these
2886             // > identifiers from left to right as follows: Major, minor, and patch versions are
2887             // > always compared numerically.
2888             //
2889             // https://semver.org/#spec-item-11
2890             // > Precedence for two pre-release versions with the same major, minor, and patch version
2891             // > MUST be determined by comparing each dot separated identifier from left to right until
2892             // > a difference is found [...]
2893             //
2894             // https://semver.org/#spec-item-11
2895             // > Build metadata does not figure into precedence
2896             if (this === other)
2897                 return 0 /* EqualTo */;
2898             if (other === undefined)
2899                 return 1 /* GreaterThan */;
2900             return ts.compareValues(this.major, other.major)
2901                 || ts.compareValues(this.minor, other.minor)
2902                 || ts.compareValues(this.patch, other.patch)
2903                 || comparePrereleaseIdentifiers(this.prerelease, other.prerelease);
2904         };
2905         Version.prototype.increment = function (field) {
2906             switch (field) {
2907                 case "major": return new Version(this.major + 1, 0, 0);
2908                 case "minor": return new Version(this.major, this.minor + 1, 0);
2909                 case "patch": return new Version(this.major, this.minor, this.patch + 1);
2910                 default: return ts.Debug.assertNever(field);
2911             }
2912         };
2913         Version.prototype.toString = function () {
2914             var result = this.major + "." + this.minor + "." + this.patch;
2915             if (ts.some(this.prerelease))
2916                 result += "-" + this.prerelease.join(".");
2917             if (ts.some(this.build))
2918                 result += "+" + this.build.join(".");
2919             return result;
2920         };
2921         Version.zero = new Version(0, 0, 0);
2922         return Version;
2923     }());
2924     ts.Version = Version;
2925     function tryParseComponents(text) {
2926         var match = versionRegExp.exec(text);
2927         if (!match)
2928             return undefined;
2929         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;
2930         if (prerelease && !prereleaseRegExp.test(prerelease))
2931             return undefined;
2932         if (build && !buildRegExp.test(build))
2933             return undefined;
2934         return {
2935             major: parseInt(major, 10),
2936             minor: parseInt(minor, 10),
2937             patch: parseInt(patch, 10),
2938             prerelease: prerelease,
2939             build: build
2940         };
2941     }
2942     function comparePrereleaseIdentifiers(left, right) {
2943         // https://semver.org/#spec-item-11
2944         // > When major, minor, and patch are equal, a pre-release version has lower precedence
2945         // > than a normal version.
2946         if (left === right)
2947             return 0 /* EqualTo */;
2948         if (left.length === 0)
2949             return right.length === 0 ? 0 /* EqualTo */ : 1 /* GreaterThan */;
2950         if (right.length === 0)
2951             return -1 /* LessThan */;
2952         // https://semver.org/#spec-item-11
2953         // > Precedence for two pre-release versions with the same major, minor, and patch version
2954         // > MUST be determined by comparing each dot separated identifier from left to right until
2955         // > a difference is found [...]
2956         var length = Math.min(left.length, right.length);
2957         for (var i = 0; i < length; i++) {
2958             var leftIdentifier = left[i];
2959             var rightIdentifier = right[i];
2960             if (leftIdentifier === rightIdentifier)
2961                 continue;
2962             var leftIsNumeric = numericIdentifierRegExp.test(leftIdentifier);
2963             var rightIsNumeric = numericIdentifierRegExp.test(rightIdentifier);
2964             if (leftIsNumeric || rightIsNumeric) {
2965                 // https://semver.org/#spec-item-11
2966                 // > Numeric identifiers always have lower precedence than non-numeric identifiers.
2967                 if (leftIsNumeric !== rightIsNumeric)
2968                     return leftIsNumeric ? -1 /* LessThan */ : 1 /* GreaterThan */;
2969                 // https://semver.org/#spec-item-11
2970                 // > identifiers consisting of only digits are compared numerically
2971                 var result = ts.compareValues(+leftIdentifier, +rightIdentifier);
2972                 if (result)
2973                     return result;
2974             }
2975             else {
2976                 // https://semver.org/#spec-item-11
2977                 // > identifiers with letters or hyphens are compared lexically in ASCII sort order.
2978                 var result = ts.compareStringsCaseSensitive(leftIdentifier, rightIdentifier);
2979                 if (result)
2980                     return result;
2981             }
2982         }
2983         // https://semver.org/#spec-item-11
2984         // > A larger set of pre-release fields has a higher precedence than a smaller set, if all
2985         // > of the preceding identifiers are equal.
2986         return ts.compareValues(left.length, right.length);
2987     }
2988     /**
2989      * Describes a semantic version range, per https://github.com/npm/node-semver#ranges
2990      */
2991     var VersionRange = /** @class */ (function () {
2992         function VersionRange(spec) {
2993             this._alternatives = spec ? ts.Debug.checkDefined(parseRange(spec), "Invalid range spec.") : ts.emptyArray;
2994         }
2995         VersionRange.tryParse = function (text) {
2996             var sets = parseRange(text);
2997             if (sets) {
2998                 var range = new VersionRange("");
2999                 range._alternatives = sets;
3000                 return range;
3001             }
3002             return undefined;
3003         };
3004         VersionRange.prototype.test = function (version) {
3005             if (typeof version === "string")
3006                 version = new Version(version);
3007             return testDisjunction(version, this._alternatives);
3008         };
3009         VersionRange.prototype.toString = function () {
3010             return formatDisjunction(this._alternatives);
3011         };
3012         return VersionRange;
3013     }());
3014     ts.VersionRange = VersionRange;
3015     // https://github.com/npm/node-semver#range-grammar
3016     //
3017     // range-set    ::= range ( logical-or range ) *
3018     // range        ::= hyphen | simple ( ' ' simple ) * | ''
3019     // logical-or   ::= ( ' ' ) * '||' ( ' ' ) *
3020     var logicalOrRegExp = /\s*\|\|\s*/g;
3021     var whitespaceRegExp = /\s+/g;
3022     // https://github.com/npm/node-semver#range-grammar
3023     //
3024     // partial      ::= xr ( '.' xr ( '.' xr qualifier ? )? )?
3025     // xr           ::= 'x' | 'X' | '*' | nr
3026     // nr           ::= '0' | ['1'-'9'] ( ['0'-'9'] ) *
3027     // qualifier    ::= ( '-' pre )? ( '+' build )?
3028     // pre          ::= parts
3029     // build        ::= parts
3030     // parts        ::= part ( '.' part ) *
3031     // part         ::= nr | [-0-9A-Za-z]+
3032     var partialRegExp = /^([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:\.([xX*0]|[1-9]\d*)(?:-([a-z0-9-.]+))?(?:\+([a-z0-9-.]+))?)?)?$/i;
3033     // https://github.com/npm/node-semver#range-grammar
3034     //
3035     // hyphen       ::= partial ' - ' partial
3036     var hyphenRegExp = /^\s*([a-z0-9-+.*]+)\s+-\s+([a-z0-9-+.*]+)\s*$/i;
3037     // https://github.com/npm/node-semver#range-grammar
3038     //
3039     // simple       ::= primitive | partial | tilde | caret
3040     // primitive    ::= ( '<' | '>' | '>=' | '<=' | '=' ) partial
3041     // tilde        ::= '~' partial
3042     // caret        ::= '^' partial
3043     var rangeRegExp = /^\s*(~|\^|<|<=|>|>=|=)?\s*([a-z0-9-+.*]+)$/i;
3044     function parseRange(text) {
3045         var alternatives = [];
3046         for (var _i = 0, _a = text.trim().split(logicalOrRegExp); _i < _a.length; _i++) {
3047             var range = _a[_i];
3048             if (!range)
3049                 continue;
3050             var comparators = [];
3051             var match = hyphenRegExp.exec(range);
3052             if (match) {
3053                 if (!parseHyphen(match[1], match[2], comparators))
3054                     return undefined;
3055             }
3056             else {
3057                 for (var _b = 0, _c = range.split(whitespaceRegExp); _b < _c.length; _b++) {
3058                     var simple = _c[_b];
3059                     var match_1 = rangeRegExp.exec(simple);
3060                     if (!match_1 || !parseComparator(match_1[1], match_1[2], comparators))
3061                         return undefined;
3062                 }
3063             }
3064             alternatives.push(comparators);
3065         }
3066         return alternatives;
3067     }
3068     function parsePartial(text) {
3069         var match = partialRegExp.exec(text);
3070         if (!match)
3071             return undefined;
3072         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];
3073         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);
3074         return { version: version, major: major, minor: minor, patch: patch };
3075     }
3076     function parseHyphen(left, right, comparators) {
3077         var leftResult = parsePartial(left);
3078         if (!leftResult)
3079             return false;
3080         var rightResult = parsePartial(right);
3081         if (!rightResult)
3082             return false;
3083         if (!isWildcard(leftResult.major)) {
3084             comparators.push(createComparator(">=", leftResult.version));
3085         }
3086         if (!isWildcard(rightResult.major)) {
3087             comparators.push(isWildcard(rightResult.minor) ? createComparator("<", rightResult.version.increment("major")) :
3088                 isWildcard(rightResult.patch) ? createComparator("<", rightResult.version.increment("minor")) :
3089                     createComparator("<=", rightResult.version));
3090         }
3091         return true;
3092     }
3093     function parseComparator(operator, text, comparators) {
3094         var result = parsePartial(text);
3095         if (!result)
3096             return false;
3097         var version = result.version, major = result.major, minor = result.minor, patch = result.patch;
3098         if (!isWildcard(major)) {
3099             switch (operator) {
3100                 case "~":
3101                     comparators.push(createComparator(">=", version));
3102                     comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" :
3103                         "minor")));
3104                     break;
3105                 case "^":
3106                     comparators.push(createComparator(">=", version));
3107                     comparators.push(createComparator("<", version.increment(version.major > 0 || isWildcard(minor) ? "major" :
3108                         version.minor > 0 || isWildcard(patch) ? "minor" :
3109                             "patch")));
3110                     break;
3111                 case "<":
3112                 case ">=":
3113                     comparators.push(createComparator(operator, version));
3114                     break;
3115                 case "<=":
3116                 case ">":
3117                     comparators.push(isWildcard(minor) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("major")) :
3118                         isWildcard(patch) ? createComparator(operator === "<=" ? "<" : ">=", version.increment("minor")) :
3119                             createComparator(operator, version));
3120                     break;
3121                 case "=":
3122                 case undefined:
3123                     if (isWildcard(minor) || isWildcard(patch)) {
3124                         comparators.push(createComparator(">=", version));
3125                         comparators.push(createComparator("<", version.increment(isWildcard(minor) ? "major" : "minor")));
3126                     }
3127                     else {
3128                         comparators.push(createComparator("=", version));
3129                     }
3130                     break;
3131                 default:
3132                     // unrecognized
3133                     return false;
3134             }
3135         }
3136         else if (operator === "<" || operator === ">") {
3137             comparators.push(createComparator("<", Version.zero));
3138         }
3139         return true;
3140     }
3141     function isWildcard(part) {
3142         return part === "*" || part === "x" || part === "X";
3143     }
3144     function createComparator(operator, operand) {
3145         return { operator: operator, operand: operand };
3146     }
3147     function testDisjunction(version, alternatives) {
3148         // an empty disjunction is treated as "*" (all versions)
3149         if (alternatives.length === 0)
3150             return true;
3151         for (var _i = 0, alternatives_1 = alternatives; _i < alternatives_1.length; _i++) {
3152             var alternative = alternatives_1[_i];
3153             if (testAlternative(version, alternative))
3154                 return true;
3155         }
3156         return false;
3157     }
3158     function testAlternative(version, comparators) {
3159         for (var _i = 0, comparators_1 = comparators; _i < comparators_1.length; _i++) {
3160             var comparator = comparators_1[_i];
3161             if (!testComparator(version, comparator.operator, comparator.operand))
3162                 return false;
3163         }
3164         return true;
3165     }
3166     function testComparator(version, operator, operand) {
3167         var cmp = version.compareTo(operand);
3168         switch (operator) {
3169             case "<": return cmp < 0;
3170             case "<=": return cmp <= 0;
3171             case ">": return cmp > 0;
3172             case ">=": return cmp >= 0;
3173             case "=": return cmp === 0;
3174             default: return ts.Debug.assertNever(operator);
3175         }
3176     }
3177     function formatDisjunction(alternatives) {
3178         return ts.map(alternatives, formatAlternative).join(" || ") || "*";
3179     }
3180     function formatAlternative(comparators) {
3181         return ts.map(comparators, formatComparator).join(" ");
3182     }
3183     function formatComparator(comparator) {
3184         return "" + comparator.operator + comparator.operand;
3185     }
3186 })(ts || (ts = {}));
3187 /*@internal*/
3188 var ts;
3189 (function (ts) {
3190     // The following definitions provide the minimum compatible support for the Web Performance User Timings API
3191     // between browsers and NodeJS:
3192     // eslint-disable-next-line @typescript-eslint/naming-convention
3193     function hasRequiredAPI(performance, PerformanceObserver) {
3194         return typeof performance === "object" &&
3195             typeof performance.timeOrigin === "number" &&
3196             typeof performance.mark === "function" &&
3197             typeof performance.measure === "function" &&
3198             typeof performance.now === "function" &&
3199             typeof PerformanceObserver === "function";
3200     }
3201     function tryGetWebPerformanceHooks() {
3202         if (typeof performance === "object" &&
3203             typeof PerformanceObserver === "function" &&
3204             hasRequiredAPI(performance, PerformanceObserver)) {
3205             return {
3206                 performance: performance,
3207                 PerformanceObserver: PerformanceObserver
3208             };
3209         }
3210     }
3211     function tryGetNodePerformanceHooks() {
3212         if (typeof module === "object" && typeof require === "function") {
3213             try {
3214                 var _a = require("perf_hooks"), performance_1 = _a.performance, PerformanceObserver_1 = _a.PerformanceObserver;
3215                 if (hasRequiredAPI(performance_1, PerformanceObserver_1)) {
3216                     // There is a bug in Node's performance.measure prior to 12.16.3/13.13.0 that does not
3217                     // match the Web Performance API specification. Node's implementation did not allow
3218                     // optional `start` and `end` arguments for `performance.measure`.
3219                     // See https://github.com/nodejs/node/pull/32651 for more information.
3220                     var version_1 = new ts.Version(process.versions.node);
3221                     var range = new ts.VersionRange("<12.16.3 || 13 <13.13");
3222                     if (range.test(version_1)) {
3223                         return {
3224                             performance: {
3225                                 get timeOrigin() { return performance_1.timeOrigin; },
3226                                 now: function () { return performance_1.now(); },
3227                                 mark: function (name) { return performance_1.mark(name); },
3228                                 measure: function (name, start, end) {
3229                                     if (start === void 0) { start = "nodeStart"; }
3230                                     if (end === undefined) {
3231                                         end = "__performance.measure-fix__";
3232                                         performance_1.mark(end);
3233                                     }
3234                                     performance_1.measure(name, start, end);
3235                                     if (end === "__performance.measure-fix__") {
3236                                         performance_1.clearMarks("__performance.measure-fix__");
3237                                     }
3238                                 }
3239                             },
3240                             PerformanceObserver: PerformanceObserver_1
3241                         };
3242                     }
3243                     return {
3244                         performance: performance_1,
3245                         PerformanceObserver: PerformanceObserver_1
3246                     };
3247                 }
3248             }
3249             catch (_b) {
3250                 // ignore errors
3251             }
3252         }
3253     }
3254     // Unlike with the native Map/Set 'tryGet' functions in corePublic.ts, we eagerly evaluate these
3255     // since we will need them for `timestamp`, below.
3256     var nativePerformanceHooks = tryGetWebPerformanceHooks() || tryGetNodePerformanceHooks();
3257     var nativePerformance = nativePerformanceHooks === null || nativePerformanceHooks === void 0 ? void 0 : nativePerformanceHooks.performance;
3258     function tryGetNativePerformanceHooks() {
3259         return nativePerformanceHooks;
3260     }
3261     ts.tryGetNativePerformanceHooks = tryGetNativePerformanceHooks;
3262     /** Gets a timestamp with (at least) ms resolution */
3263     ts.timestamp = nativePerformance ? function () { return nativePerformance.now(); } :
3264         Date.now ? Date.now :
3265             function () { return +(new Date()); };
3266 })(ts || (ts = {}));
3267 /*@internal*/
3268 /** Performance measurements for the compiler. */
3269 var ts;
3270 (function (ts) {
3271     var performance;
3272     (function (performance) {
3273         var perfHooks;
3274         var perfObserver;
3275         // when set, indicates the implementation of `Performance` to use for user timing.
3276         // when unset, indicates user timing is unavailable or disabled.
3277         var performanceImpl;
3278         function createTimerIf(condition, measureName, startMarkName, endMarkName) {
3279             return condition ? createTimer(measureName, startMarkName, endMarkName) : performance.nullTimer;
3280         }
3281         performance.createTimerIf = createTimerIf;
3282         function createTimer(measureName, startMarkName, endMarkName) {
3283             var enterCount = 0;
3284             return {
3285                 enter: enter,
3286                 exit: exit
3287             };
3288             function enter() {
3289                 if (++enterCount === 1) {
3290                     mark(startMarkName);
3291                 }
3292             }
3293             function exit() {
3294                 if (--enterCount === 0) {
3295                     mark(endMarkName);
3296                     measure(measureName, startMarkName, endMarkName);
3297                 }
3298                 else if (enterCount < 0) {
3299                     ts.Debug.fail("enter/exit count does not match.");
3300                 }
3301             }
3302         }
3303         performance.createTimer = createTimer;
3304         performance.nullTimer = { enter: ts.noop, exit: ts.noop };
3305         var counts = new ts.Map();
3306         var durations = new ts.Map();
3307         /**
3308          * Marks a performance event.
3309          *
3310          * @param markName The name of the mark.
3311          */
3312         function mark(markName) {
3313             performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.mark(markName);
3314         }
3315         performance.mark = mark;
3316         /**
3317          * Adds a performance measurement with the specified name.
3318          *
3319          * @param measureName The name of the performance measurement.
3320          * @param startMarkName The name of the starting mark. If not supplied, the point at which the
3321          *      profiler was enabled is used.
3322          * @param endMarkName The name of the ending mark. If not supplied, the current timestamp is
3323          *      used.
3324          */
3325         function measure(measureName, startMarkName, endMarkName) {
3326             performanceImpl === null || performanceImpl === void 0 ? void 0 : performanceImpl.measure(measureName, startMarkName, endMarkName);
3327         }
3328         performance.measure = measure;
3329         /**
3330          * Gets the number of times a marker was encountered.
3331          *
3332          * @param markName The name of the mark.
3333          */
3334         function getCount(markName) {
3335             return counts.get(markName) || 0;
3336         }
3337         performance.getCount = getCount;
3338         /**
3339          * Gets the total duration of all measurements with the supplied name.
3340          *
3341          * @param measureName The name of the measure whose durations should be accumulated.
3342          */
3343         function getDuration(measureName) {
3344             return durations.get(measureName) || 0;
3345         }
3346         performance.getDuration = getDuration;
3347         /**
3348          * Iterate over each measure, performing some action
3349          *
3350          * @param cb The action to perform for each measure
3351          */
3352         function forEachMeasure(cb) {
3353             durations.forEach(function (duration, measureName) { return cb(measureName, duration); });
3354         }
3355         performance.forEachMeasure = forEachMeasure;
3356         /**
3357          * Indicates whether the performance API is enabled.
3358          */
3359         function isEnabled() {
3360             return !!performanceImpl;
3361         }
3362         performance.isEnabled = isEnabled;
3363         /** Enables (and resets) performance measurements for the compiler. */
3364         function enable() {
3365             if (!performanceImpl) {
3366                 perfHooks || (perfHooks = ts.tryGetNativePerformanceHooks());
3367                 if (!perfHooks)
3368                     return false;
3369                 perfObserver || (perfObserver = new perfHooks.PerformanceObserver(updateStatisticsFromList));
3370                 perfObserver.observe({ entryTypes: ["mark", "measure"] });
3371                 performanceImpl = perfHooks.performance;
3372             }
3373             return true;
3374         }
3375         performance.enable = enable;
3376         /** Disables performance measurements for the compiler. */
3377         function disable() {
3378             perfObserver === null || perfObserver === void 0 ? void 0 : perfObserver.disconnect();
3379             performanceImpl = undefined;
3380             counts.clear();
3381             durations.clear();
3382         }
3383         performance.disable = disable;
3384         function updateStatisticsFromList(list) {
3385             for (var _i = 0, _a = list.getEntriesByType("mark"); _i < _a.length; _i++) {
3386                 var mark_1 = _a[_i];
3387                 counts.set(mark_1.name, (counts.get(mark_1.name) || 0) + 1);
3388             }
3389             for (var _b = 0, _c = list.getEntriesByType("measure"); _b < _c.length; _b++) {
3390                 var measure_1 = _c[_b];
3391                 durations.set(measure_1.name, (durations.get(measure_1.name) || 0) + measure_1.duration);
3392             }
3393         }
3394     })(performance = ts.performance || (ts.performance = {}));
3395 })(ts || (ts = {}));
3396 /* @internal */
3397 var ts;
3398 (function (ts) {
3399     var _a;
3400     var nullLogger = {
3401         logEvent: ts.noop,
3402         logErrEvent: ts.noop,
3403         logPerfEvent: ts.noop,
3404         logInfoEvent: ts.noop,
3405         logStartCommand: ts.noop,
3406         logStopCommand: ts.noop,
3407         logStartUpdateProgram: ts.noop,
3408         logStopUpdateProgram: ts.noop,
3409         logStartUpdateGraph: ts.noop,
3410         logStopUpdateGraph: ts.noop,
3411         logStartResolveModule: ts.noop,
3412         logStopResolveModule: ts.noop,
3413         logStartParseSourceFile: ts.noop,
3414         logStopParseSourceFile: ts.noop,
3415         logStartReadFile: ts.noop,
3416         logStopReadFile: ts.noop,
3417         logStartBindFile: ts.noop,
3418         logStopBindFile: ts.noop,
3419         logStartScheduledOperation: ts.noop,
3420         logStopScheduledOperation: ts.noop,
3421     };
3422     // Load optional module to enable Event Tracing for Windows
3423     // See https://github.com/microsoft/typescript-etw for more information
3424     var etwModule;
3425     try {
3426         var etwModulePath = (_a = process.env.TS_ETW_MODULE_PATH) !== null && _a !== void 0 ? _a : "./node_modules/@microsoft/typescript-etw";
3427         // require() will throw an exception if the module is not found
3428         // It may also return undefined if not installed properly
3429         etwModule = require(etwModulePath);
3430     }
3431     catch (e) {
3432         etwModule = undefined;
3433     }
3434     /** Performance logger that will generate ETW events if possible - check for `logEvent` member, as `etwModule` will be `{}` when browserified */
3435     ts.perfLogger = etwModule && etwModule.logEvent ? etwModule : nullLogger;
3436 })(ts || (ts = {}));
3437 /*@internal*/
3438 /** Tracing events for the compiler. */
3439 var ts;
3440 (function (ts) {
3441     var tracing;
3442     (function (tracing) {
3443         var fs;
3444         var traceCount = 0;
3445         var traceFd;
3446         var legendPath;
3447         var legend = [];
3448         /** Starts tracing for the given project (unless the `fs` module is unavailable). */
3449         function startTracing(configFilePath, traceDir, isBuildMode) {
3450             ts.Debug.assert(!traceFd, "Tracing already started");
3451             if (fs === undefined) {
3452                 try {
3453                     fs = require("fs");
3454                 }
3455                 catch (_a) {
3456                     fs = false;
3457                 }
3458             }
3459             if (!fs) {
3460                 return;
3461             }
3462             if (legendPath === undefined) {
3463                 legendPath = ts.combinePaths(traceDir, "legend.json");
3464             }
3465             // Note that writing will fail later on if it exists and is not a directory
3466             if (!fs.existsSync(traceDir)) {
3467                 fs.mkdirSync(traceDir, { recursive: true });
3468             }
3469             var countPart = isBuildMode ? "." + ++traceCount : "";
3470             var tracePath = ts.combinePaths(traceDir, "trace" + countPart + ".json");
3471             var typesPath = ts.combinePaths(traceDir, "types" + countPart + ".json");
3472             legend.push({
3473                 configFilePath: configFilePath,
3474                 tracePath: tracePath,
3475                 typesPath: typesPath,
3476             });
3477             traceFd = fs.openSync(tracePath, "w");
3478             // Start with a prefix that contains some metadata that the devtools profiler expects (also avoids a warning on import)
3479             var meta = { cat: "__metadata", ph: "M", ts: 1000 * ts.timestamp(), pid: 1, tid: 1 };
3480             fs.writeSync(traceFd, "[\n"
3481                 + [__assign({ name: "process_name", args: { name: "tsc" } }, meta), __assign({ name: "thread_name", args: { name: "Main" } }, meta), __assign(__assign({ name: "TracingStartedInBrowser" }, meta), { cat: "disabled-by-default-devtools.timeline" })]
3482                     .map(function (v) { return JSON.stringify(v); }).join(",\n"));
3483         }
3484         tracing.startTracing = startTracing;
3485         /** Stops tracing for the in-progress project and dumps the type catalog (unless the `fs` module is unavailable). */
3486         function stopTracing(typeCatalog) {
3487             if (!traceFd) {
3488                 ts.Debug.assert(!fs, "Tracing is not in progress");
3489                 return;
3490             }
3491             ts.Debug.assert(fs);
3492             fs.writeSync(traceFd, "\n]\n");
3493             fs.closeSync(traceFd);
3494             traceFd = undefined;
3495             if (typeCatalog) {
3496                 dumpTypes(typeCatalog);
3497             }
3498             else {
3499                 // We pre-computed this path for convenience, but clear it
3500                 // now that the file won't be created.
3501                 legend[legend.length - 1].typesPath = undefined;
3502             }
3503         }
3504         tracing.stopTracing = stopTracing;
3505         function isTracing() {
3506             return !!traceFd;
3507         }
3508         tracing.isTracing = isTracing;
3509         var Phase;
3510         (function (Phase) {
3511             Phase["Parse"] = "parse";
3512             Phase["Program"] = "program";
3513             Phase["Bind"] = "bind";
3514             Phase["Check"] = "check";
3515             Phase["Emit"] = "emit";
3516         })(Phase = tracing.Phase || (tracing.Phase = {}));
3517         /** Note: `push`/`pop` should be used by default.
3518          * `begin`/`end` are for special cases where we need the data point even if the event never
3519          * terminates (typically for reducing a scenario too big to trace to one that can be completed).
3520          * In the future we might implement an exit handler to dump unfinished events which would
3521          * deprecate these operations.
3522          */
3523         function begin(phase, name, args) {
3524             if (!traceFd)
3525                 return;
3526             writeEvent("B", phase, name, args);
3527         }
3528         tracing.begin = begin;
3529         function end(phase, name, args) {
3530             if (!traceFd)
3531                 return;
3532             writeEvent("E", phase, name, args);
3533         }
3534         tracing.end = end;
3535         function instant(phase, name, args) {
3536             if (!traceFd)
3537                 return;
3538             writeEvent("I", phase, name, args, "\"s\":\"g\"");
3539         }
3540         tracing.instant = instant;
3541         // Used for "Complete" (ph:"X") events
3542         var completeEvents = [];
3543         function push(phase, name, args) {
3544             if (!traceFd)
3545                 return;
3546             completeEvents.push({ phase: phase, name: name, args: args, time: 1000 * ts.timestamp() });
3547         }
3548         tracing.push = push;
3549         function pop() {
3550             if (!traceFd)
3551                 return;
3552             ts.Debug.assert(completeEvents.length > 0);
3553             var _a = completeEvents.pop(), phase = _a.phase, name = _a.name, args = _a.args, time = _a.time;
3554             var dur = 1000 * ts.timestamp() - time;
3555             writeEvent("X", phase, name, args, "\"dur\":" + dur, time);
3556         }
3557         tracing.pop = pop;
3558         function writeEvent(eventType, phase, name, args, extras, time) {
3559             if (time === void 0) { time = 1000 * ts.timestamp(); }
3560             ts.Debug.assert(traceFd);
3561             ts.Debug.assert(fs);
3562             ts.performance.mark("beginTracing");
3563             fs.writeSync(traceFd, ",\n{\"pid\":1,\"tid\":1,\"ph\":\"" + eventType + "\",\"cat\":\"" + phase + "\",\"ts\":" + time + ",\"name\":\"" + name + "\"");
3564             if (extras)
3565                 fs.writeSync(traceFd, "," + extras);
3566             if (args)
3567                 fs.writeSync(traceFd, ",\"args\":" + JSON.stringify(args));
3568             fs.writeSync(traceFd, "}");
3569             ts.performance.mark("endTracing");
3570             ts.performance.measure("Tracing", "beginTracing", "endTracing");
3571         }
3572         function indexFromOne(lc) {
3573             return {
3574                 line: lc.line + 1,
3575                 character: lc.character + 1,
3576             };
3577         }
3578         function dumpTypes(types) {
3579             var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _r;
3580             ts.Debug.assert(fs);
3581             ts.performance.mark("beginDumpTypes");
3582             var typesPath = legend[legend.length - 1].typesPath;
3583             var typesFd = fs.openSync(typesPath, "w");
3584             var recursionIdentityMap = new ts.Map();
3585             // Cleverness: no line break here so that the type ID will match the line number
3586             fs.writeSync(typesFd, "[");
3587             var numTypes = types.length;
3588             for (var i = 0; i < numTypes; i++) {
3589                 var type = types[i];
3590                 var objectFlags = type.objectFlags;
3591                 var symbol = (_a = type.aliasSymbol) !== null && _a !== void 0 ? _a : type.symbol;
3592                 var firstDeclaration = (_b = symbol === null || symbol === void 0 ? void 0 : symbol.declarations) === null || _b === void 0 ? void 0 : _b[0];
3593                 var firstFile = firstDeclaration && ts.getSourceFileOfNode(firstDeclaration);
3594                 // It's slow to compute the display text, so skip it unless it's really valuable (or cheap)
3595                 var display = void 0;
3596                 if ((objectFlags & 16 /* Anonymous */) | (type.flags & 2944 /* Literal */)) {
3597                     try {
3598                         display = (_c = type.checker) === null || _c === void 0 ? void 0 : _c.typeToString(type);
3599                     }
3600                     catch (_s) {
3601                         display = undefined;
3602                     }
3603                 }
3604                 var indexedAccessProperties = {};
3605                 if (type.flags & 8388608 /* IndexedAccess */) {
3606                     var indexedAccessType = type;
3607                     indexedAccessProperties = {
3608                         indexedAccessObjectType: (_d = indexedAccessType.objectType) === null || _d === void 0 ? void 0 : _d.id,
3609                         indexedAccessIndexType: (_e = indexedAccessType.indexType) === null || _e === void 0 ? void 0 : _e.id,
3610                     };
3611                 }
3612                 var referenceProperties = {};
3613                 if (objectFlags & 4 /* Reference */) {
3614                     var referenceType = type;
3615                     referenceProperties = {
3616                         instantiatedType: (_f = referenceType.target) === null || _f === void 0 ? void 0 : _f.id,
3617                         typeArguments: (_g = referenceType.resolvedTypeArguments) === null || _g === void 0 ? void 0 : _g.map(function (t) { return t.id; }),
3618                     };
3619                 }
3620                 var conditionalProperties = {};
3621                 if (type.flags & 16777216 /* Conditional */) {
3622                     var conditionalType = type;
3623                     conditionalProperties = {
3624                         conditionalCheckType: (_h = conditionalType.checkType) === null || _h === void 0 ? void 0 : _h.id,
3625                         conditionalExtendsType: (_j = conditionalType.extendsType) === null || _j === void 0 ? void 0 : _j.id,
3626                         conditionalTrueType: (_l = (_k = conditionalType.resolvedTrueType) === null || _k === void 0 ? void 0 : _k.id) !== null && _l !== void 0 ? _l : -1,
3627                         conditionalFalseType: (_o = (_m = conditionalType.resolvedFalseType) === null || _m === void 0 ? void 0 : _m.id) !== null && _o !== void 0 ? _o : -1,
3628                     };
3629                 }
3630                 // We can't print out an arbitrary object, so just assign each one a unique number.
3631                 // Don't call it an "id" so people don't treat it as a type id.
3632                 var recursionToken = void 0;
3633                 var recursionIdentity = type.checker.getRecursionIdentity(type);
3634                 if (recursionIdentity) {
3635                     recursionToken = recursionIdentityMap.get(recursionIdentity);
3636                     if (!recursionToken) {
3637                         recursionToken = recursionIdentityMap.size;
3638                         recursionIdentityMap.set(recursionIdentity, recursionToken);
3639                     }
3640                 }
3641                 var descriptor = __assign(__assign(__assign(__assign({ id: type.id, intrinsicName: type.intrinsicName, symbolName: (symbol === null || symbol === void 0 ? void 0 : symbol.escapedName) && ts.unescapeLeadingUnderscores(symbol.escapedName), recursionId: recursionToken, unionTypes: (type.flags & 1048576 /* Union */) ? (_p = type.types) === null || _p === void 0 ? void 0 : _p.map(function (t) { return t.id; }) : undefined, intersectionTypes: (type.flags & 2097152 /* Intersection */) ? type.types.map(function (t) { return t.id; }) : undefined, aliasTypeArguments: (_q = type.aliasTypeArguments) === null || _q === void 0 ? void 0 : _q.map(function (t) { return t.id; }), keyofType: (type.flags & 4194304 /* Index */) ? (_r = type.type) === null || _r === void 0 ? void 0 : _r.id : undefined }, indexedAccessProperties), referenceProperties), conditionalProperties), { firstDeclaration: firstDeclaration && {
3642                         path: firstFile.path,
3643                         start: indexFromOne(ts.getLineAndCharacterOfPosition(firstFile, firstDeclaration.pos)),
3644                         end: indexFromOne(ts.getLineAndCharacterOfPosition(ts.getSourceFileOfNode(firstDeclaration), firstDeclaration.end)),
3645                     }, flags: ts.Debug.formatTypeFlags(type.flags).split("|"), display: display });
3646                 fs.writeSync(typesFd, JSON.stringify(descriptor));
3647                 if (i < numTypes - 1) {
3648                     fs.writeSync(typesFd, ",\n");
3649                 }
3650             }
3651             fs.writeSync(typesFd, "]\n");
3652             fs.closeSync(typesFd);
3653             ts.performance.mark("endDumpTypes");
3654             ts.performance.measure("Dump types", "beginDumpTypes", "endDumpTypes");
3655         }
3656         function dumpLegend() {
3657             if (!legendPath) {
3658                 return;
3659             }
3660             ts.Debug.assert(fs);
3661             fs.writeFileSync(legendPath, JSON.stringify(legend));
3662         }
3663         tracing.dumpLegend = dumpLegend;
3664     })(tracing = ts.tracing || (ts.tracing = {}));
3665 })(ts || (ts = {}));
3666 var ts;
3667 (function (ts) {
3668     // token > SyntaxKind.Identifier => token is a keyword
3669     // Also, If you add a new SyntaxKind be sure to keep the `Markers` section at the bottom in sync
3670     var SyntaxKind;
3671     (function (SyntaxKind) {
3672         SyntaxKind[SyntaxKind["Unknown"] = 0] = "Unknown";
3673         SyntaxKind[SyntaxKind["EndOfFileToken"] = 1] = "EndOfFileToken";
3674         SyntaxKind[SyntaxKind["SingleLineCommentTrivia"] = 2] = "SingleLineCommentTrivia";
3675         SyntaxKind[SyntaxKind["MultiLineCommentTrivia"] = 3] = "MultiLineCommentTrivia";
3676         SyntaxKind[SyntaxKind["NewLineTrivia"] = 4] = "NewLineTrivia";
3677         SyntaxKind[SyntaxKind["WhitespaceTrivia"] = 5] = "WhitespaceTrivia";
3678         // We detect and preserve #! on the first line
3679         SyntaxKind[SyntaxKind["ShebangTrivia"] = 6] = "ShebangTrivia";
3680         // We detect and provide better error recovery when we encounter a git merge marker.  This
3681         // allows us to edit files with git-conflict markers in them in a much more pleasant manner.
3682         SyntaxKind[SyntaxKind["ConflictMarkerTrivia"] = 7] = "ConflictMarkerTrivia";
3683         // Literals
3684         SyntaxKind[SyntaxKind["NumericLiteral"] = 8] = "NumericLiteral";
3685         SyntaxKind[SyntaxKind["BigIntLiteral"] = 9] = "BigIntLiteral";
3686         SyntaxKind[SyntaxKind["StringLiteral"] = 10] = "StringLiteral";
3687         SyntaxKind[SyntaxKind["JsxText"] = 11] = "JsxText";
3688         SyntaxKind[SyntaxKind["JsxTextAllWhiteSpaces"] = 12] = "JsxTextAllWhiteSpaces";
3689         SyntaxKind[SyntaxKind["RegularExpressionLiteral"] = 13] = "RegularExpressionLiteral";
3690         SyntaxKind[SyntaxKind["NoSubstitutionTemplateLiteral"] = 14] = "NoSubstitutionTemplateLiteral";
3691         // Pseudo-literals
3692         SyntaxKind[SyntaxKind["TemplateHead"] = 15] = "TemplateHead";
3693         SyntaxKind[SyntaxKind["TemplateMiddle"] = 16] = "TemplateMiddle";
3694         SyntaxKind[SyntaxKind["TemplateTail"] = 17] = "TemplateTail";
3695         // Punctuation
3696         SyntaxKind[SyntaxKind["OpenBraceToken"] = 18] = "OpenBraceToken";
3697         SyntaxKind[SyntaxKind["CloseBraceToken"] = 19] = "CloseBraceToken";
3698         SyntaxKind[SyntaxKind["OpenParenToken"] = 20] = "OpenParenToken";
3699         SyntaxKind[SyntaxKind["CloseParenToken"] = 21] = "CloseParenToken";
3700         SyntaxKind[SyntaxKind["OpenBracketToken"] = 22] = "OpenBracketToken";
3701         SyntaxKind[SyntaxKind["CloseBracketToken"] = 23] = "CloseBracketToken";
3702         SyntaxKind[SyntaxKind["DotToken"] = 24] = "DotToken";
3703         SyntaxKind[SyntaxKind["DotDotDotToken"] = 25] = "DotDotDotToken";
3704         SyntaxKind[SyntaxKind["SemicolonToken"] = 26] = "SemicolonToken";
3705         SyntaxKind[SyntaxKind["CommaToken"] = 27] = "CommaToken";
3706         SyntaxKind[SyntaxKind["QuestionDotToken"] = 28] = "QuestionDotToken";
3707         SyntaxKind[SyntaxKind["LessThanToken"] = 29] = "LessThanToken";
3708         SyntaxKind[SyntaxKind["LessThanSlashToken"] = 30] = "LessThanSlashToken";
3709         SyntaxKind[SyntaxKind["GreaterThanToken"] = 31] = "GreaterThanToken";
3710         SyntaxKind[SyntaxKind["LessThanEqualsToken"] = 32] = "LessThanEqualsToken";
3711         SyntaxKind[SyntaxKind["GreaterThanEqualsToken"] = 33] = "GreaterThanEqualsToken";
3712         SyntaxKind[SyntaxKind["EqualsEqualsToken"] = 34] = "EqualsEqualsToken";
3713         SyntaxKind[SyntaxKind["ExclamationEqualsToken"] = 35] = "ExclamationEqualsToken";
3714         SyntaxKind[SyntaxKind["EqualsEqualsEqualsToken"] = 36] = "EqualsEqualsEqualsToken";
3715         SyntaxKind[SyntaxKind["ExclamationEqualsEqualsToken"] = 37] = "ExclamationEqualsEqualsToken";
3716         SyntaxKind[SyntaxKind["EqualsGreaterThanToken"] = 38] = "EqualsGreaterThanToken";
3717         SyntaxKind[SyntaxKind["PlusToken"] = 39] = "PlusToken";
3718         SyntaxKind[SyntaxKind["MinusToken"] = 40] = "MinusToken";
3719         SyntaxKind[SyntaxKind["AsteriskToken"] = 41] = "AsteriskToken";
3720         SyntaxKind[SyntaxKind["AsteriskAsteriskToken"] = 42] = "AsteriskAsteriskToken";
3721         SyntaxKind[SyntaxKind["SlashToken"] = 43] = "SlashToken";
3722         SyntaxKind[SyntaxKind["PercentToken"] = 44] = "PercentToken";
3723         SyntaxKind[SyntaxKind["PlusPlusToken"] = 45] = "PlusPlusToken";
3724         SyntaxKind[SyntaxKind["MinusMinusToken"] = 46] = "MinusMinusToken";
3725         SyntaxKind[SyntaxKind["LessThanLessThanToken"] = 47] = "LessThanLessThanToken";
3726         SyntaxKind[SyntaxKind["GreaterThanGreaterThanToken"] = 48] = "GreaterThanGreaterThanToken";
3727         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanToken"] = 49] = "GreaterThanGreaterThanGreaterThanToken";
3728         SyntaxKind[SyntaxKind["AmpersandToken"] = 50] = "AmpersandToken";
3729         SyntaxKind[SyntaxKind["BarToken"] = 51] = "BarToken";
3730         SyntaxKind[SyntaxKind["CaretToken"] = 52] = "CaretToken";
3731         SyntaxKind[SyntaxKind["ExclamationToken"] = 53] = "ExclamationToken";
3732         SyntaxKind[SyntaxKind["TildeToken"] = 54] = "TildeToken";
3733         SyntaxKind[SyntaxKind["AmpersandAmpersandToken"] = 55] = "AmpersandAmpersandToken";
3734         SyntaxKind[SyntaxKind["BarBarToken"] = 56] = "BarBarToken";
3735         SyntaxKind[SyntaxKind["QuestionToken"] = 57] = "QuestionToken";
3736         SyntaxKind[SyntaxKind["ColonToken"] = 58] = "ColonToken";
3737         SyntaxKind[SyntaxKind["AtToken"] = 59] = "AtToken";
3738         SyntaxKind[SyntaxKind["QuestionQuestionToken"] = 60] = "QuestionQuestionToken";
3739         /** Only the JSDoc scanner produces BacktickToken. The normal scanner produces NoSubstitutionTemplateLiteral and related kinds. */
3740         SyntaxKind[SyntaxKind["BacktickToken"] = 61] = "BacktickToken";
3741         // Assignments
3742         SyntaxKind[SyntaxKind["EqualsToken"] = 62] = "EqualsToken";
3743         SyntaxKind[SyntaxKind["PlusEqualsToken"] = 63] = "PlusEqualsToken";
3744         SyntaxKind[SyntaxKind["MinusEqualsToken"] = 64] = "MinusEqualsToken";
3745         SyntaxKind[SyntaxKind["AsteriskEqualsToken"] = 65] = "AsteriskEqualsToken";
3746         SyntaxKind[SyntaxKind["AsteriskAsteriskEqualsToken"] = 66] = "AsteriskAsteriskEqualsToken";
3747         SyntaxKind[SyntaxKind["SlashEqualsToken"] = 67] = "SlashEqualsToken";
3748         SyntaxKind[SyntaxKind["PercentEqualsToken"] = 68] = "PercentEqualsToken";
3749         SyntaxKind[SyntaxKind["LessThanLessThanEqualsToken"] = 69] = "LessThanLessThanEqualsToken";
3750         SyntaxKind[SyntaxKind["GreaterThanGreaterThanEqualsToken"] = 70] = "GreaterThanGreaterThanEqualsToken";
3751         SyntaxKind[SyntaxKind["GreaterThanGreaterThanGreaterThanEqualsToken"] = 71] = "GreaterThanGreaterThanGreaterThanEqualsToken";
3752         SyntaxKind[SyntaxKind["AmpersandEqualsToken"] = 72] = "AmpersandEqualsToken";
3753         SyntaxKind[SyntaxKind["BarEqualsToken"] = 73] = "BarEqualsToken";
3754         SyntaxKind[SyntaxKind["BarBarEqualsToken"] = 74] = "BarBarEqualsToken";
3755         SyntaxKind[SyntaxKind["AmpersandAmpersandEqualsToken"] = 75] = "AmpersandAmpersandEqualsToken";
3756         SyntaxKind[SyntaxKind["QuestionQuestionEqualsToken"] = 76] = "QuestionQuestionEqualsToken";
3757         SyntaxKind[SyntaxKind["CaretEqualsToken"] = 77] = "CaretEqualsToken";
3758         // Identifiers and PrivateIdentifiers
3759         SyntaxKind[SyntaxKind["Identifier"] = 78] = "Identifier";
3760         SyntaxKind[SyntaxKind["PrivateIdentifier"] = 79] = "PrivateIdentifier";
3761         // Reserved words
3762         SyntaxKind[SyntaxKind["BreakKeyword"] = 80] = "BreakKeyword";
3763         SyntaxKind[SyntaxKind["CaseKeyword"] = 81] = "CaseKeyword";
3764         SyntaxKind[SyntaxKind["CatchKeyword"] = 82] = "CatchKeyword";
3765         SyntaxKind[SyntaxKind["ClassKeyword"] = 83] = "ClassKeyword";
3766         SyntaxKind[SyntaxKind["ConstKeyword"] = 84] = "ConstKeyword";
3767         SyntaxKind[SyntaxKind["ContinueKeyword"] = 85] = "ContinueKeyword";
3768         SyntaxKind[SyntaxKind["DebuggerKeyword"] = 86] = "DebuggerKeyword";
3769         SyntaxKind[SyntaxKind["DefaultKeyword"] = 87] = "DefaultKeyword";
3770         SyntaxKind[SyntaxKind["DeleteKeyword"] = 88] = "DeleteKeyword";
3771         SyntaxKind[SyntaxKind["DoKeyword"] = 89] = "DoKeyword";
3772         SyntaxKind[SyntaxKind["ElseKeyword"] = 90] = "ElseKeyword";
3773         SyntaxKind[SyntaxKind["EnumKeyword"] = 91] = "EnumKeyword";
3774         SyntaxKind[SyntaxKind["ExportKeyword"] = 92] = "ExportKeyword";
3775         SyntaxKind[SyntaxKind["ExtendsKeyword"] = 93] = "ExtendsKeyword";
3776         SyntaxKind[SyntaxKind["FalseKeyword"] = 94] = "FalseKeyword";
3777         SyntaxKind[SyntaxKind["FinallyKeyword"] = 95] = "FinallyKeyword";
3778         SyntaxKind[SyntaxKind["ForKeyword"] = 96] = "ForKeyword";
3779         SyntaxKind[SyntaxKind["FunctionKeyword"] = 97] = "FunctionKeyword";
3780         SyntaxKind[SyntaxKind["IfKeyword"] = 98] = "IfKeyword";
3781         SyntaxKind[SyntaxKind["ImportKeyword"] = 99] = "ImportKeyword";
3782         SyntaxKind[SyntaxKind["InKeyword"] = 100] = "InKeyword";
3783         SyntaxKind[SyntaxKind["InstanceOfKeyword"] = 101] = "InstanceOfKeyword";
3784         SyntaxKind[SyntaxKind["NewKeyword"] = 102] = "NewKeyword";
3785         SyntaxKind[SyntaxKind["NullKeyword"] = 103] = "NullKeyword";
3786         SyntaxKind[SyntaxKind["ReturnKeyword"] = 104] = "ReturnKeyword";
3787         SyntaxKind[SyntaxKind["SuperKeyword"] = 105] = "SuperKeyword";
3788         SyntaxKind[SyntaxKind["SwitchKeyword"] = 106] = "SwitchKeyword";
3789         SyntaxKind[SyntaxKind["ThisKeyword"] = 107] = "ThisKeyword";
3790         SyntaxKind[SyntaxKind["ThrowKeyword"] = 108] = "ThrowKeyword";
3791         SyntaxKind[SyntaxKind["TrueKeyword"] = 109] = "TrueKeyword";
3792         SyntaxKind[SyntaxKind["TryKeyword"] = 110] = "TryKeyword";
3793         SyntaxKind[SyntaxKind["TypeOfKeyword"] = 111] = "TypeOfKeyword";
3794         SyntaxKind[SyntaxKind["VarKeyword"] = 112] = "VarKeyword";
3795         SyntaxKind[SyntaxKind["VoidKeyword"] = 113] = "VoidKeyword";
3796         SyntaxKind[SyntaxKind["WhileKeyword"] = 114] = "WhileKeyword";
3797         SyntaxKind[SyntaxKind["WithKeyword"] = 115] = "WithKeyword";
3798         // Strict mode reserved words
3799         SyntaxKind[SyntaxKind["ImplementsKeyword"] = 116] = "ImplementsKeyword";
3800         SyntaxKind[SyntaxKind["InterfaceKeyword"] = 117] = "InterfaceKeyword";
3801         SyntaxKind[SyntaxKind["LetKeyword"] = 118] = "LetKeyword";
3802         SyntaxKind[SyntaxKind["PackageKeyword"] = 119] = "PackageKeyword";
3803         SyntaxKind[SyntaxKind["PrivateKeyword"] = 120] = "PrivateKeyword";
3804         SyntaxKind[SyntaxKind["ProtectedKeyword"] = 121] = "ProtectedKeyword";
3805         SyntaxKind[SyntaxKind["PublicKeyword"] = 122] = "PublicKeyword";
3806         SyntaxKind[SyntaxKind["StaticKeyword"] = 123] = "StaticKeyword";
3807         SyntaxKind[SyntaxKind["YieldKeyword"] = 124] = "YieldKeyword";
3808         // Contextual keywords
3809         SyntaxKind[SyntaxKind["AbstractKeyword"] = 125] = "AbstractKeyword";
3810         SyntaxKind[SyntaxKind["AsKeyword"] = 126] = "AsKeyword";
3811         SyntaxKind[SyntaxKind["AssertsKeyword"] = 127] = "AssertsKeyword";
3812         SyntaxKind[SyntaxKind["AnyKeyword"] = 128] = "AnyKeyword";
3813         SyntaxKind[SyntaxKind["AsyncKeyword"] = 129] = "AsyncKeyword";
3814         SyntaxKind[SyntaxKind["AwaitKeyword"] = 130] = "AwaitKeyword";
3815         SyntaxKind[SyntaxKind["BooleanKeyword"] = 131] = "BooleanKeyword";
3816         SyntaxKind[SyntaxKind["ConstructorKeyword"] = 132] = "ConstructorKeyword";
3817         SyntaxKind[SyntaxKind["DeclareKeyword"] = 133] = "DeclareKeyword";
3818         SyntaxKind[SyntaxKind["GetKeyword"] = 134] = "GetKeyword";
3819         SyntaxKind[SyntaxKind["InferKeyword"] = 135] = "InferKeyword";
3820         SyntaxKind[SyntaxKind["IntrinsicKeyword"] = 136] = "IntrinsicKeyword";
3821         SyntaxKind[SyntaxKind["IsKeyword"] = 137] = "IsKeyword";
3822         SyntaxKind[SyntaxKind["KeyOfKeyword"] = 138] = "KeyOfKeyword";
3823         SyntaxKind[SyntaxKind["ModuleKeyword"] = 139] = "ModuleKeyword";
3824         SyntaxKind[SyntaxKind["NamespaceKeyword"] = 140] = "NamespaceKeyword";
3825         SyntaxKind[SyntaxKind["NeverKeyword"] = 141] = "NeverKeyword";
3826         SyntaxKind[SyntaxKind["ReadonlyKeyword"] = 142] = "ReadonlyKeyword";
3827         SyntaxKind[SyntaxKind["RequireKeyword"] = 143] = "RequireKeyword";
3828         SyntaxKind[SyntaxKind["NumberKeyword"] = 144] = "NumberKeyword";
3829         SyntaxKind[SyntaxKind["ObjectKeyword"] = 145] = "ObjectKeyword";
3830         SyntaxKind[SyntaxKind["SetKeyword"] = 146] = "SetKeyword";
3831         SyntaxKind[SyntaxKind["StringKeyword"] = 147] = "StringKeyword";
3832         SyntaxKind[SyntaxKind["SymbolKeyword"] = 148] = "SymbolKeyword";
3833         SyntaxKind[SyntaxKind["TypeKeyword"] = 149] = "TypeKeyword";
3834         SyntaxKind[SyntaxKind["UndefinedKeyword"] = 150] = "UndefinedKeyword";
3835         SyntaxKind[SyntaxKind["UniqueKeyword"] = 151] = "UniqueKeyword";
3836         SyntaxKind[SyntaxKind["UnknownKeyword"] = 152] = "UnknownKeyword";
3837         SyntaxKind[SyntaxKind["FromKeyword"] = 153] = "FromKeyword";
3838         SyntaxKind[SyntaxKind["GlobalKeyword"] = 154] = "GlobalKeyword";
3839         SyntaxKind[SyntaxKind["BigIntKeyword"] = 155] = "BigIntKeyword";
3840         SyntaxKind[SyntaxKind["OfKeyword"] = 156] = "OfKeyword";
3841         // Parse tree nodes
3842         // Names
3843         SyntaxKind[SyntaxKind["QualifiedName"] = 157] = "QualifiedName";
3844         SyntaxKind[SyntaxKind["ComputedPropertyName"] = 158] = "ComputedPropertyName";
3845         // Signature elements
3846         SyntaxKind[SyntaxKind["TypeParameter"] = 159] = "TypeParameter";
3847         SyntaxKind[SyntaxKind["Parameter"] = 160] = "Parameter";
3848         SyntaxKind[SyntaxKind["Decorator"] = 161] = "Decorator";
3849         // TypeMember
3850         SyntaxKind[SyntaxKind["PropertySignature"] = 162] = "PropertySignature";
3851         SyntaxKind[SyntaxKind["PropertyDeclaration"] = 163] = "PropertyDeclaration";
3852         SyntaxKind[SyntaxKind["MethodSignature"] = 164] = "MethodSignature";
3853         SyntaxKind[SyntaxKind["MethodDeclaration"] = 165] = "MethodDeclaration";
3854         SyntaxKind[SyntaxKind["Constructor"] = 166] = "Constructor";
3855         SyntaxKind[SyntaxKind["GetAccessor"] = 167] = "GetAccessor";
3856         SyntaxKind[SyntaxKind["SetAccessor"] = 168] = "SetAccessor";
3857         SyntaxKind[SyntaxKind["CallSignature"] = 169] = "CallSignature";
3858         SyntaxKind[SyntaxKind["ConstructSignature"] = 170] = "ConstructSignature";
3859         SyntaxKind[SyntaxKind["IndexSignature"] = 171] = "IndexSignature";
3860         // Type
3861         SyntaxKind[SyntaxKind["TypePredicate"] = 172] = "TypePredicate";
3862         SyntaxKind[SyntaxKind["TypeReference"] = 173] = "TypeReference";
3863         SyntaxKind[SyntaxKind["FunctionType"] = 174] = "FunctionType";
3864         SyntaxKind[SyntaxKind["ConstructorType"] = 175] = "ConstructorType";
3865         SyntaxKind[SyntaxKind["TypeQuery"] = 176] = "TypeQuery";
3866         SyntaxKind[SyntaxKind["TypeLiteral"] = 177] = "TypeLiteral";
3867         SyntaxKind[SyntaxKind["ArrayType"] = 178] = "ArrayType";
3868         SyntaxKind[SyntaxKind["TupleType"] = 179] = "TupleType";
3869         SyntaxKind[SyntaxKind["OptionalType"] = 180] = "OptionalType";
3870         SyntaxKind[SyntaxKind["RestType"] = 181] = "RestType";
3871         SyntaxKind[SyntaxKind["UnionType"] = 182] = "UnionType";
3872         SyntaxKind[SyntaxKind["IntersectionType"] = 183] = "IntersectionType";
3873         SyntaxKind[SyntaxKind["ConditionalType"] = 184] = "ConditionalType";
3874         SyntaxKind[SyntaxKind["InferType"] = 185] = "InferType";
3875         SyntaxKind[SyntaxKind["ParenthesizedType"] = 186] = "ParenthesizedType";
3876         SyntaxKind[SyntaxKind["ThisType"] = 187] = "ThisType";
3877         SyntaxKind[SyntaxKind["TypeOperator"] = 188] = "TypeOperator";
3878         SyntaxKind[SyntaxKind["IndexedAccessType"] = 189] = "IndexedAccessType";
3879         SyntaxKind[SyntaxKind["MappedType"] = 190] = "MappedType";
3880         SyntaxKind[SyntaxKind["LiteralType"] = 191] = "LiteralType";
3881         SyntaxKind[SyntaxKind["NamedTupleMember"] = 192] = "NamedTupleMember";
3882         SyntaxKind[SyntaxKind["TemplateLiteralType"] = 193] = "TemplateLiteralType";
3883         SyntaxKind[SyntaxKind["TemplateLiteralTypeSpan"] = 194] = "TemplateLiteralTypeSpan";
3884         SyntaxKind[SyntaxKind["ImportType"] = 195] = "ImportType";
3885         // Binding patterns
3886         SyntaxKind[SyntaxKind["ObjectBindingPattern"] = 196] = "ObjectBindingPattern";
3887         SyntaxKind[SyntaxKind["ArrayBindingPattern"] = 197] = "ArrayBindingPattern";
3888         SyntaxKind[SyntaxKind["BindingElement"] = 198] = "BindingElement";
3889         // Expression
3890         SyntaxKind[SyntaxKind["ArrayLiteralExpression"] = 199] = "ArrayLiteralExpression";
3891         SyntaxKind[SyntaxKind["ObjectLiteralExpression"] = 200] = "ObjectLiteralExpression";
3892         SyntaxKind[SyntaxKind["PropertyAccessExpression"] = 201] = "PropertyAccessExpression";
3893         SyntaxKind[SyntaxKind["ElementAccessExpression"] = 202] = "ElementAccessExpression";
3894         SyntaxKind[SyntaxKind["CallExpression"] = 203] = "CallExpression";
3895         SyntaxKind[SyntaxKind["NewExpression"] = 204] = "NewExpression";
3896         SyntaxKind[SyntaxKind["TaggedTemplateExpression"] = 205] = "TaggedTemplateExpression";
3897         SyntaxKind[SyntaxKind["TypeAssertionExpression"] = 206] = "TypeAssertionExpression";
3898         SyntaxKind[SyntaxKind["ParenthesizedExpression"] = 207] = "ParenthesizedExpression";
3899         SyntaxKind[SyntaxKind["FunctionExpression"] = 208] = "FunctionExpression";
3900         SyntaxKind[SyntaxKind["ArrowFunction"] = 209] = "ArrowFunction";
3901         SyntaxKind[SyntaxKind["DeleteExpression"] = 210] = "DeleteExpression";
3902         SyntaxKind[SyntaxKind["TypeOfExpression"] = 211] = "TypeOfExpression";
3903         SyntaxKind[SyntaxKind["VoidExpression"] = 212] = "VoidExpression";
3904         SyntaxKind[SyntaxKind["AwaitExpression"] = 213] = "AwaitExpression";
3905         SyntaxKind[SyntaxKind["PrefixUnaryExpression"] = 214] = "PrefixUnaryExpression";
3906         SyntaxKind[SyntaxKind["PostfixUnaryExpression"] = 215] = "PostfixUnaryExpression";
3907         SyntaxKind[SyntaxKind["BinaryExpression"] = 216] = "BinaryExpression";
3908         SyntaxKind[SyntaxKind["ConditionalExpression"] = 217] = "ConditionalExpression";
3909         SyntaxKind[SyntaxKind["TemplateExpression"] = 218] = "TemplateExpression";
3910         SyntaxKind[SyntaxKind["YieldExpression"] = 219] = "YieldExpression";
3911         SyntaxKind[SyntaxKind["SpreadElement"] = 220] = "SpreadElement";
3912         SyntaxKind[SyntaxKind["ClassExpression"] = 221] = "ClassExpression";
3913         SyntaxKind[SyntaxKind["OmittedExpression"] = 222] = "OmittedExpression";
3914         SyntaxKind[SyntaxKind["ExpressionWithTypeArguments"] = 223] = "ExpressionWithTypeArguments";
3915         SyntaxKind[SyntaxKind["AsExpression"] = 224] = "AsExpression";
3916         SyntaxKind[SyntaxKind["NonNullExpression"] = 225] = "NonNullExpression";
3917         SyntaxKind[SyntaxKind["MetaProperty"] = 226] = "MetaProperty";
3918         SyntaxKind[SyntaxKind["SyntheticExpression"] = 227] = "SyntheticExpression";
3919         // Misc
3920         SyntaxKind[SyntaxKind["TemplateSpan"] = 228] = "TemplateSpan";
3921         SyntaxKind[SyntaxKind["SemicolonClassElement"] = 229] = "SemicolonClassElement";
3922         // Element
3923         SyntaxKind[SyntaxKind["Block"] = 230] = "Block";
3924         SyntaxKind[SyntaxKind["EmptyStatement"] = 231] = "EmptyStatement";
3925         SyntaxKind[SyntaxKind["VariableStatement"] = 232] = "VariableStatement";
3926         SyntaxKind[SyntaxKind["ExpressionStatement"] = 233] = "ExpressionStatement";
3927         SyntaxKind[SyntaxKind["IfStatement"] = 234] = "IfStatement";
3928         SyntaxKind[SyntaxKind["DoStatement"] = 235] = "DoStatement";
3929         SyntaxKind[SyntaxKind["WhileStatement"] = 236] = "WhileStatement";
3930         SyntaxKind[SyntaxKind["ForStatement"] = 237] = "ForStatement";
3931         SyntaxKind[SyntaxKind["ForInStatement"] = 238] = "ForInStatement";
3932         SyntaxKind[SyntaxKind["ForOfStatement"] = 239] = "ForOfStatement";
3933         SyntaxKind[SyntaxKind["ContinueStatement"] = 240] = "ContinueStatement";
3934         SyntaxKind[SyntaxKind["BreakStatement"] = 241] = "BreakStatement";
3935         SyntaxKind[SyntaxKind["ReturnStatement"] = 242] = "ReturnStatement";
3936         SyntaxKind[SyntaxKind["WithStatement"] = 243] = "WithStatement";
3937         SyntaxKind[SyntaxKind["SwitchStatement"] = 244] = "SwitchStatement";
3938         SyntaxKind[SyntaxKind["LabeledStatement"] = 245] = "LabeledStatement";
3939         SyntaxKind[SyntaxKind["ThrowStatement"] = 246] = "ThrowStatement";
3940         SyntaxKind[SyntaxKind["TryStatement"] = 247] = "TryStatement";
3941         SyntaxKind[SyntaxKind["DebuggerStatement"] = 248] = "DebuggerStatement";
3942         SyntaxKind[SyntaxKind["VariableDeclaration"] = 249] = "VariableDeclaration";
3943         SyntaxKind[SyntaxKind["VariableDeclarationList"] = 250] = "VariableDeclarationList";
3944         SyntaxKind[SyntaxKind["FunctionDeclaration"] = 251] = "FunctionDeclaration";
3945         SyntaxKind[SyntaxKind["ClassDeclaration"] = 252] = "ClassDeclaration";
3946         SyntaxKind[SyntaxKind["InterfaceDeclaration"] = 253] = "InterfaceDeclaration";
3947         SyntaxKind[SyntaxKind["TypeAliasDeclaration"] = 254] = "TypeAliasDeclaration";
3948         SyntaxKind[SyntaxKind["EnumDeclaration"] = 255] = "EnumDeclaration";
3949         SyntaxKind[SyntaxKind["ModuleDeclaration"] = 256] = "ModuleDeclaration";
3950         SyntaxKind[SyntaxKind["ModuleBlock"] = 257] = "ModuleBlock";
3951         SyntaxKind[SyntaxKind["CaseBlock"] = 258] = "CaseBlock";
3952         SyntaxKind[SyntaxKind["NamespaceExportDeclaration"] = 259] = "NamespaceExportDeclaration";
3953         SyntaxKind[SyntaxKind["ImportEqualsDeclaration"] = 260] = "ImportEqualsDeclaration";
3954         SyntaxKind[SyntaxKind["ImportDeclaration"] = 261] = "ImportDeclaration";
3955         SyntaxKind[SyntaxKind["ImportClause"] = 262] = "ImportClause";
3956         SyntaxKind[SyntaxKind["NamespaceImport"] = 263] = "NamespaceImport";
3957         SyntaxKind[SyntaxKind["NamedImports"] = 264] = "NamedImports";
3958         SyntaxKind[SyntaxKind["ImportSpecifier"] = 265] = "ImportSpecifier";
3959         SyntaxKind[SyntaxKind["ExportAssignment"] = 266] = "ExportAssignment";
3960         SyntaxKind[SyntaxKind["ExportDeclaration"] = 267] = "ExportDeclaration";
3961         SyntaxKind[SyntaxKind["NamedExports"] = 268] = "NamedExports";
3962         SyntaxKind[SyntaxKind["NamespaceExport"] = 269] = "NamespaceExport";
3963         SyntaxKind[SyntaxKind["ExportSpecifier"] = 270] = "ExportSpecifier";
3964         SyntaxKind[SyntaxKind["MissingDeclaration"] = 271] = "MissingDeclaration";
3965         // Module references
3966         SyntaxKind[SyntaxKind["ExternalModuleReference"] = 272] = "ExternalModuleReference";
3967         // JSX
3968         SyntaxKind[SyntaxKind["JsxElement"] = 273] = "JsxElement";
3969         SyntaxKind[SyntaxKind["JsxSelfClosingElement"] = 274] = "JsxSelfClosingElement";
3970         SyntaxKind[SyntaxKind["JsxOpeningElement"] = 275] = "JsxOpeningElement";
3971         SyntaxKind[SyntaxKind["JsxClosingElement"] = 276] = "JsxClosingElement";
3972         SyntaxKind[SyntaxKind["JsxFragment"] = 277] = "JsxFragment";
3973         SyntaxKind[SyntaxKind["JsxOpeningFragment"] = 278] = "JsxOpeningFragment";
3974         SyntaxKind[SyntaxKind["JsxClosingFragment"] = 279] = "JsxClosingFragment";
3975         SyntaxKind[SyntaxKind["JsxAttribute"] = 280] = "JsxAttribute";
3976         SyntaxKind[SyntaxKind["JsxAttributes"] = 281] = "JsxAttributes";
3977         SyntaxKind[SyntaxKind["JsxSpreadAttribute"] = 282] = "JsxSpreadAttribute";
3978         SyntaxKind[SyntaxKind["JsxExpression"] = 283] = "JsxExpression";
3979         // Clauses
3980         SyntaxKind[SyntaxKind["CaseClause"] = 284] = "CaseClause";
3981         SyntaxKind[SyntaxKind["DefaultClause"] = 285] = "DefaultClause";
3982         SyntaxKind[SyntaxKind["HeritageClause"] = 286] = "HeritageClause";
3983         SyntaxKind[SyntaxKind["CatchClause"] = 287] = "CatchClause";
3984         // Property assignments
3985         SyntaxKind[SyntaxKind["PropertyAssignment"] = 288] = "PropertyAssignment";
3986         SyntaxKind[SyntaxKind["ShorthandPropertyAssignment"] = 289] = "ShorthandPropertyAssignment";
3987         SyntaxKind[SyntaxKind["SpreadAssignment"] = 290] = "SpreadAssignment";
3988         // Enum
3989         SyntaxKind[SyntaxKind["EnumMember"] = 291] = "EnumMember";
3990         // Unparsed
3991         SyntaxKind[SyntaxKind["UnparsedPrologue"] = 292] = "UnparsedPrologue";
3992         SyntaxKind[SyntaxKind["UnparsedPrepend"] = 293] = "UnparsedPrepend";
3993         SyntaxKind[SyntaxKind["UnparsedText"] = 294] = "UnparsedText";
3994         SyntaxKind[SyntaxKind["UnparsedInternalText"] = 295] = "UnparsedInternalText";
3995         SyntaxKind[SyntaxKind["UnparsedSyntheticReference"] = 296] = "UnparsedSyntheticReference";
3996         // Top-level nodes
3997         SyntaxKind[SyntaxKind["SourceFile"] = 297] = "SourceFile";
3998         SyntaxKind[SyntaxKind["Bundle"] = 298] = "Bundle";
3999         SyntaxKind[SyntaxKind["UnparsedSource"] = 299] = "UnparsedSource";
4000         SyntaxKind[SyntaxKind["InputFiles"] = 300] = "InputFiles";
4001         // JSDoc nodes
4002         SyntaxKind[SyntaxKind["JSDocTypeExpression"] = 301] = "JSDocTypeExpression";
4003         SyntaxKind[SyntaxKind["JSDocNameReference"] = 302] = "JSDocNameReference";
4004         // The * type
4005         SyntaxKind[SyntaxKind["JSDocAllType"] = 303] = "JSDocAllType";
4006         // The ? type
4007         SyntaxKind[SyntaxKind["JSDocUnknownType"] = 304] = "JSDocUnknownType";
4008         SyntaxKind[SyntaxKind["JSDocNullableType"] = 305] = "JSDocNullableType";
4009         SyntaxKind[SyntaxKind["JSDocNonNullableType"] = 306] = "JSDocNonNullableType";
4010         SyntaxKind[SyntaxKind["JSDocOptionalType"] = 307] = "JSDocOptionalType";
4011         SyntaxKind[SyntaxKind["JSDocFunctionType"] = 308] = "JSDocFunctionType";
4012         SyntaxKind[SyntaxKind["JSDocVariadicType"] = 309] = "JSDocVariadicType";
4013         // https://jsdoc.app/about-namepaths.html
4014         SyntaxKind[SyntaxKind["JSDocNamepathType"] = 310] = "JSDocNamepathType";
4015         SyntaxKind[SyntaxKind["JSDocComment"] = 311] = "JSDocComment";
4016         SyntaxKind[SyntaxKind["JSDocTypeLiteral"] = 312] = "JSDocTypeLiteral";
4017         SyntaxKind[SyntaxKind["JSDocSignature"] = 313] = "JSDocSignature";
4018         SyntaxKind[SyntaxKind["JSDocTag"] = 314] = "JSDocTag";
4019         SyntaxKind[SyntaxKind["JSDocAugmentsTag"] = 315] = "JSDocAugmentsTag";
4020         SyntaxKind[SyntaxKind["JSDocImplementsTag"] = 316] = "JSDocImplementsTag";
4021         SyntaxKind[SyntaxKind["JSDocAuthorTag"] = 317] = "JSDocAuthorTag";
4022         SyntaxKind[SyntaxKind["JSDocDeprecatedTag"] = 318] = "JSDocDeprecatedTag";
4023         SyntaxKind[SyntaxKind["JSDocClassTag"] = 319] = "JSDocClassTag";
4024         SyntaxKind[SyntaxKind["JSDocPublicTag"] = 320] = "JSDocPublicTag";
4025         SyntaxKind[SyntaxKind["JSDocPrivateTag"] = 321] = "JSDocPrivateTag";
4026         SyntaxKind[SyntaxKind["JSDocProtectedTag"] = 322] = "JSDocProtectedTag";
4027         SyntaxKind[SyntaxKind["JSDocReadonlyTag"] = 323] = "JSDocReadonlyTag";
4028         SyntaxKind[SyntaxKind["JSDocCallbackTag"] = 324] = "JSDocCallbackTag";
4029         SyntaxKind[SyntaxKind["JSDocEnumTag"] = 325] = "JSDocEnumTag";
4030         SyntaxKind[SyntaxKind["JSDocParameterTag"] = 326] = "JSDocParameterTag";
4031         SyntaxKind[SyntaxKind["JSDocReturnTag"] = 327] = "JSDocReturnTag";
4032         SyntaxKind[SyntaxKind["JSDocThisTag"] = 328] = "JSDocThisTag";
4033         SyntaxKind[SyntaxKind["JSDocTypeTag"] = 329] = "JSDocTypeTag";
4034         SyntaxKind[SyntaxKind["JSDocTemplateTag"] = 330] = "JSDocTemplateTag";
4035         SyntaxKind[SyntaxKind["JSDocTypedefTag"] = 331] = "JSDocTypedefTag";
4036         SyntaxKind[SyntaxKind["JSDocSeeTag"] = 332] = "JSDocSeeTag";
4037         SyntaxKind[SyntaxKind["JSDocPropertyTag"] = 333] = "JSDocPropertyTag";
4038         // Synthesized list
4039         SyntaxKind[SyntaxKind["SyntaxList"] = 334] = "SyntaxList";
4040         // Transformation nodes
4041         SyntaxKind[SyntaxKind["NotEmittedStatement"] = 335] = "NotEmittedStatement";
4042         SyntaxKind[SyntaxKind["PartiallyEmittedExpression"] = 336] = "PartiallyEmittedExpression";
4043         SyntaxKind[SyntaxKind["CommaListExpression"] = 337] = "CommaListExpression";
4044         SyntaxKind[SyntaxKind["MergeDeclarationMarker"] = 338] = "MergeDeclarationMarker";
4045         SyntaxKind[SyntaxKind["EndOfDeclarationMarker"] = 339] = "EndOfDeclarationMarker";
4046         SyntaxKind[SyntaxKind["SyntheticReferenceExpression"] = 340] = "SyntheticReferenceExpression";
4047         // Enum value count
4048         SyntaxKind[SyntaxKind["Count"] = 341] = "Count";
4049         // Markers
4050         SyntaxKind[SyntaxKind["FirstAssignment"] = 62] = "FirstAssignment";
4051         SyntaxKind[SyntaxKind["LastAssignment"] = 77] = "LastAssignment";
4052         SyntaxKind[SyntaxKind["FirstCompoundAssignment"] = 63] = "FirstCompoundAssignment";
4053         SyntaxKind[SyntaxKind["LastCompoundAssignment"] = 77] = "LastCompoundAssignment";
4054         SyntaxKind[SyntaxKind["FirstReservedWord"] = 80] = "FirstReservedWord";
4055         SyntaxKind[SyntaxKind["LastReservedWord"] = 115] = "LastReservedWord";
4056         SyntaxKind[SyntaxKind["FirstKeyword"] = 80] = "FirstKeyword";
4057         SyntaxKind[SyntaxKind["LastKeyword"] = 156] = "LastKeyword";
4058         SyntaxKind[SyntaxKind["FirstFutureReservedWord"] = 116] = "FirstFutureReservedWord";
4059         SyntaxKind[SyntaxKind["LastFutureReservedWord"] = 124] = "LastFutureReservedWord";
4060         SyntaxKind[SyntaxKind["FirstTypeNode"] = 172] = "FirstTypeNode";
4061         SyntaxKind[SyntaxKind["LastTypeNode"] = 195] = "LastTypeNode";
4062         SyntaxKind[SyntaxKind["FirstPunctuation"] = 18] = "FirstPunctuation";
4063         SyntaxKind[SyntaxKind["LastPunctuation"] = 77] = "LastPunctuation";
4064         SyntaxKind[SyntaxKind["FirstToken"] = 0] = "FirstToken";
4065         SyntaxKind[SyntaxKind["LastToken"] = 156] = "LastToken";
4066         SyntaxKind[SyntaxKind["FirstTriviaToken"] = 2] = "FirstTriviaToken";
4067         SyntaxKind[SyntaxKind["LastTriviaToken"] = 7] = "LastTriviaToken";
4068         SyntaxKind[SyntaxKind["FirstLiteralToken"] = 8] = "FirstLiteralToken";
4069         SyntaxKind[SyntaxKind["LastLiteralToken"] = 14] = "LastLiteralToken";
4070         SyntaxKind[SyntaxKind["FirstTemplateToken"] = 14] = "FirstTemplateToken";
4071         SyntaxKind[SyntaxKind["LastTemplateToken"] = 17] = "LastTemplateToken";
4072         SyntaxKind[SyntaxKind["FirstBinaryOperator"] = 29] = "FirstBinaryOperator";
4073         SyntaxKind[SyntaxKind["LastBinaryOperator"] = 77] = "LastBinaryOperator";
4074         SyntaxKind[SyntaxKind["FirstStatement"] = 232] = "FirstStatement";
4075         SyntaxKind[SyntaxKind["LastStatement"] = 248] = "LastStatement";
4076         SyntaxKind[SyntaxKind["FirstNode"] = 157] = "FirstNode";
4077         SyntaxKind[SyntaxKind["FirstJSDocNode"] = 301] = "FirstJSDocNode";
4078         SyntaxKind[SyntaxKind["LastJSDocNode"] = 333] = "LastJSDocNode";
4079         SyntaxKind[SyntaxKind["FirstJSDocTagNode"] = 314] = "FirstJSDocTagNode";
4080         SyntaxKind[SyntaxKind["LastJSDocTagNode"] = 333] = "LastJSDocTagNode";
4081         /* @internal */ SyntaxKind[SyntaxKind["FirstContextualKeyword"] = 125] = "FirstContextualKeyword";
4082         /* @internal */ SyntaxKind[SyntaxKind["LastContextualKeyword"] = 156] = "LastContextualKeyword";
4083     })(SyntaxKind = ts.SyntaxKind || (ts.SyntaxKind = {}));
4084     var NodeFlags;
4085     (function (NodeFlags) {
4086         NodeFlags[NodeFlags["None"] = 0] = "None";
4087         NodeFlags[NodeFlags["Let"] = 1] = "Let";
4088         NodeFlags[NodeFlags["Const"] = 2] = "Const";
4089         NodeFlags[NodeFlags["NestedNamespace"] = 4] = "NestedNamespace";
4090         NodeFlags[NodeFlags["Synthesized"] = 8] = "Synthesized";
4091         NodeFlags[NodeFlags["Namespace"] = 16] = "Namespace";
4092         NodeFlags[NodeFlags["OptionalChain"] = 32] = "OptionalChain";
4093         NodeFlags[NodeFlags["ExportContext"] = 64] = "ExportContext";
4094         NodeFlags[NodeFlags["ContainsThis"] = 128] = "ContainsThis";
4095         NodeFlags[NodeFlags["HasImplicitReturn"] = 256] = "HasImplicitReturn";
4096         NodeFlags[NodeFlags["HasExplicitReturn"] = 512] = "HasExplicitReturn";
4097         NodeFlags[NodeFlags["GlobalAugmentation"] = 1024] = "GlobalAugmentation";
4098         NodeFlags[NodeFlags["HasAsyncFunctions"] = 2048] = "HasAsyncFunctions";
4099         NodeFlags[NodeFlags["DisallowInContext"] = 4096] = "DisallowInContext";
4100         NodeFlags[NodeFlags["YieldContext"] = 8192] = "YieldContext";
4101         NodeFlags[NodeFlags["DecoratorContext"] = 16384] = "DecoratorContext";
4102         NodeFlags[NodeFlags["AwaitContext"] = 32768] = "AwaitContext";
4103         NodeFlags[NodeFlags["ThisNodeHasError"] = 65536] = "ThisNodeHasError";
4104         NodeFlags[NodeFlags["JavaScriptFile"] = 131072] = "JavaScriptFile";
4105         NodeFlags[NodeFlags["ThisNodeOrAnySubNodesHasError"] = 262144] = "ThisNodeOrAnySubNodesHasError";
4106         NodeFlags[NodeFlags["HasAggregatedChildData"] = 524288] = "HasAggregatedChildData";
4107         // These flags will be set when the parser encounters a dynamic import expression or 'import.meta' to avoid
4108         // walking the tree if the flags are not set. However, these flags are just a approximation
4109         // (hence why it's named "PossiblyContainsDynamicImport") because once set, the flags never get cleared.
4110         // During editing, if a dynamic import is removed, incremental parsing will *NOT* clear this flag.
4111         // This means that the tree will always be traversed during module resolution, or when looking for external module indicators.
4112         // However, the removal operation should not occur often and in the case of the
4113         // removal, it is likely that users will add the import anyway.
4114         // The advantage of this approach is its simplicity. For the case of batch compilation,
4115         // we guarantee that users won't have to pay the price of walking the tree if a dynamic import isn't used.
4116         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsDynamicImport"] = 1048576] = "PossiblyContainsDynamicImport";
4117         /* @internal */ NodeFlags[NodeFlags["PossiblyContainsImportMeta"] = 2097152] = "PossiblyContainsImportMeta";
4118         NodeFlags[NodeFlags["JSDoc"] = 4194304] = "JSDoc";
4119         /* @internal */ NodeFlags[NodeFlags["Ambient"] = 8388608] = "Ambient";
4120         /* @internal */ NodeFlags[NodeFlags["InWithStatement"] = 16777216] = "InWithStatement";
4121         NodeFlags[NodeFlags["JsonFile"] = 33554432] = "JsonFile";
4122         /* @internal */ NodeFlags[NodeFlags["TypeCached"] = 67108864] = "TypeCached";
4123         /* @internal */ NodeFlags[NodeFlags["Deprecated"] = 134217728] = "Deprecated";
4124         NodeFlags[NodeFlags["BlockScoped"] = 3] = "BlockScoped";
4125         NodeFlags[NodeFlags["ReachabilityCheckFlags"] = 768] = "ReachabilityCheckFlags";
4126         NodeFlags[NodeFlags["ReachabilityAndEmitFlags"] = 2816] = "ReachabilityAndEmitFlags";
4127         // Parsing context flags
4128         NodeFlags[NodeFlags["ContextFlags"] = 25358336] = "ContextFlags";
4129         // Exclude these flags when parsing a Type
4130         NodeFlags[NodeFlags["TypeExcludesFlags"] = 40960] = "TypeExcludesFlags";
4131         // Represents all flags that are potentially set once and
4132         // never cleared on SourceFiles which get re-used in between incremental parses.
4133         // See the comment above on `PossiblyContainsDynamicImport` and `PossiblyContainsImportMeta`.
4134         /* @internal */ NodeFlags[NodeFlags["PermanentlySetIncrementalFlags"] = 3145728] = "PermanentlySetIncrementalFlags";
4135     })(NodeFlags = ts.NodeFlags || (ts.NodeFlags = {}));
4136     var ModifierFlags;
4137     (function (ModifierFlags) {
4138         ModifierFlags[ModifierFlags["None"] = 0] = "None";
4139         ModifierFlags[ModifierFlags["Export"] = 1] = "Export";
4140         ModifierFlags[ModifierFlags["Ambient"] = 2] = "Ambient";
4141         ModifierFlags[ModifierFlags["Public"] = 4] = "Public";
4142         ModifierFlags[ModifierFlags["Private"] = 8] = "Private";
4143         ModifierFlags[ModifierFlags["Protected"] = 16] = "Protected";
4144         ModifierFlags[ModifierFlags["Static"] = 32] = "Static";
4145         ModifierFlags[ModifierFlags["Readonly"] = 64] = "Readonly";
4146         ModifierFlags[ModifierFlags["Abstract"] = 128] = "Abstract";
4147         ModifierFlags[ModifierFlags["Async"] = 256] = "Async";
4148         ModifierFlags[ModifierFlags["Default"] = 512] = "Default";
4149         ModifierFlags[ModifierFlags["Const"] = 2048] = "Const";
4150         ModifierFlags[ModifierFlags["HasComputedJSDocModifiers"] = 4096] = "HasComputedJSDocModifiers";
4151         ModifierFlags[ModifierFlags["Deprecated"] = 8192] = "Deprecated";
4152         ModifierFlags[ModifierFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
4153         ModifierFlags[ModifierFlags["AccessibilityModifier"] = 28] = "AccessibilityModifier";
4154         // Accessibility modifiers and 'readonly' can be attached to a parameter in a constructor to make it a property.
4155         ModifierFlags[ModifierFlags["ParameterPropertyModifier"] = 92] = "ParameterPropertyModifier";
4156         ModifierFlags[ModifierFlags["NonPublicAccessibilityModifier"] = 24] = "NonPublicAccessibilityModifier";
4157         ModifierFlags[ModifierFlags["TypeScriptModifier"] = 2270] = "TypeScriptModifier";
4158         ModifierFlags[ModifierFlags["ExportDefault"] = 513] = "ExportDefault";
4159         ModifierFlags[ModifierFlags["All"] = 11263] = "All";
4160     })(ModifierFlags = ts.ModifierFlags || (ts.ModifierFlags = {}));
4161     var JsxFlags;
4162     (function (JsxFlags) {
4163         JsxFlags[JsxFlags["None"] = 0] = "None";
4164         /** An element from a named property of the JSX.IntrinsicElements interface */
4165         JsxFlags[JsxFlags["IntrinsicNamedElement"] = 1] = "IntrinsicNamedElement";
4166         /** An element inferred from the string index signature of the JSX.IntrinsicElements interface */
4167         JsxFlags[JsxFlags["IntrinsicIndexedElement"] = 2] = "IntrinsicIndexedElement";
4168         JsxFlags[JsxFlags["IntrinsicElement"] = 3] = "IntrinsicElement";
4169     })(JsxFlags = ts.JsxFlags || (ts.JsxFlags = {}));
4170     /* @internal */
4171     var RelationComparisonResult;
4172     (function (RelationComparisonResult) {
4173         RelationComparisonResult[RelationComparisonResult["Succeeded"] = 1] = "Succeeded";
4174         RelationComparisonResult[RelationComparisonResult["Failed"] = 2] = "Failed";
4175         RelationComparisonResult[RelationComparisonResult["Reported"] = 4] = "Reported";
4176         RelationComparisonResult[RelationComparisonResult["ReportsUnmeasurable"] = 8] = "ReportsUnmeasurable";
4177         RelationComparisonResult[RelationComparisonResult["ReportsUnreliable"] = 16] = "ReportsUnreliable";
4178         RelationComparisonResult[RelationComparisonResult["ReportsMask"] = 24] = "ReportsMask";
4179     })(RelationComparisonResult = ts.RelationComparisonResult || (ts.RelationComparisonResult = {}));
4180     var GeneratedIdentifierFlags;
4181     (function (GeneratedIdentifierFlags) {
4182         // Kinds
4183         GeneratedIdentifierFlags[GeneratedIdentifierFlags["None"] = 0] = "None";
4184         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Auto"] = 1] = "Auto";
4185         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Loop"] = 2] = "Loop";
4186         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Unique"] = 3] = "Unique";
4187         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["Node"] = 4] = "Node";
4188         /*@internal*/ GeneratedIdentifierFlags[GeneratedIdentifierFlags["KindMask"] = 7] = "KindMask";
4189         // Flags
4190         GeneratedIdentifierFlags[GeneratedIdentifierFlags["ReservedInNestedScopes"] = 8] = "ReservedInNestedScopes";
4191         GeneratedIdentifierFlags[GeneratedIdentifierFlags["Optimistic"] = 16] = "Optimistic";
4192         GeneratedIdentifierFlags[GeneratedIdentifierFlags["FileLevel"] = 32] = "FileLevel";
4193         GeneratedIdentifierFlags[GeneratedIdentifierFlags["AllowNameSubstitution"] = 64] = "AllowNameSubstitution";
4194     })(GeneratedIdentifierFlags = ts.GeneratedIdentifierFlags || (ts.GeneratedIdentifierFlags = {}));
4195     var TokenFlags;
4196     (function (TokenFlags) {
4197         TokenFlags[TokenFlags["None"] = 0] = "None";
4198         /* @internal */
4199         TokenFlags[TokenFlags["PrecedingLineBreak"] = 1] = "PrecedingLineBreak";
4200         /* @internal */
4201         TokenFlags[TokenFlags["PrecedingJSDocComment"] = 2] = "PrecedingJSDocComment";
4202         /* @internal */
4203         TokenFlags[TokenFlags["Unterminated"] = 4] = "Unterminated";
4204         /* @internal */
4205         TokenFlags[TokenFlags["ExtendedUnicodeEscape"] = 8] = "ExtendedUnicodeEscape";
4206         TokenFlags[TokenFlags["Scientific"] = 16] = "Scientific";
4207         TokenFlags[TokenFlags["Octal"] = 32] = "Octal";
4208         TokenFlags[TokenFlags["HexSpecifier"] = 64] = "HexSpecifier";
4209         TokenFlags[TokenFlags["BinarySpecifier"] = 128] = "BinarySpecifier";
4210         TokenFlags[TokenFlags["OctalSpecifier"] = 256] = "OctalSpecifier";
4211         /* @internal */
4212         TokenFlags[TokenFlags["ContainsSeparator"] = 512] = "ContainsSeparator";
4213         /* @internal */
4214         TokenFlags[TokenFlags["UnicodeEscape"] = 1024] = "UnicodeEscape";
4215         /* @internal */
4216         TokenFlags[TokenFlags["ContainsInvalidEscape"] = 2048] = "ContainsInvalidEscape";
4217         /* @internal */
4218         TokenFlags[TokenFlags["BinaryOrOctalSpecifier"] = 384] = "BinaryOrOctalSpecifier";
4219         /* @internal */
4220         TokenFlags[TokenFlags["NumericLiteralFlags"] = 1008] = "NumericLiteralFlags";
4221         /* @internal */
4222         TokenFlags[TokenFlags["TemplateLiteralLikeFlags"] = 2048] = "TemplateLiteralLikeFlags";
4223     })(TokenFlags = ts.TokenFlags || (ts.TokenFlags = {}));
4224     // NOTE: Ensure this is up-to-date with src/debug/debug.ts
4225     var FlowFlags;
4226     (function (FlowFlags) {
4227         FlowFlags[FlowFlags["Unreachable"] = 1] = "Unreachable";
4228         FlowFlags[FlowFlags["Start"] = 2] = "Start";
4229         FlowFlags[FlowFlags["BranchLabel"] = 4] = "BranchLabel";
4230         FlowFlags[FlowFlags["LoopLabel"] = 8] = "LoopLabel";
4231         FlowFlags[FlowFlags["Assignment"] = 16] = "Assignment";
4232         FlowFlags[FlowFlags["TrueCondition"] = 32] = "TrueCondition";
4233         FlowFlags[FlowFlags["FalseCondition"] = 64] = "FalseCondition";
4234         FlowFlags[FlowFlags["SwitchClause"] = 128] = "SwitchClause";
4235         FlowFlags[FlowFlags["ArrayMutation"] = 256] = "ArrayMutation";
4236         FlowFlags[FlowFlags["Call"] = 512] = "Call";
4237         FlowFlags[FlowFlags["ReduceLabel"] = 1024] = "ReduceLabel";
4238         FlowFlags[FlowFlags["Referenced"] = 2048] = "Referenced";
4239         FlowFlags[FlowFlags["Shared"] = 4096] = "Shared";
4240         FlowFlags[FlowFlags["Label"] = 12] = "Label";
4241         FlowFlags[FlowFlags["Condition"] = 96] = "Condition";
4242     })(FlowFlags = ts.FlowFlags || (ts.FlowFlags = {}));
4243     /* @internal */
4244     var CommentDirectiveType;
4245     (function (CommentDirectiveType) {
4246         CommentDirectiveType[CommentDirectiveType["ExpectError"] = 0] = "ExpectError";
4247         CommentDirectiveType[CommentDirectiveType["Ignore"] = 1] = "Ignore";
4248     })(CommentDirectiveType = ts.CommentDirectiveType || (ts.CommentDirectiveType = {}));
4249     var OperationCanceledException = /** @class */ (function () {
4250         function OperationCanceledException() {
4251         }
4252         return OperationCanceledException;
4253     }());
4254     ts.OperationCanceledException = OperationCanceledException;
4255     /*@internal*/
4256     var RefFileKind;
4257     (function (RefFileKind) {
4258         RefFileKind[RefFileKind["Import"] = 0] = "Import";
4259         RefFileKind[RefFileKind["ReferenceFile"] = 1] = "ReferenceFile";
4260         RefFileKind[RefFileKind["TypeReferenceDirective"] = 2] = "TypeReferenceDirective";
4261     })(RefFileKind = ts.RefFileKind || (ts.RefFileKind = {}));
4262     /* @internal */
4263     var StructureIsReused;
4264     (function (StructureIsReused) {
4265         StructureIsReused[StructureIsReused["Not"] = 0] = "Not";
4266         StructureIsReused[StructureIsReused["SafeModules"] = 1] = "SafeModules";
4267         StructureIsReused[StructureIsReused["Completely"] = 2] = "Completely";
4268     })(StructureIsReused = ts.StructureIsReused || (ts.StructureIsReused = {}));
4269     /** Return code used by getEmitOutput function to indicate status of the function */
4270     var ExitStatus;
4271     (function (ExitStatus) {
4272         // Compiler ran successfully.  Either this was a simple do-nothing compilation (for example,
4273         // when -version or -help was provided, or this was a normal compilation, no diagnostics
4274         // were produced, and all outputs were generated successfully.
4275         ExitStatus[ExitStatus["Success"] = 0] = "Success";
4276         // Diagnostics were produced and because of them no code was generated.
4277         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsSkipped"] = 1] = "DiagnosticsPresent_OutputsSkipped";
4278         // Diagnostics were produced and outputs were generated in spite of them.
4279         ExitStatus[ExitStatus["DiagnosticsPresent_OutputsGenerated"] = 2] = "DiagnosticsPresent_OutputsGenerated";
4280         // When build skipped because passed in project is invalid
4281         ExitStatus[ExitStatus["InvalidProject_OutputsSkipped"] = 3] = "InvalidProject_OutputsSkipped";
4282         // When build is skipped because project references form cycle
4283         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkipped"] = 4] = "ProjectReferenceCycle_OutputsSkipped";
4284         /** @deprecated Use ProjectReferenceCycle_OutputsSkipped instead. */
4285         ExitStatus[ExitStatus["ProjectReferenceCycle_OutputsSkupped"] = 4] = "ProjectReferenceCycle_OutputsSkupped";
4286     })(ExitStatus = ts.ExitStatus || (ts.ExitStatus = {}));
4287     /* @internal */
4288     var UnionReduction;
4289     (function (UnionReduction) {
4290         UnionReduction[UnionReduction["None"] = 0] = "None";
4291         UnionReduction[UnionReduction["Literal"] = 1] = "Literal";
4292         UnionReduction[UnionReduction["Subtype"] = 2] = "Subtype";
4293     })(UnionReduction = ts.UnionReduction || (ts.UnionReduction = {}));
4294     /* @internal */
4295     var ContextFlags;
4296     (function (ContextFlags) {
4297         ContextFlags[ContextFlags["None"] = 0] = "None";
4298         ContextFlags[ContextFlags["Signature"] = 1] = "Signature";
4299         ContextFlags[ContextFlags["NoConstraints"] = 2] = "NoConstraints";
4300         ContextFlags[ContextFlags["Completions"] = 4] = "Completions";
4301         ContextFlags[ContextFlags["SkipBindingPatterns"] = 8] = "SkipBindingPatterns";
4302     })(ContextFlags = ts.ContextFlags || (ts.ContextFlags = {}));
4303     // NOTE: If modifying this enum, must modify `TypeFormatFlags` too!
4304     var NodeBuilderFlags;
4305     (function (NodeBuilderFlags) {
4306         NodeBuilderFlags[NodeBuilderFlags["None"] = 0] = "None";
4307         // Options
4308         NodeBuilderFlags[NodeBuilderFlags["NoTruncation"] = 1] = "NoTruncation";
4309         NodeBuilderFlags[NodeBuilderFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
4310         NodeBuilderFlags[NodeBuilderFlags["GenerateNamesForShadowedTypeParams"] = 4] = "GenerateNamesForShadowedTypeParams";
4311         NodeBuilderFlags[NodeBuilderFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
4312         NodeBuilderFlags[NodeBuilderFlags["ForbidIndexedAccessSymbolReferences"] = 16] = "ForbidIndexedAccessSymbolReferences";
4313         NodeBuilderFlags[NodeBuilderFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
4314         NodeBuilderFlags[NodeBuilderFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
4315         NodeBuilderFlags[NodeBuilderFlags["UseOnlyExternalAliasing"] = 128] = "UseOnlyExternalAliasing";
4316         NodeBuilderFlags[NodeBuilderFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
4317         NodeBuilderFlags[NodeBuilderFlags["WriteTypeParametersInQualifiedName"] = 512] = "WriteTypeParametersInQualifiedName";
4318         NodeBuilderFlags[NodeBuilderFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
4319         NodeBuilderFlags[NodeBuilderFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
4320         NodeBuilderFlags[NodeBuilderFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
4321         NodeBuilderFlags[NodeBuilderFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
4322         NodeBuilderFlags[NodeBuilderFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
4323         NodeBuilderFlags[NodeBuilderFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
4324         NodeBuilderFlags[NodeBuilderFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
4325         NodeBuilderFlags[NodeBuilderFlags["NoUndefinedOptionalParameterType"] = 1073741824] = "NoUndefinedOptionalParameterType";
4326         // Error handling
4327         NodeBuilderFlags[NodeBuilderFlags["AllowThisInObjectLiteral"] = 32768] = "AllowThisInObjectLiteral";
4328         NodeBuilderFlags[NodeBuilderFlags["AllowQualifedNameInPlaceOfIdentifier"] = 65536] = "AllowQualifedNameInPlaceOfIdentifier";
4329         NodeBuilderFlags[NodeBuilderFlags["AllowAnonymousIdentifier"] = 131072] = "AllowAnonymousIdentifier";
4330         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyUnionOrIntersection"] = 262144] = "AllowEmptyUnionOrIntersection";
4331         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyTuple"] = 524288] = "AllowEmptyTuple";
4332         NodeBuilderFlags[NodeBuilderFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
4333         NodeBuilderFlags[NodeBuilderFlags["AllowEmptyIndexInfoType"] = 2097152] = "AllowEmptyIndexInfoType";
4334         // Errors (cont.)
4335         NodeBuilderFlags[NodeBuilderFlags["AllowNodeModulesRelativePaths"] = 67108864] = "AllowNodeModulesRelativePaths";
4336         /* @internal */ NodeBuilderFlags[NodeBuilderFlags["DoNotIncludeSymbolChain"] = 134217728] = "DoNotIncludeSymbolChain";
4337         NodeBuilderFlags[NodeBuilderFlags["IgnoreErrors"] = 70221824] = "IgnoreErrors";
4338         // State
4339         NodeBuilderFlags[NodeBuilderFlags["InObjectTypeLiteral"] = 4194304] = "InObjectTypeLiteral";
4340         NodeBuilderFlags[NodeBuilderFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
4341         NodeBuilderFlags[NodeBuilderFlags["InInitialEntityName"] = 16777216] = "InInitialEntityName";
4342         NodeBuilderFlags[NodeBuilderFlags["InReverseMappedType"] = 33554432] = "InReverseMappedType";
4343     })(NodeBuilderFlags = ts.NodeBuilderFlags || (ts.NodeBuilderFlags = {}));
4344     // Ensure the shared flags between this and `NodeBuilderFlags` stay in alignment
4345     var TypeFormatFlags;
4346     (function (TypeFormatFlags) {
4347         TypeFormatFlags[TypeFormatFlags["None"] = 0] = "None";
4348         TypeFormatFlags[TypeFormatFlags["NoTruncation"] = 1] = "NoTruncation";
4349         TypeFormatFlags[TypeFormatFlags["WriteArrayAsGenericType"] = 2] = "WriteArrayAsGenericType";
4350         // hole because there's a hole in node builder flags
4351         TypeFormatFlags[TypeFormatFlags["UseStructuralFallback"] = 8] = "UseStructuralFallback";
4352         // hole because there's a hole in node builder flags
4353         TypeFormatFlags[TypeFormatFlags["WriteTypeArgumentsOfSignature"] = 32] = "WriteTypeArgumentsOfSignature";
4354         TypeFormatFlags[TypeFormatFlags["UseFullyQualifiedType"] = 64] = "UseFullyQualifiedType";
4355         // hole because `UseOnlyExternalAliasing` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` instead
4356         TypeFormatFlags[TypeFormatFlags["SuppressAnyReturnType"] = 256] = "SuppressAnyReturnType";
4357         // hole because `WriteTypeParametersInQualifiedName` is here in node builder flags, but functions which take old flags use `SymbolFormatFlags` for this instead
4358         TypeFormatFlags[TypeFormatFlags["MultilineObjectLiterals"] = 1024] = "MultilineObjectLiterals";
4359         TypeFormatFlags[TypeFormatFlags["WriteClassExpressionAsTypeLiteral"] = 2048] = "WriteClassExpressionAsTypeLiteral";
4360         TypeFormatFlags[TypeFormatFlags["UseTypeOfFunction"] = 4096] = "UseTypeOfFunction";
4361         TypeFormatFlags[TypeFormatFlags["OmitParameterModifiers"] = 8192] = "OmitParameterModifiers";
4362         TypeFormatFlags[TypeFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 16384] = "UseAliasDefinedOutsideCurrentScope";
4363         TypeFormatFlags[TypeFormatFlags["UseSingleQuotesForStringLiteralType"] = 268435456] = "UseSingleQuotesForStringLiteralType";
4364         TypeFormatFlags[TypeFormatFlags["NoTypeReduction"] = 536870912] = "NoTypeReduction";
4365         // Error Handling
4366         TypeFormatFlags[TypeFormatFlags["AllowUniqueESSymbolType"] = 1048576] = "AllowUniqueESSymbolType";
4367         // TypeFormatFlags exclusive
4368         TypeFormatFlags[TypeFormatFlags["AddUndefined"] = 131072] = "AddUndefined";
4369         TypeFormatFlags[TypeFormatFlags["WriteArrowStyleSignature"] = 262144] = "WriteArrowStyleSignature";
4370         // State
4371         TypeFormatFlags[TypeFormatFlags["InArrayType"] = 524288] = "InArrayType";
4372         TypeFormatFlags[TypeFormatFlags["InElementType"] = 2097152] = "InElementType";
4373         TypeFormatFlags[TypeFormatFlags["InFirstTypeArgument"] = 4194304] = "InFirstTypeArgument";
4374         TypeFormatFlags[TypeFormatFlags["InTypeAlias"] = 8388608] = "InTypeAlias";
4375         /** @deprecated */ TypeFormatFlags[TypeFormatFlags["WriteOwnNameForAnyLike"] = 0] = "WriteOwnNameForAnyLike";
4376         TypeFormatFlags[TypeFormatFlags["NodeBuilderFlagsMask"] = 814775659] = "NodeBuilderFlagsMask";
4377     })(TypeFormatFlags = ts.TypeFormatFlags || (ts.TypeFormatFlags = {}));
4378     var SymbolFormatFlags;
4379     (function (SymbolFormatFlags) {
4380         SymbolFormatFlags[SymbolFormatFlags["None"] = 0] = "None";
4381         // Write symbols's type argument if it is instantiated symbol
4382         // eg. class C<T> { p: T }   <-- Show p as C<T>.p here
4383         //     var a: C<number>;
4384         //     var p = a.p; <--- Here p is property of C<number> so show it as C<number>.p instead of just C.p
4385         SymbolFormatFlags[SymbolFormatFlags["WriteTypeParametersOrArguments"] = 1] = "WriteTypeParametersOrArguments";
4386         // Use only external alias information to get the symbol name in the given context
4387         // eg.  module m { export class c { } } import x = m.c;
4388         // When this flag is specified m.c will be used to refer to the class instead of alias symbol x
4389         SymbolFormatFlags[SymbolFormatFlags["UseOnlyExternalAliasing"] = 2] = "UseOnlyExternalAliasing";
4390         // Build symbol name using any nodes needed, instead of just components of an entity name
4391         SymbolFormatFlags[SymbolFormatFlags["AllowAnyNodeKind"] = 4] = "AllowAnyNodeKind";
4392         // Prefer aliases which are not directly visible
4393         SymbolFormatFlags[SymbolFormatFlags["UseAliasDefinedOutsideCurrentScope"] = 8] = "UseAliasDefinedOutsideCurrentScope";
4394         // Skip building an accessible symbol chain
4395         /* @internal */ SymbolFormatFlags[SymbolFormatFlags["DoNotIncludeSymbolChain"] = 16] = "DoNotIncludeSymbolChain";
4396     })(SymbolFormatFlags = ts.SymbolFormatFlags || (ts.SymbolFormatFlags = {}));
4397     /* @internal */
4398     var SymbolAccessibility;
4399     (function (SymbolAccessibility) {
4400         SymbolAccessibility[SymbolAccessibility["Accessible"] = 0] = "Accessible";
4401         SymbolAccessibility[SymbolAccessibility["NotAccessible"] = 1] = "NotAccessible";
4402         SymbolAccessibility[SymbolAccessibility["CannotBeNamed"] = 2] = "CannotBeNamed";
4403     })(SymbolAccessibility = ts.SymbolAccessibility || (ts.SymbolAccessibility = {}));
4404     /* @internal */
4405     var SyntheticSymbolKind;
4406     (function (SyntheticSymbolKind) {
4407         SyntheticSymbolKind[SyntheticSymbolKind["UnionOrIntersection"] = 0] = "UnionOrIntersection";
4408         SyntheticSymbolKind[SyntheticSymbolKind["Spread"] = 1] = "Spread";
4409     })(SyntheticSymbolKind = ts.SyntheticSymbolKind || (ts.SyntheticSymbolKind = {}));
4410     var TypePredicateKind;
4411     (function (TypePredicateKind) {
4412         TypePredicateKind[TypePredicateKind["This"] = 0] = "This";
4413         TypePredicateKind[TypePredicateKind["Identifier"] = 1] = "Identifier";
4414         TypePredicateKind[TypePredicateKind["AssertsThis"] = 2] = "AssertsThis";
4415         TypePredicateKind[TypePredicateKind["AssertsIdentifier"] = 3] = "AssertsIdentifier";
4416     })(TypePredicateKind = ts.TypePredicateKind || (ts.TypePredicateKind = {}));
4417     /** Indicates how to serialize the name for a TypeReferenceNode when emitting decorator metadata */
4418     /* @internal */
4419     var TypeReferenceSerializationKind;
4420     (function (TypeReferenceSerializationKind) {
4421         // The TypeReferenceNode could not be resolved.
4422         // The type name should be emitted using a safe fallback.
4423         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Unknown"] = 0] = "Unknown";
4424         // The TypeReferenceNode resolves to a type with a constructor
4425         // function that can be reached at runtime (e.g. a `class`
4426         // declaration or a `var` declaration for the static side
4427         // of a type, such as the global `Promise` type in lib.d.ts).
4428         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithConstructSignatureAndValue"] = 1] = "TypeWithConstructSignatureAndValue";
4429         // The TypeReferenceNode resolves to a Void-like, Nullable, or Never type.
4430         TypeReferenceSerializationKind[TypeReferenceSerializationKind["VoidNullableOrNeverType"] = 2] = "VoidNullableOrNeverType";
4431         // The TypeReferenceNode resolves to a Number-like type.
4432         TypeReferenceSerializationKind[TypeReferenceSerializationKind["NumberLikeType"] = 3] = "NumberLikeType";
4433         // The TypeReferenceNode resolves to a BigInt-like type.
4434         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BigIntLikeType"] = 4] = "BigIntLikeType";
4435         // The TypeReferenceNode resolves to a String-like type.
4436         TypeReferenceSerializationKind[TypeReferenceSerializationKind["StringLikeType"] = 5] = "StringLikeType";
4437         // The TypeReferenceNode resolves to a Boolean-like type.
4438         TypeReferenceSerializationKind[TypeReferenceSerializationKind["BooleanType"] = 6] = "BooleanType";
4439         // The TypeReferenceNode resolves to an Array-like type.
4440         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ArrayLikeType"] = 7] = "ArrayLikeType";
4441         // The TypeReferenceNode resolves to the ESSymbol type.
4442         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ESSymbolType"] = 8] = "ESSymbolType";
4443         // The TypeReferenceNode resolved to the global Promise constructor symbol.
4444         TypeReferenceSerializationKind[TypeReferenceSerializationKind["Promise"] = 9] = "Promise";
4445         // The TypeReferenceNode resolves to a Function type or a type with call signatures.
4446         TypeReferenceSerializationKind[TypeReferenceSerializationKind["TypeWithCallSignature"] = 10] = "TypeWithCallSignature";
4447         // The TypeReferenceNode resolves to any other type.
4448         TypeReferenceSerializationKind[TypeReferenceSerializationKind["ObjectType"] = 11] = "ObjectType";
4449     })(TypeReferenceSerializationKind = ts.TypeReferenceSerializationKind || (ts.TypeReferenceSerializationKind = {}));
4450     var SymbolFlags;
4451     (function (SymbolFlags) {
4452         SymbolFlags[SymbolFlags["None"] = 0] = "None";
4453         SymbolFlags[SymbolFlags["FunctionScopedVariable"] = 1] = "FunctionScopedVariable";
4454         SymbolFlags[SymbolFlags["BlockScopedVariable"] = 2] = "BlockScopedVariable";
4455         SymbolFlags[SymbolFlags["Property"] = 4] = "Property";
4456         SymbolFlags[SymbolFlags["EnumMember"] = 8] = "EnumMember";
4457         SymbolFlags[SymbolFlags["Function"] = 16] = "Function";
4458         SymbolFlags[SymbolFlags["Class"] = 32] = "Class";
4459         SymbolFlags[SymbolFlags["Interface"] = 64] = "Interface";
4460         SymbolFlags[SymbolFlags["ConstEnum"] = 128] = "ConstEnum";
4461         SymbolFlags[SymbolFlags["RegularEnum"] = 256] = "RegularEnum";
4462         SymbolFlags[SymbolFlags["ValueModule"] = 512] = "ValueModule";
4463         SymbolFlags[SymbolFlags["NamespaceModule"] = 1024] = "NamespaceModule";
4464         SymbolFlags[SymbolFlags["TypeLiteral"] = 2048] = "TypeLiteral";
4465         SymbolFlags[SymbolFlags["ObjectLiteral"] = 4096] = "ObjectLiteral";
4466         SymbolFlags[SymbolFlags["Method"] = 8192] = "Method";
4467         SymbolFlags[SymbolFlags["Constructor"] = 16384] = "Constructor";
4468         SymbolFlags[SymbolFlags["GetAccessor"] = 32768] = "GetAccessor";
4469         SymbolFlags[SymbolFlags["SetAccessor"] = 65536] = "SetAccessor";
4470         SymbolFlags[SymbolFlags["Signature"] = 131072] = "Signature";
4471         SymbolFlags[SymbolFlags["TypeParameter"] = 262144] = "TypeParameter";
4472         SymbolFlags[SymbolFlags["TypeAlias"] = 524288] = "TypeAlias";
4473         SymbolFlags[SymbolFlags["ExportValue"] = 1048576] = "ExportValue";
4474         SymbolFlags[SymbolFlags["Alias"] = 2097152] = "Alias";
4475         SymbolFlags[SymbolFlags["Prototype"] = 4194304] = "Prototype";
4476         SymbolFlags[SymbolFlags["ExportStar"] = 8388608] = "ExportStar";
4477         SymbolFlags[SymbolFlags["Optional"] = 16777216] = "Optional";
4478         SymbolFlags[SymbolFlags["Transient"] = 33554432] = "Transient";
4479         SymbolFlags[SymbolFlags["Assignment"] = 67108864] = "Assignment";
4480         SymbolFlags[SymbolFlags["ModuleExports"] = 134217728] = "ModuleExports";
4481         /* @internal */
4482         SymbolFlags[SymbolFlags["All"] = 67108863] = "All";
4483         SymbolFlags[SymbolFlags["Enum"] = 384] = "Enum";
4484         SymbolFlags[SymbolFlags["Variable"] = 3] = "Variable";
4485         SymbolFlags[SymbolFlags["Value"] = 111551] = "Value";
4486         SymbolFlags[SymbolFlags["Type"] = 788968] = "Type";
4487         SymbolFlags[SymbolFlags["Namespace"] = 1920] = "Namespace";
4488         SymbolFlags[SymbolFlags["Module"] = 1536] = "Module";
4489         SymbolFlags[SymbolFlags["Accessor"] = 98304] = "Accessor";
4490         // Variables can be redeclared, but can not redeclare a block-scoped declaration with the
4491         // same name, or any other value that is not a variable, e.g. ValueModule or Class
4492         SymbolFlags[SymbolFlags["FunctionScopedVariableExcludes"] = 111550] = "FunctionScopedVariableExcludes";
4493         // Block-scoped declarations are not allowed to be re-declared
4494         // they can not merge with anything in the value space
4495         SymbolFlags[SymbolFlags["BlockScopedVariableExcludes"] = 111551] = "BlockScopedVariableExcludes";
4496         SymbolFlags[SymbolFlags["ParameterExcludes"] = 111551] = "ParameterExcludes";
4497         SymbolFlags[SymbolFlags["PropertyExcludes"] = 0] = "PropertyExcludes";
4498         SymbolFlags[SymbolFlags["EnumMemberExcludes"] = 900095] = "EnumMemberExcludes";
4499         SymbolFlags[SymbolFlags["FunctionExcludes"] = 110991] = "FunctionExcludes";
4500         SymbolFlags[SymbolFlags["ClassExcludes"] = 899503] = "ClassExcludes";
4501         SymbolFlags[SymbolFlags["InterfaceExcludes"] = 788872] = "InterfaceExcludes";
4502         SymbolFlags[SymbolFlags["RegularEnumExcludes"] = 899327] = "RegularEnumExcludes";
4503         SymbolFlags[SymbolFlags["ConstEnumExcludes"] = 899967] = "ConstEnumExcludes";
4504         SymbolFlags[SymbolFlags["ValueModuleExcludes"] = 110735] = "ValueModuleExcludes";
4505         SymbolFlags[SymbolFlags["NamespaceModuleExcludes"] = 0] = "NamespaceModuleExcludes";
4506         SymbolFlags[SymbolFlags["MethodExcludes"] = 103359] = "MethodExcludes";
4507         SymbolFlags[SymbolFlags["GetAccessorExcludes"] = 46015] = "GetAccessorExcludes";
4508         SymbolFlags[SymbolFlags["SetAccessorExcludes"] = 78783] = "SetAccessorExcludes";
4509         SymbolFlags[SymbolFlags["TypeParameterExcludes"] = 526824] = "TypeParameterExcludes";
4510         SymbolFlags[SymbolFlags["TypeAliasExcludes"] = 788968] = "TypeAliasExcludes";
4511         SymbolFlags[SymbolFlags["AliasExcludes"] = 2097152] = "AliasExcludes";
4512         SymbolFlags[SymbolFlags["ModuleMember"] = 2623475] = "ModuleMember";
4513         SymbolFlags[SymbolFlags["ExportHasLocal"] = 944] = "ExportHasLocal";
4514         SymbolFlags[SymbolFlags["BlockScoped"] = 418] = "BlockScoped";
4515         SymbolFlags[SymbolFlags["PropertyOrAccessor"] = 98308] = "PropertyOrAccessor";
4516         SymbolFlags[SymbolFlags["ClassMember"] = 106500] = "ClassMember";
4517         /* @internal */
4518         SymbolFlags[SymbolFlags["ExportSupportsDefaultModifier"] = 112] = "ExportSupportsDefaultModifier";
4519         /* @internal */
4520         SymbolFlags[SymbolFlags["ExportDoesNotSupportDefaultModifier"] = -113] = "ExportDoesNotSupportDefaultModifier";
4521         /* @internal */
4522         // The set of things we consider semantically classifiable.  Used to speed up the LS during
4523         // classification.
4524         SymbolFlags[SymbolFlags["Classifiable"] = 2885600] = "Classifiable";
4525         /* @internal */
4526         SymbolFlags[SymbolFlags["LateBindingContainer"] = 6256] = "LateBindingContainer";
4527     })(SymbolFlags = ts.SymbolFlags || (ts.SymbolFlags = {}));
4528     /* @internal */
4529     var EnumKind;
4530     (function (EnumKind) {
4531         EnumKind[EnumKind["Numeric"] = 0] = "Numeric";
4532         EnumKind[EnumKind["Literal"] = 1] = "Literal"; // Literal enum (each member has a TypeFlags.EnumLiteral type)
4533     })(EnumKind = ts.EnumKind || (ts.EnumKind = {}));
4534     /* @internal */
4535     var CheckFlags;
4536     (function (CheckFlags) {
4537         CheckFlags[CheckFlags["Instantiated"] = 1] = "Instantiated";
4538         CheckFlags[CheckFlags["SyntheticProperty"] = 2] = "SyntheticProperty";
4539         CheckFlags[CheckFlags["SyntheticMethod"] = 4] = "SyntheticMethod";
4540         CheckFlags[CheckFlags["Readonly"] = 8] = "Readonly";
4541         CheckFlags[CheckFlags["ReadPartial"] = 16] = "ReadPartial";
4542         CheckFlags[CheckFlags["WritePartial"] = 32] = "WritePartial";
4543         CheckFlags[CheckFlags["HasNonUniformType"] = 64] = "HasNonUniformType";
4544         CheckFlags[CheckFlags["HasLiteralType"] = 128] = "HasLiteralType";
4545         CheckFlags[CheckFlags["ContainsPublic"] = 256] = "ContainsPublic";
4546         CheckFlags[CheckFlags["ContainsProtected"] = 512] = "ContainsProtected";
4547         CheckFlags[CheckFlags["ContainsPrivate"] = 1024] = "ContainsPrivate";
4548         CheckFlags[CheckFlags["ContainsStatic"] = 2048] = "ContainsStatic";
4549         CheckFlags[CheckFlags["Late"] = 4096] = "Late";
4550         CheckFlags[CheckFlags["ReverseMapped"] = 8192] = "ReverseMapped";
4551         CheckFlags[CheckFlags["OptionalParameter"] = 16384] = "OptionalParameter";
4552         CheckFlags[CheckFlags["RestParameter"] = 32768] = "RestParameter";
4553         CheckFlags[CheckFlags["DeferredType"] = 65536] = "DeferredType";
4554         CheckFlags[CheckFlags["HasNeverType"] = 131072] = "HasNeverType";
4555         CheckFlags[CheckFlags["Mapped"] = 262144] = "Mapped";
4556         CheckFlags[CheckFlags["StripOptional"] = 524288] = "StripOptional";
4557         CheckFlags[CheckFlags["Synthetic"] = 6] = "Synthetic";
4558         CheckFlags[CheckFlags["Discriminant"] = 192] = "Discriminant";
4559         CheckFlags[CheckFlags["Partial"] = 48] = "Partial";
4560     })(CheckFlags = ts.CheckFlags || (ts.CheckFlags = {}));
4561     var InternalSymbolName;
4562     (function (InternalSymbolName) {
4563         InternalSymbolName["Call"] = "__call";
4564         InternalSymbolName["Constructor"] = "__constructor";
4565         InternalSymbolName["New"] = "__new";
4566         InternalSymbolName["Index"] = "__index";
4567         InternalSymbolName["ExportStar"] = "__export";
4568         InternalSymbolName["Global"] = "__global";
4569         InternalSymbolName["Missing"] = "__missing";
4570         InternalSymbolName["Type"] = "__type";
4571         InternalSymbolName["Object"] = "__object";
4572         InternalSymbolName["JSXAttributes"] = "__jsxAttributes";
4573         InternalSymbolName["Class"] = "__class";
4574         InternalSymbolName["Function"] = "__function";
4575         InternalSymbolName["Computed"] = "__computed";
4576         InternalSymbolName["Resolving"] = "__resolving__";
4577         InternalSymbolName["ExportEquals"] = "export=";
4578         InternalSymbolName["Default"] = "default";
4579         InternalSymbolName["This"] = "this";
4580     })(InternalSymbolName = ts.InternalSymbolName || (ts.InternalSymbolName = {}));
4581     /* @internal */
4582     var NodeCheckFlags;
4583     (function (NodeCheckFlags) {
4584         NodeCheckFlags[NodeCheckFlags["TypeChecked"] = 1] = "TypeChecked";
4585         NodeCheckFlags[NodeCheckFlags["LexicalThis"] = 2] = "LexicalThis";
4586         NodeCheckFlags[NodeCheckFlags["CaptureThis"] = 4] = "CaptureThis";
4587         NodeCheckFlags[NodeCheckFlags["CaptureNewTarget"] = 8] = "CaptureNewTarget";
4588         NodeCheckFlags[NodeCheckFlags["SuperInstance"] = 256] = "SuperInstance";
4589         NodeCheckFlags[NodeCheckFlags["SuperStatic"] = 512] = "SuperStatic";
4590         NodeCheckFlags[NodeCheckFlags["ContextChecked"] = 1024] = "ContextChecked";
4591         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuper"] = 2048] = "AsyncMethodWithSuper";
4592         NodeCheckFlags[NodeCheckFlags["AsyncMethodWithSuperBinding"] = 4096] = "AsyncMethodWithSuperBinding";
4593         NodeCheckFlags[NodeCheckFlags["CaptureArguments"] = 8192] = "CaptureArguments";
4594         NodeCheckFlags[NodeCheckFlags["EnumValuesComputed"] = 16384] = "EnumValuesComputed";
4595         NodeCheckFlags[NodeCheckFlags["LexicalModuleMergesWithClass"] = 32768] = "LexicalModuleMergesWithClass";
4596         NodeCheckFlags[NodeCheckFlags["LoopWithCapturedBlockScopedBinding"] = 65536] = "LoopWithCapturedBlockScopedBinding";
4597         NodeCheckFlags[NodeCheckFlags["ContainsCapturedBlockScopeBinding"] = 131072] = "ContainsCapturedBlockScopeBinding";
4598         NodeCheckFlags[NodeCheckFlags["CapturedBlockScopedBinding"] = 262144] = "CapturedBlockScopedBinding";
4599         NodeCheckFlags[NodeCheckFlags["BlockScopedBindingInLoop"] = 524288] = "BlockScopedBindingInLoop";
4600         NodeCheckFlags[NodeCheckFlags["ClassWithBodyScopedClassBinding"] = 1048576] = "ClassWithBodyScopedClassBinding";
4601         NodeCheckFlags[NodeCheckFlags["BodyScopedClassBinding"] = 2097152] = "BodyScopedClassBinding";
4602         NodeCheckFlags[NodeCheckFlags["NeedsLoopOutParameter"] = 4194304] = "NeedsLoopOutParameter";
4603         NodeCheckFlags[NodeCheckFlags["AssignmentsMarked"] = 8388608] = "AssignmentsMarked";
4604         NodeCheckFlags[NodeCheckFlags["ClassWithConstructorReference"] = 16777216] = "ClassWithConstructorReference";
4605         NodeCheckFlags[NodeCheckFlags["ConstructorReferenceInClass"] = 33554432] = "ConstructorReferenceInClass";
4606         NodeCheckFlags[NodeCheckFlags["ContainsClassWithPrivateIdentifiers"] = 67108864] = "ContainsClassWithPrivateIdentifiers";
4607     })(NodeCheckFlags = ts.NodeCheckFlags || (ts.NodeCheckFlags = {}));
4608     var TypeFlags;
4609     (function (TypeFlags) {
4610         TypeFlags[TypeFlags["Any"] = 1] = "Any";
4611         TypeFlags[TypeFlags["Unknown"] = 2] = "Unknown";
4612         TypeFlags[TypeFlags["String"] = 4] = "String";
4613         TypeFlags[TypeFlags["Number"] = 8] = "Number";
4614         TypeFlags[TypeFlags["Boolean"] = 16] = "Boolean";
4615         TypeFlags[TypeFlags["Enum"] = 32] = "Enum";
4616         TypeFlags[TypeFlags["BigInt"] = 64] = "BigInt";
4617         TypeFlags[TypeFlags["StringLiteral"] = 128] = "StringLiteral";
4618         TypeFlags[TypeFlags["NumberLiteral"] = 256] = "NumberLiteral";
4619         TypeFlags[TypeFlags["BooleanLiteral"] = 512] = "BooleanLiteral";
4620         TypeFlags[TypeFlags["EnumLiteral"] = 1024] = "EnumLiteral";
4621         TypeFlags[TypeFlags["BigIntLiteral"] = 2048] = "BigIntLiteral";
4622         TypeFlags[TypeFlags["ESSymbol"] = 4096] = "ESSymbol";
4623         TypeFlags[TypeFlags["UniqueESSymbol"] = 8192] = "UniqueESSymbol";
4624         TypeFlags[TypeFlags["Void"] = 16384] = "Void";
4625         TypeFlags[TypeFlags["Undefined"] = 32768] = "Undefined";
4626         TypeFlags[TypeFlags["Null"] = 65536] = "Null";
4627         TypeFlags[TypeFlags["Never"] = 131072] = "Never";
4628         TypeFlags[TypeFlags["TypeParameter"] = 262144] = "TypeParameter";
4629         TypeFlags[TypeFlags["Object"] = 524288] = "Object";
4630         TypeFlags[TypeFlags["Union"] = 1048576] = "Union";
4631         TypeFlags[TypeFlags["Intersection"] = 2097152] = "Intersection";
4632         TypeFlags[TypeFlags["Index"] = 4194304] = "Index";
4633         TypeFlags[TypeFlags["IndexedAccess"] = 8388608] = "IndexedAccess";
4634         TypeFlags[TypeFlags["Conditional"] = 16777216] = "Conditional";
4635         TypeFlags[TypeFlags["Substitution"] = 33554432] = "Substitution";
4636         TypeFlags[TypeFlags["NonPrimitive"] = 67108864] = "NonPrimitive";
4637         TypeFlags[TypeFlags["TemplateLiteral"] = 134217728] = "TemplateLiteral";
4638         TypeFlags[TypeFlags["StringMapping"] = 268435456] = "StringMapping";
4639         /* @internal */
4640         TypeFlags[TypeFlags["AnyOrUnknown"] = 3] = "AnyOrUnknown";
4641         /* @internal */
4642         TypeFlags[TypeFlags["Nullable"] = 98304] = "Nullable";
4643         TypeFlags[TypeFlags["Literal"] = 2944] = "Literal";
4644         TypeFlags[TypeFlags["Unit"] = 109440] = "Unit";
4645         TypeFlags[TypeFlags["StringOrNumberLiteral"] = 384] = "StringOrNumberLiteral";
4646         /* @internal */
4647         TypeFlags[TypeFlags["StringOrNumberLiteralOrUnique"] = 8576] = "StringOrNumberLiteralOrUnique";
4648         /* @internal */
4649         TypeFlags[TypeFlags["DefinitelyFalsy"] = 117632] = "DefinitelyFalsy";
4650         TypeFlags[TypeFlags["PossiblyFalsy"] = 117724] = "PossiblyFalsy";
4651         /* @internal */
4652         TypeFlags[TypeFlags["Intrinsic"] = 67359327] = "Intrinsic";
4653         /* @internal */
4654         TypeFlags[TypeFlags["Primitive"] = 131068] = "Primitive";
4655         TypeFlags[TypeFlags["StringLike"] = 402653316] = "StringLike";
4656         TypeFlags[TypeFlags["NumberLike"] = 296] = "NumberLike";
4657         TypeFlags[TypeFlags["BigIntLike"] = 2112] = "BigIntLike";
4658         TypeFlags[TypeFlags["BooleanLike"] = 528] = "BooleanLike";
4659         TypeFlags[TypeFlags["EnumLike"] = 1056] = "EnumLike";
4660         TypeFlags[TypeFlags["ESSymbolLike"] = 12288] = "ESSymbolLike";
4661         TypeFlags[TypeFlags["VoidLike"] = 49152] = "VoidLike";
4662         /* @internal */
4663         TypeFlags[TypeFlags["DisjointDomains"] = 469892092] = "DisjointDomains";
4664         TypeFlags[TypeFlags["UnionOrIntersection"] = 3145728] = "UnionOrIntersection";
4665         TypeFlags[TypeFlags["StructuredType"] = 3670016] = "StructuredType";
4666         TypeFlags[TypeFlags["TypeVariable"] = 8650752] = "TypeVariable";
4667         TypeFlags[TypeFlags["InstantiableNonPrimitive"] = 58982400] = "InstantiableNonPrimitive";
4668         TypeFlags[TypeFlags["InstantiablePrimitive"] = 406847488] = "InstantiablePrimitive";
4669         TypeFlags[TypeFlags["Instantiable"] = 465829888] = "Instantiable";
4670         TypeFlags[TypeFlags["StructuredOrInstantiable"] = 469499904] = "StructuredOrInstantiable";
4671         /* @internal */
4672         TypeFlags[TypeFlags["ObjectFlagsType"] = 3899393] = "ObjectFlagsType";
4673         /* @internal */
4674         TypeFlags[TypeFlags["Simplifiable"] = 25165824] = "Simplifiable";
4675         /* @internal */
4676         TypeFlags[TypeFlags["Substructure"] = 469237760] = "Substructure";
4677         // 'Narrowable' types are types where narrowing actually narrows.
4678         // This *should* be every type other than null, undefined, void, and never
4679         TypeFlags[TypeFlags["Narrowable"] = 536624127] = "Narrowable";
4680         /* @internal */
4681         TypeFlags[TypeFlags["NotPrimitiveUnion"] = 469647395] = "NotPrimitiveUnion";
4682         // The following flags are aggregated during union and intersection type construction
4683         /* @internal */
4684         TypeFlags[TypeFlags["IncludesMask"] = 205258751] = "IncludesMask";
4685         // The following flags are used for different purposes during union and intersection type construction
4686         /* @internal */
4687         TypeFlags[TypeFlags["IncludesStructuredOrInstantiable"] = 262144] = "IncludesStructuredOrInstantiable";
4688         /* @internal */
4689         TypeFlags[TypeFlags["IncludesNonWideningType"] = 4194304] = "IncludesNonWideningType";
4690         /* @internal */
4691         TypeFlags[TypeFlags["IncludesWildcard"] = 8388608] = "IncludesWildcard";
4692         /* @internal */
4693         TypeFlags[TypeFlags["IncludesEmptyObject"] = 16777216] = "IncludesEmptyObject";
4694     })(TypeFlags = ts.TypeFlags || (ts.TypeFlags = {}));
4695     var ObjectFlags;
4696     (function (ObjectFlags) {
4697         ObjectFlags[ObjectFlags["Class"] = 1] = "Class";
4698         ObjectFlags[ObjectFlags["Interface"] = 2] = "Interface";
4699         ObjectFlags[ObjectFlags["Reference"] = 4] = "Reference";
4700         ObjectFlags[ObjectFlags["Tuple"] = 8] = "Tuple";
4701         ObjectFlags[ObjectFlags["Anonymous"] = 16] = "Anonymous";
4702         ObjectFlags[ObjectFlags["Mapped"] = 32] = "Mapped";
4703         ObjectFlags[ObjectFlags["Instantiated"] = 64] = "Instantiated";
4704         ObjectFlags[ObjectFlags["ObjectLiteral"] = 128] = "ObjectLiteral";
4705         ObjectFlags[ObjectFlags["EvolvingArray"] = 256] = "EvolvingArray";
4706         ObjectFlags[ObjectFlags["ObjectLiteralPatternWithComputedProperties"] = 512] = "ObjectLiteralPatternWithComputedProperties";
4707         ObjectFlags[ObjectFlags["ContainsSpread"] = 1024] = "ContainsSpread";
4708         ObjectFlags[ObjectFlags["ReverseMapped"] = 2048] = "ReverseMapped";
4709         ObjectFlags[ObjectFlags["JsxAttributes"] = 4096] = "JsxAttributes";
4710         ObjectFlags[ObjectFlags["MarkerType"] = 8192] = "MarkerType";
4711         ObjectFlags[ObjectFlags["JSLiteral"] = 16384] = "JSLiteral";
4712         ObjectFlags[ObjectFlags["FreshLiteral"] = 32768] = "FreshLiteral";
4713         ObjectFlags[ObjectFlags["ArrayLiteral"] = 65536] = "ArrayLiteral";
4714         ObjectFlags[ObjectFlags["ObjectRestType"] = 131072] = "ObjectRestType";
4715         /* @internal */
4716         ObjectFlags[ObjectFlags["PrimitiveUnion"] = 262144] = "PrimitiveUnion";
4717         /* @internal */
4718         ObjectFlags[ObjectFlags["ContainsWideningType"] = 524288] = "ContainsWideningType";
4719         /* @internal */
4720         ObjectFlags[ObjectFlags["ContainsObjectOrArrayLiteral"] = 1048576] = "ContainsObjectOrArrayLiteral";
4721         /* @internal */
4722         ObjectFlags[ObjectFlags["NonInferrableType"] = 2097152] = "NonInferrableType";
4723         /* @internal */
4724         ObjectFlags[ObjectFlags["IsGenericObjectTypeComputed"] = 4194304] = "IsGenericObjectTypeComputed";
4725         /* @internal */
4726         ObjectFlags[ObjectFlags["IsGenericObjectType"] = 8388608] = "IsGenericObjectType";
4727         /* @internal */
4728         ObjectFlags[ObjectFlags["IsGenericIndexTypeComputed"] = 16777216] = "IsGenericIndexTypeComputed";
4729         /* @internal */
4730         ObjectFlags[ObjectFlags["IsGenericIndexType"] = 33554432] = "IsGenericIndexType";
4731         /* @internal */
4732         ObjectFlags[ObjectFlags["CouldContainTypeVariablesComputed"] = 67108864] = "CouldContainTypeVariablesComputed";
4733         /* @internal */
4734         ObjectFlags[ObjectFlags["CouldContainTypeVariables"] = 134217728] = "CouldContainTypeVariables";
4735         /* @internal */
4736         ObjectFlags[ObjectFlags["ContainsIntersections"] = 268435456] = "ContainsIntersections";
4737         /* @internal */
4738         ObjectFlags[ObjectFlags["IsNeverIntersectionComputed"] = 268435456] = "IsNeverIntersectionComputed";
4739         /* @internal */
4740         ObjectFlags[ObjectFlags["IsNeverIntersection"] = 536870912] = "IsNeverIntersection";
4741         /* @internal */
4742         ObjectFlags[ObjectFlags["IsClassInstanceClone"] = 1073741824] = "IsClassInstanceClone";
4743         ObjectFlags[ObjectFlags["ClassOrInterface"] = 3] = "ClassOrInterface";
4744         /* @internal */
4745         ObjectFlags[ObjectFlags["RequiresWidening"] = 1572864] = "RequiresWidening";
4746         /* @internal */
4747         ObjectFlags[ObjectFlags["PropagatingFlags"] = 3670016] = "PropagatingFlags";
4748         // Object flags that uniquely identify the kind of ObjectType
4749         /* @internal */
4750         ObjectFlags[ObjectFlags["ObjectTypeKindMask"] = 2367] = "ObjectTypeKindMask";
4751     })(ObjectFlags = ts.ObjectFlags || (ts.ObjectFlags = {}));
4752     /* @internal */
4753     var VarianceFlags;
4754     (function (VarianceFlags) {
4755         VarianceFlags[VarianceFlags["Invariant"] = 0] = "Invariant";
4756         VarianceFlags[VarianceFlags["Covariant"] = 1] = "Covariant";
4757         VarianceFlags[VarianceFlags["Contravariant"] = 2] = "Contravariant";
4758         VarianceFlags[VarianceFlags["Bivariant"] = 3] = "Bivariant";
4759         VarianceFlags[VarianceFlags["Independent"] = 4] = "Independent";
4760         VarianceFlags[VarianceFlags["VarianceMask"] = 7] = "VarianceMask";
4761         VarianceFlags[VarianceFlags["Unmeasurable"] = 8] = "Unmeasurable";
4762         VarianceFlags[VarianceFlags["Unreliable"] = 16] = "Unreliable";
4763         VarianceFlags[VarianceFlags["AllowsStructuralFallback"] = 24] = "AllowsStructuralFallback";
4764     })(VarianceFlags = ts.VarianceFlags || (ts.VarianceFlags = {}));
4765     var ElementFlags;
4766     (function (ElementFlags) {
4767         ElementFlags[ElementFlags["Required"] = 1] = "Required";
4768         ElementFlags[ElementFlags["Optional"] = 2] = "Optional";
4769         ElementFlags[ElementFlags["Rest"] = 4] = "Rest";
4770         ElementFlags[ElementFlags["Variadic"] = 8] = "Variadic";
4771         ElementFlags[ElementFlags["Variable"] = 12] = "Variable";
4772     })(ElementFlags = ts.ElementFlags || (ts.ElementFlags = {}));
4773     /* @internal */
4774     var JsxReferenceKind;
4775     (function (JsxReferenceKind) {
4776         JsxReferenceKind[JsxReferenceKind["Component"] = 0] = "Component";
4777         JsxReferenceKind[JsxReferenceKind["Function"] = 1] = "Function";
4778         JsxReferenceKind[JsxReferenceKind["Mixed"] = 2] = "Mixed";
4779     })(JsxReferenceKind = ts.JsxReferenceKind || (ts.JsxReferenceKind = {}));
4780     var SignatureKind;
4781     (function (SignatureKind) {
4782         SignatureKind[SignatureKind["Call"] = 0] = "Call";
4783         SignatureKind[SignatureKind["Construct"] = 1] = "Construct";
4784     })(SignatureKind = ts.SignatureKind || (ts.SignatureKind = {}));
4785     /* @internal */
4786     var SignatureFlags;
4787     (function (SignatureFlags) {
4788         SignatureFlags[SignatureFlags["None"] = 0] = "None";
4789         SignatureFlags[SignatureFlags["HasRestParameter"] = 1] = "HasRestParameter";
4790         SignatureFlags[SignatureFlags["HasLiteralTypes"] = 2] = "HasLiteralTypes";
4791         SignatureFlags[SignatureFlags["IsInnerCallChain"] = 4] = "IsInnerCallChain";
4792         SignatureFlags[SignatureFlags["IsOuterCallChain"] = 8] = "IsOuterCallChain";
4793         SignatureFlags[SignatureFlags["IsUntypedSignatureInJSFile"] = 16] = "IsUntypedSignatureInJSFile";
4794         // We do not propagate `IsInnerCallChain` to instantiated signatures, as that would result in us
4795         // attempting to add `| undefined` on each recursive call to `getReturnTypeOfSignature` when
4796         // instantiating the return type.
4797         SignatureFlags[SignatureFlags["PropagatingFlags"] = 19] = "PropagatingFlags";
4798         SignatureFlags[SignatureFlags["CallChainFlags"] = 12] = "CallChainFlags";
4799     })(SignatureFlags = ts.SignatureFlags || (ts.SignatureFlags = {}));
4800     var IndexKind;
4801     (function (IndexKind) {
4802         IndexKind[IndexKind["String"] = 0] = "String";
4803         IndexKind[IndexKind["Number"] = 1] = "Number";
4804     })(IndexKind = ts.IndexKind || (ts.IndexKind = {}));
4805     /* @internal */
4806     var TypeMapKind;
4807     (function (TypeMapKind) {
4808         TypeMapKind[TypeMapKind["Simple"] = 0] = "Simple";
4809         TypeMapKind[TypeMapKind["Array"] = 1] = "Array";
4810         TypeMapKind[TypeMapKind["Function"] = 2] = "Function";
4811         TypeMapKind[TypeMapKind["Composite"] = 3] = "Composite";
4812         TypeMapKind[TypeMapKind["Merged"] = 4] = "Merged";
4813     })(TypeMapKind = ts.TypeMapKind || (ts.TypeMapKind = {}));
4814     var InferencePriority;
4815     (function (InferencePriority) {
4816         InferencePriority[InferencePriority["NakedTypeVariable"] = 1] = "NakedTypeVariable";
4817         InferencePriority[InferencePriority["SpeculativeTuple"] = 2] = "SpeculativeTuple";
4818         InferencePriority[InferencePriority["HomomorphicMappedType"] = 4] = "HomomorphicMappedType";
4819         InferencePriority[InferencePriority["PartialHomomorphicMappedType"] = 8] = "PartialHomomorphicMappedType";
4820         InferencePriority[InferencePriority["MappedTypeConstraint"] = 16] = "MappedTypeConstraint";
4821         InferencePriority[InferencePriority["ContravariantConditional"] = 32] = "ContravariantConditional";
4822         InferencePriority[InferencePriority["ReturnType"] = 64] = "ReturnType";
4823         InferencePriority[InferencePriority["LiteralKeyof"] = 128] = "LiteralKeyof";
4824         InferencePriority[InferencePriority["NoConstraints"] = 256] = "NoConstraints";
4825         InferencePriority[InferencePriority["AlwaysStrict"] = 512] = "AlwaysStrict";
4826         InferencePriority[InferencePriority["MaxValue"] = 1024] = "MaxValue";
4827         InferencePriority[InferencePriority["PriorityImpliesCombination"] = 208] = "PriorityImpliesCombination";
4828         InferencePriority[InferencePriority["Circularity"] = -1] = "Circularity";
4829     })(InferencePriority = ts.InferencePriority || (ts.InferencePriority = {}));
4830     /* @internal */
4831     var InferenceFlags;
4832     (function (InferenceFlags) {
4833         InferenceFlags[InferenceFlags["None"] = 0] = "None";
4834         InferenceFlags[InferenceFlags["NoDefault"] = 1] = "NoDefault";
4835         InferenceFlags[InferenceFlags["AnyDefault"] = 2] = "AnyDefault";
4836         InferenceFlags[InferenceFlags["SkippedGenericFunction"] = 4] = "SkippedGenericFunction";
4837     })(InferenceFlags = ts.InferenceFlags || (ts.InferenceFlags = {}));
4838     /**
4839      * Ternary values are defined such that
4840      * x & y picks the lesser in the order False < Unknown < Maybe < True, and
4841      * x | y picks the greater in the order False < Unknown < Maybe < True.
4842      * Generally, Ternary.Maybe is used as the result of a relation that depends on itself, and
4843      * Ternary.Unknown is used as the result of a variance check that depends on itself. We make
4844      * a distinction because we don't want to cache circular variance check results.
4845      */
4846     /* @internal */
4847     var Ternary;
4848     (function (Ternary) {
4849         Ternary[Ternary["False"] = 0] = "False";
4850         Ternary[Ternary["Unknown"] = 1] = "Unknown";
4851         Ternary[Ternary["Maybe"] = 3] = "Maybe";
4852         Ternary[Ternary["True"] = -1] = "True";
4853     })(Ternary = ts.Ternary || (ts.Ternary = {}));
4854     /* @internal */
4855     var AssignmentDeclarationKind;
4856     (function (AssignmentDeclarationKind) {
4857         AssignmentDeclarationKind[AssignmentDeclarationKind["None"] = 0] = "None";
4858         /// exports.name = expr
4859         /// module.exports.name = expr
4860         AssignmentDeclarationKind[AssignmentDeclarationKind["ExportsProperty"] = 1] = "ExportsProperty";
4861         /// module.exports = expr
4862         AssignmentDeclarationKind[AssignmentDeclarationKind["ModuleExports"] = 2] = "ModuleExports";
4863         /// className.prototype.name = expr
4864         AssignmentDeclarationKind[AssignmentDeclarationKind["PrototypeProperty"] = 3] = "PrototypeProperty";
4865         /// this.name = expr
4866         AssignmentDeclarationKind[AssignmentDeclarationKind["ThisProperty"] = 4] = "ThisProperty";
4867         // F.name = expr
4868         AssignmentDeclarationKind[AssignmentDeclarationKind["Property"] = 5] = "Property";
4869         // F.prototype = { ... }
4870         AssignmentDeclarationKind[AssignmentDeclarationKind["Prototype"] = 6] = "Prototype";
4871         // Object.defineProperty(x, 'name', { value: any, writable?: boolean (false by default) });
4872         // Object.defineProperty(x, 'name', { get: Function, set: Function });
4873         // Object.defineProperty(x, 'name', { get: Function });
4874         // Object.defineProperty(x, 'name', { set: Function });
4875         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyValue"] = 7] = "ObjectDefinePropertyValue";
4876         // Object.defineProperty(exports || module.exports, 'name', ...);
4877         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePropertyExports"] = 8] = "ObjectDefinePropertyExports";
4878         // Object.defineProperty(Foo.prototype, 'name', ...);
4879         AssignmentDeclarationKind[AssignmentDeclarationKind["ObjectDefinePrototypeProperty"] = 9] = "ObjectDefinePrototypeProperty";
4880     })(AssignmentDeclarationKind = ts.AssignmentDeclarationKind || (ts.AssignmentDeclarationKind = {}));
4881     var DiagnosticCategory;
4882     (function (DiagnosticCategory) {
4883         DiagnosticCategory[DiagnosticCategory["Warning"] = 0] = "Warning";
4884         DiagnosticCategory[DiagnosticCategory["Error"] = 1] = "Error";
4885         DiagnosticCategory[DiagnosticCategory["Suggestion"] = 2] = "Suggestion";
4886         DiagnosticCategory[DiagnosticCategory["Message"] = 3] = "Message";
4887     })(DiagnosticCategory = ts.DiagnosticCategory || (ts.DiagnosticCategory = {}));
4888     /* @internal */
4889     function diagnosticCategoryName(d, lowerCase) {
4890         if (lowerCase === void 0) { lowerCase = true; }
4891         var name = DiagnosticCategory[d.category];
4892         return lowerCase ? name.toLowerCase() : name;
4893     }
4894     ts.diagnosticCategoryName = diagnosticCategoryName;
4895     var ModuleResolutionKind;
4896     (function (ModuleResolutionKind) {
4897         ModuleResolutionKind[ModuleResolutionKind["Classic"] = 1] = "Classic";
4898         ModuleResolutionKind[ModuleResolutionKind["NodeJs"] = 2] = "NodeJs";
4899     })(ModuleResolutionKind = ts.ModuleResolutionKind || (ts.ModuleResolutionKind = {}));
4900     var WatchFileKind;
4901     (function (WatchFileKind) {
4902         WatchFileKind[WatchFileKind["FixedPollingInterval"] = 0] = "FixedPollingInterval";
4903         WatchFileKind[WatchFileKind["PriorityPollingInterval"] = 1] = "PriorityPollingInterval";
4904         WatchFileKind[WatchFileKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4905         WatchFileKind[WatchFileKind["UseFsEvents"] = 3] = "UseFsEvents";
4906         WatchFileKind[WatchFileKind["UseFsEventsOnParentDirectory"] = 4] = "UseFsEventsOnParentDirectory";
4907     })(WatchFileKind = ts.WatchFileKind || (ts.WatchFileKind = {}));
4908     var WatchDirectoryKind;
4909     (function (WatchDirectoryKind) {
4910         WatchDirectoryKind[WatchDirectoryKind["UseFsEvents"] = 0] = "UseFsEvents";
4911         WatchDirectoryKind[WatchDirectoryKind["FixedPollingInterval"] = 1] = "FixedPollingInterval";
4912         WatchDirectoryKind[WatchDirectoryKind["DynamicPriorityPolling"] = 2] = "DynamicPriorityPolling";
4913     })(WatchDirectoryKind = ts.WatchDirectoryKind || (ts.WatchDirectoryKind = {}));
4914     var PollingWatchKind;
4915     (function (PollingWatchKind) {
4916         PollingWatchKind[PollingWatchKind["FixedInterval"] = 0] = "FixedInterval";
4917         PollingWatchKind[PollingWatchKind["PriorityInterval"] = 1] = "PriorityInterval";
4918         PollingWatchKind[PollingWatchKind["DynamicPriority"] = 2] = "DynamicPriority";
4919     })(PollingWatchKind = ts.PollingWatchKind || (ts.PollingWatchKind = {}));
4920     var ModuleKind;
4921     (function (ModuleKind) {
4922         ModuleKind[ModuleKind["None"] = 0] = "None";
4923         ModuleKind[ModuleKind["CommonJS"] = 1] = "CommonJS";
4924         ModuleKind[ModuleKind["AMD"] = 2] = "AMD";
4925         ModuleKind[ModuleKind["UMD"] = 3] = "UMD";
4926         ModuleKind[ModuleKind["System"] = 4] = "System";
4927         // NOTE: ES module kinds should be contiguous to more easily check whether a module kind is *any* ES module kind.
4928         //       Non-ES module kinds should not come between ES2015 (the earliest ES module kind) and ESNext (the last ES
4929         //       module kind).
4930         ModuleKind[ModuleKind["ES2015"] = 5] = "ES2015";
4931         ModuleKind[ModuleKind["ES2020"] = 6] = "ES2020";
4932         ModuleKind[ModuleKind["ESNext"] = 99] = "ESNext";
4933     })(ModuleKind = ts.ModuleKind || (ts.ModuleKind = {}));
4934     var JsxEmit;
4935     (function (JsxEmit) {
4936         JsxEmit[JsxEmit["None"] = 0] = "None";
4937         JsxEmit[JsxEmit["Preserve"] = 1] = "Preserve";
4938         JsxEmit[JsxEmit["React"] = 2] = "React";
4939         JsxEmit[JsxEmit["ReactNative"] = 3] = "ReactNative";
4940         JsxEmit[JsxEmit["ReactJSX"] = 4] = "ReactJSX";
4941         JsxEmit[JsxEmit["ReactJSXDev"] = 5] = "ReactJSXDev";
4942     })(JsxEmit = ts.JsxEmit || (ts.JsxEmit = {}));
4943     var ImportsNotUsedAsValues;
4944     (function (ImportsNotUsedAsValues) {
4945         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Remove"] = 0] = "Remove";
4946         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Preserve"] = 1] = "Preserve";
4947         ImportsNotUsedAsValues[ImportsNotUsedAsValues["Error"] = 2] = "Error";
4948     })(ImportsNotUsedAsValues = ts.ImportsNotUsedAsValues || (ts.ImportsNotUsedAsValues = {}));
4949     var NewLineKind;
4950     (function (NewLineKind) {
4951         NewLineKind[NewLineKind["CarriageReturnLineFeed"] = 0] = "CarriageReturnLineFeed";
4952         NewLineKind[NewLineKind["LineFeed"] = 1] = "LineFeed";
4953     })(NewLineKind = ts.NewLineKind || (ts.NewLineKind = {}));
4954     var ScriptKind;
4955     (function (ScriptKind) {
4956         ScriptKind[ScriptKind["Unknown"] = 0] = "Unknown";
4957         ScriptKind[ScriptKind["JS"] = 1] = "JS";
4958         ScriptKind[ScriptKind["JSX"] = 2] = "JSX";
4959         ScriptKind[ScriptKind["TS"] = 3] = "TS";
4960         ScriptKind[ScriptKind["TSX"] = 4] = "TSX";
4961         ScriptKind[ScriptKind["External"] = 5] = "External";
4962         ScriptKind[ScriptKind["JSON"] = 6] = "JSON";
4963         /**
4964          * Used on extensions that doesn't define the ScriptKind but the content defines it.
4965          * Deferred extensions are going to be included in all project contexts.
4966          */
4967         ScriptKind[ScriptKind["Deferred"] = 7] = "Deferred";
4968     })(ScriptKind = ts.ScriptKind || (ts.ScriptKind = {}));
4969     var ScriptTarget;
4970     (function (ScriptTarget) {
4971         ScriptTarget[ScriptTarget["ES3"] = 0] = "ES3";
4972         ScriptTarget[ScriptTarget["ES5"] = 1] = "ES5";
4973         ScriptTarget[ScriptTarget["ES2015"] = 2] = "ES2015";
4974         ScriptTarget[ScriptTarget["ES2016"] = 3] = "ES2016";
4975         ScriptTarget[ScriptTarget["ES2017"] = 4] = "ES2017";
4976         ScriptTarget[ScriptTarget["ES2018"] = 5] = "ES2018";
4977         ScriptTarget[ScriptTarget["ES2019"] = 6] = "ES2019";
4978         ScriptTarget[ScriptTarget["ES2020"] = 7] = "ES2020";
4979         ScriptTarget[ScriptTarget["ESNext"] = 99] = "ESNext";
4980         ScriptTarget[ScriptTarget["JSON"] = 100] = "JSON";
4981         ScriptTarget[ScriptTarget["Latest"] = 99] = "Latest";
4982     })(ScriptTarget = ts.ScriptTarget || (ts.ScriptTarget = {}));
4983     var LanguageVariant;
4984     (function (LanguageVariant) {
4985         LanguageVariant[LanguageVariant["Standard"] = 0] = "Standard";
4986         LanguageVariant[LanguageVariant["JSX"] = 1] = "JSX";
4987     })(LanguageVariant = ts.LanguageVariant || (ts.LanguageVariant = {}));
4988     var WatchDirectoryFlags;
4989     (function (WatchDirectoryFlags) {
4990         WatchDirectoryFlags[WatchDirectoryFlags["None"] = 0] = "None";
4991         WatchDirectoryFlags[WatchDirectoryFlags["Recursive"] = 1] = "Recursive";
4992     })(WatchDirectoryFlags = ts.WatchDirectoryFlags || (ts.WatchDirectoryFlags = {}));
4993     /* @internal */
4994     var CharacterCodes;
4995     (function (CharacterCodes) {
4996         CharacterCodes[CharacterCodes["nullCharacter"] = 0] = "nullCharacter";
4997         CharacterCodes[CharacterCodes["maxAsciiCharacter"] = 127] = "maxAsciiCharacter";
4998         CharacterCodes[CharacterCodes["lineFeed"] = 10] = "lineFeed";
4999         CharacterCodes[CharacterCodes["carriageReturn"] = 13] = "carriageReturn";
5000         CharacterCodes[CharacterCodes["lineSeparator"] = 8232] = "lineSeparator";
5001         CharacterCodes[CharacterCodes["paragraphSeparator"] = 8233] = "paragraphSeparator";
5002         CharacterCodes[CharacterCodes["nextLine"] = 133] = "nextLine";
5003         // Unicode 3.0 space characters
5004         CharacterCodes[CharacterCodes["space"] = 32] = "space";
5005         CharacterCodes[CharacterCodes["nonBreakingSpace"] = 160] = "nonBreakingSpace";
5006         CharacterCodes[CharacterCodes["enQuad"] = 8192] = "enQuad";
5007         CharacterCodes[CharacterCodes["emQuad"] = 8193] = "emQuad";
5008         CharacterCodes[CharacterCodes["enSpace"] = 8194] = "enSpace";
5009         CharacterCodes[CharacterCodes["emSpace"] = 8195] = "emSpace";
5010         CharacterCodes[CharacterCodes["threePerEmSpace"] = 8196] = "threePerEmSpace";
5011         CharacterCodes[CharacterCodes["fourPerEmSpace"] = 8197] = "fourPerEmSpace";
5012         CharacterCodes[CharacterCodes["sixPerEmSpace"] = 8198] = "sixPerEmSpace";
5013         CharacterCodes[CharacterCodes["figureSpace"] = 8199] = "figureSpace";
5014         CharacterCodes[CharacterCodes["punctuationSpace"] = 8200] = "punctuationSpace";
5015         CharacterCodes[CharacterCodes["thinSpace"] = 8201] = "thinSpace";
5016         CharacterCodes[CharacterCodes["hairSpace"] = 8202] = "hairSpace";
5017         CharacterCodes[CharacterCodes["zeroWidthSpace"] = 8203] = "zeroWidthSpace";
5018         CharacterCodes[CharacterCodes["narrowNoBreakSpace"] = 8239] = "narrowNoBreakSpace";
5019         CharacterCodes[CharacterCodes["ideographicSpace"] = 12288] = "ideographicSpace";
5020         CharacterCodes[CharacterCodes["mathematicalSpace"] = 8287] = "mathematicalSpace";
5021         CharacterCodes[CharacterCodes["ogham"] = 5760] = "ogham";
5022         CharacterCodes[CharacterCodes["_"] = 95] = "_";
5023         CharacterCodes[CharacterCodes["$"] = 36] = "$";
5024         CharacterCodes[CharacterCodes["_0"] = 48] = "_0";
5025         CharacterCodes[CharacterCodes["_1"] = 49] = "_1";
5026         CharacterCodes[CharacterCodes["_2"] = 50] = "_2";
5027         CharacterCodes[CharacterCodes["_3"] = 51] = "_3";
5028         CharacterCodes[CharacterCodes["_4"] = 52] = "_4";
5029         CharacterCodes[CharacterCodes["_5"] = 53] = "_5";
5030         CharacterCodes[CharacterCodes["_6"] = 54] = "_6";
5031         CharacterCodes[CharacterCodes["_7"] = 55] = "_7";
5032         CharacterCodes[CharacterCodes["_8"] = 56] = "_8";
5033         CharacterCodes[CharacterCodes["_9"] = 57] = "_9";
5034         CharacterCodes[CharacterCodes["a"] = 97] = "a";
5035         CharacterCodes[CharacterCodes["b"] = 98] = "b";
5036         CharacterCodes[CharacterCodes["c"] = 99] = "c";
5037         CharacterCodes[CharacterCodes["d"] = 100] = "d";
5038         CharacterCodes[CharacterCodes["e"] = 101] = "e";
5039         CharacterCodes[CharacterCodes["f"] = 102] = "f";
5040         CharacterCodes[CharacterCodes["g"] = 103] = "g";
5041         CharacterCodes[CharacterCodes["h"] = 104] = "h";
5042         CharacterCodes[CharacterCodes["i"] = 105] = "i";
5043         CharacterCodes[CharacterCodes["j"] = 106] = "j";
5044         CharacterCodes[CharacterCodes["k"] = 107] = "k";
5045         CharacterCodes[CharacterCodes["l"] = 108] = "l";
5046         CharacterCodes[CharacterCodes["m"] = 109] = "m";
5047         CharacterCodes[CharacterCodes["n"] = 110] = "n";
5048         CharacterCodes[CharacterCodes["o"] = 111] = "o";
5049         CharacterCodes[CharacterCodes["p"] = 112] = "p";
5050         CharacterCodes[CharacterCodes["q"] = 113] = "q";
5051         CharacterCodes[CharacterCodes["r"] = 114] = "r";
5052         CharacterCodes[CharacterCodes["s"] = 115] = "s";
5053         CharacterCodes[CharacterCodes["t"] = 116] = "t";
5054         CharacterCodes[CharacterCodes["u"] = 117] = "u";
5055         CharacterCodes[CharacterCodes["v"] = 118] = "v";
5056         CharacterCodes[CharacterCodes["w"] = 119] = "w";
5057         CharacterCodes[CharacterCodes["x"] = 120] = "x";
5058         CharacterCodes[CharacterCodes["y"] = 121] = "y";
5059         CharacterCodes[CharacterCodes["z"] = 122] = "z";
5060         CharacterCodes[CharacterCodes["A"] = 65] = "A";
5061         CharacterCodes[CharacterCodes["B"] = 66] = "B";
5062         CharacterCodes[CharacterCodes["C"] = 67] = "C";
5063         CharacterCodes[CharacterCodes["D"] = 68] = "D";
5064         CharacterCodes[CharacterCodes["E"] = 69] = "E";
5065         CharacterCodes[CharacterCodes["F"] = 70] = "F";
5066         CharacterCodes[CharacterCodes["G"] = 71] = "G";
5067         CharacterCodes[CharacterCodes["H"] = 72] = "H";
5068         CharacterCodes[CharacterCodes["I"] = 73] = "I";
5069         CharacterCodes[CharacterCodes["J"] = 74] = "J";
5070         CharacterCodes[CharacterCodes["K"] = 75] = "K";
5071         CharacterCodes[CharacterCodes["L"] = 76] = "L";
5072         CharacterCodes[CharacterCodes["M"] = 77] = "M";
5073         CharacterCodes[CharacterCodes["N"] = 78] = "N";
5074         CharacterCodes[CharacterCodes["O"] = 79] = "O";
5075         CharacterCodes[CharacterCodes["P"] = 80] = "P";
5076         CharacterCodes[CharacterCodes["Q"] = 81] = "Q";
5077         CharacterCodes[CharacterCodes["R"] = 82] = "R";
5078         CharacterCodes[CharacterCodes["S"] = 83] = "S";
5079         CharacterCodes[CharacterCodes["T"] = 84] = "T";
5080         CharacterCodes[CharacterCodes["U"] = 85] = "U";
5081         CharacterCodes[CharacterCodes["V"] = 86] = "V";
5082         CharacterCodes[CharacterCodes["W"] = 87] = "W";
5083         CharacterCodes[CharacterCodes["X"] = 88] = "X";
5084         CharacterCodes[CharacterCodes["Y"] = 89] = "Y";
5085         CharacterCodes[CharacterCodes["Z"] = 90] = "Z";
5086         CharacterCodes[CharacterCodes["ampersand"] = 38] = "ampersand";
5087         CharacterCodes[CharacterCodes["asterisk"] = 42] = "asterisk";
5088         CharacterCodes[CharacterCodes["at"] = 64] = "at";
5089         CharacterCodes[CharacterCodes["backslash"] = 92] = "backslash";
5090         CharacterCodes[CharacterCodes["backtick"] = 96] = "backtick";
5091         CharacterCodes[CharacterCodes["bar"] = 124] = "bar";
5092         CharacterCodes[CharacterCodes["caret"] = 94] = "caret";
5093         CharacterCodes[CharacterCodes["closeBrace"] = 125] = "closeBrace";
5094         CharacterCodes[CharacterCodes["closeBracket"] = 93] = "closeBracket";
5095         CharacterCodes[CharacterCodes["closeParen"] = 41] = "closeParen";
5096         CharacterCodes[CharacterCodes["colon"] = 58] = "colon";
5097         CharacterCodes[CharacterCodes["comma"] = 44] = "comma";
5098         CharacterCodes[CharacterCodes["dot"] = 46] = "dot";
5099         CharacterCodes[CharacterCodes["doubleQuote"] = 34] = "doubleQuote";
5100         CharacterCodes[CharacterCodes["equals"] = 61] = "equals";
5101         CharacterCodes[CharacterCodes["exclamation"] = 33] = "exclamation";
5102         CharacterCodes[CharacterCodes["greaterThan"] = 62] = "greaterThan";
5103         CharacterCodes[CharacterCodes["hash"] = 35] = "hash";
5104         CharacterCodes[CharacterCodes["lessThan"] = 60] = "lessThan";
5105         CharacterCodes[CharacterCodes["minus"] = 45] = "minus";
5106         CharacterCodes[CharacterCodes["openBrace"] = 123] = "openBrace";
5107         CharacterCodes[CharacterCodes["openBracket"] = 91] = "openBracket";
5108         CharacterCodes[CharacterCodes["openParen"] = 40] = "openParen";
5109         CharacterCodes[CharacterCodes["percent"] = 37] = "percent";
5110         CharacterCodes[CharacterCodes["plus"] = 43] = "plus";
5111         CharacterCodes[CharacterCodes["question"] = 63] = "question";
5112         CharacterCodes[CharacterCodes["semicolon"] = 59] = "semicolon";
5113         CharacterCodes[CharacterCodes["singleQuote"] = 39] = "singleQuote";
5114         CharacterCodes[CharacterCodes["slash"] = 47] = "slash";
5115         CharacterCodes[CharacterCodes["tilde"] = 126] = "tilde";
5116         CharacterCodes[CharacterCodes["backspace"] = 8] = "backspace";
5117         CharacterCodes[CharacterCodes["formFeed"] = 12] = "formFeed";
5118         CharacterCodes[CharacterCodes["byteOrderMark"] = 65279] = "byteOrderMark";
5119         CharacterCodes[CharacterCodes["tab"] = 9] = "tab";
5120         CharacterCodes[CharacterCodes["verticalTab"] = 11] = "verticalTab";
5121     })(CharacterCodes = ts.CharacterCodes || (ts.CharacterCodes = {}));
5122     var Extension;
5123     (function (Extension) {
5124         Extension["Ts"] = ".ts";
5125         Extension["Tsx"] = ".tsx";
5126         Extension["Dts"] = ".d.ts";
5127         Extension["Js"] = ".js";
5128         Extension["Jsx"] = ".jsx";
5129         Extension["Json"] = ".json";
5130         Extension["TsBuildInfo"] = ".tsbuildinfo";
5131     })(Extension = ts.Extension || (ts.Extension = {}));
5132     /* @internal */
5133     var TransformFlags;
5134     (function (TransformFlags) {
5135         TransformFlags[TransformFlags["None"] = 0] = "None";
5136         // Facts
5137         // - Flags used to indicate that a node or subtree contains syntax that requires transformation.
5138         TransformFlags[TransformFlags["ContainsTypeScript"] = 1] = "ContainsTypeScript";
5139         TransformFlags[TransformFlags["ContainsJsx"] = 2] = "ContainsJsx";
5140         TransformFlags[TransformFlags["ContainsESNext"] = 4] = "ContainsESNext";
5141         TransformFlags[TransformFlags["ContainsES2020"] = 8] = "ContainsES2020";
5142         TransformFlags[TransformFlags["ContainsES2019"] = 16] = "ContainsES2019";
5143         TransformFlags[TransformFlags["ContainsES2018"] = 32] = "ContainsES2018";
5144         TransformFlags[TransformFlags["ContainsES2017"] = 64] = "ContainsES2017";
5145         TransformFlags[TransformFlags["ContainsES2016"] = 128] = "ContainsES2016";
5146         TransformFlags[TransformFlags["ContainsES2015"] = 256] = "ContainsES2015";
5147         TransformFlags[TransformFlags["ContainsGenerator"] = 512] = "ContainsGenerator";
5148         TransformFlags[TransformFlags["ContainsDestructuringAssignment"] = 1024] = "ContainsDestructuringAssignment";
5149         // Markers
5150         // - Flags used to indicate that a subtree contains a specific transformation.
5151         TransformFlags[TransformFlags["ContainsTypeScriptClassSyntax"] = 2048] = "ContainsTypeScriptClassSyntax";
5152         TransformFlags[TransformFlags["ContainsLexicalThis"] = 4096] = "ContainsLexicalThis";
5153         TransformFlags[TransformFlags["ContainsRestOrSpread"] = 8192] = "ContainsRestOrSpread";
5154         TransformFlags[TransformFlags["ContainsObjectRestOrSpread"] = 16384] = "ContainsObjectRestOrSpread";
5155         TransformFlags[TransformFlags["ContainsComputedPropertyName"] = 32768] = "ContainsComputedPropertyName";
5156         TransformFlags[TransformFlags["ContainsBlockScopedBinding"] = 65536] = "ContainsBlockScopedBinding";
5157         TransformFlags[TransformFlags["ContainsBindingPattern"] = 131072] = "ContainsBindingPattern";
5158         TransformFlags[TransformFlags["ContainsYield"] = 262144] = "ContainsYield";
5159         TransformFlags[TransformFlags["ContainsAwait"] = 524288] = "ContainsAwait";
5160         TransformFlags[TransformFlags["ContainsHoistedDeclarationOrCompletion"] = 1048576] = "ContainsHoistedDeclarationOrCompletion";
5161         TransformFlags[TransformFlags["ContainsDynamicImport"] = 2097152] = "ContainsDynamicImport";
5162         TransformFlags[TransformFlags["ContainsClassFields"] = 4194304] = "ContainsClassFields";
5163         TransformFlags[TransformFlags["ContainsPossibleTopLevelAwait"] = 8388608] = "ContainsPossibleTopLevelAwait";
5164         // Please leave this as 1 << 29.
5165         // It is the maximum bit we can set before we outgrow the size of a v8 small integer (SMI) on an x86 system.
5166         // It is a good reminder of how much room we have left
5167         TransformFlags[TransformFlags["HasComputedFlags"] = 536870912] = "HasComputedFlags";
5168         // Assertions
5169         // - Bitmasks that are used to assert facts about the syntax of a node and its subtree.
5170         TransformFlags[TransformFlags["AssertTypeScript"] = 1] = "AssertTypeScript";
5171         TransformFlags[TransformFlags["AssertJsx"] = 2] = "AssertJsx";
5172         TransformFlags[TransformFlags["AssertESNext"] = 4] = "AssertESNext";
5173         TransformFlags[TransformFlags["AssertES2020"] = 8] = "AssertES2020";
5174         TransformFlags[TransformFlags["AssertES2019"] = 16] = "AssertES2019";
5175         TransformFlags[TransformFlags["AssertES2018"] = 32] = "AssertES2018";
5176         TransformFlags[TransformFlags["AssertES2017"] = 64] = "AssertES2017";
5177         TransformFlags[TransformFlags["AssertES2016"] = 128] = "AssertES2016";
5178         TransformFlags[TransformFlags["AssertES2015"] = 256] = "AssertES2015";
5179         TransformFlags[TransformFlags["AssertGenerator"] = 512] = "AssertGenerator";
5180         TransformFlags[TransformFlags["AssertDestructuringAssignment"] = 1024] = "AssertDestructuringAssignment";
5181         // Scope Exclusions
5182         // - Bitmasks that exclude flags from propagating out of a specific context
5183         //   into the subtree flags of their container.
5184         TransformFlags[TransformFlags["OuterExpressionExcludes"] = 536870912] = "OuterExpressionExcludes";
5185         TransformFlags[TransformFlags["PropertyAccessExcludes"] = 536870912] = "PropertyAccessExcludes";
5186         TransformFlags[TransformFlags["NodeExcludes"] = 536870912] = "NodeExcludes";
5187         TransformFlags[TransformFlags["ArrowFunctionExcludes"] = 547309568] = "ArrowFunctionExcludes";
5188         TransformFlags[TransformFlags["FunctionExcludes"] = 547313664] = "FunctionExcludes";
5189         TransformFlags[TransformFlags["ConstructorExcludes"] = 547311616] = "ConstructorExcludes";
5190         TransformFlags[TransformFlags["MethodOrAccessorExcludes"] = 538923008] = "MethodOrAccessorExcludes";
5191         TransformFlags[TransformFlags["PropertyExcludes"] = 536875008] = "PropertyExcludes";
5192         TransformFlags[TransformFlags["ClassExcludes"] = 536905728] = "ClassExcludes";
5193         TransformFlags[TransformFlags["ModuleExcludes"] = 546379776] = "ModuleExcludes";
5194         TransformFlags[TransformFlags["TypeExcludes"] = -2] = "TypeExcludes";
5195         TransformFlags[TransformFlags["ObjectLiteralExcludes"] = 536922112] = "ObjectLiteralExcludes";
5196         TransformFlags[TransformFlags["ArrayLiteralOrCallOrNewExcludes"] = 536879104] = "ArrayLiteralOrCallOrNewExcludes";
5197         TransformFlags[TransformFlags["VariableDeclarationListExcludes"] = 537018368] = "VariableDeclarationListExcludes";
5198         TransformFlags[TransformFlags["ParameterExcludes"] = 536870912] = "ParameterExcludes";
5199         TransformFlags[TransformFlags["CatchClauseExcludes"] = 536887296] = "CatchClauseExcludes";
5200         TransformFlags[TransformFlags["BindingPatternExcludes"] = 536879104] = "BindingPatternExcludes";
5201         // Propagating flags
5202         // - Bitmasks for flags that should propagate from a child
5203         TransformFlags[TransformFlags["PropertyNamePropagatingFlags"] = 4096] = "PropertyNamePropagatingFlags";
5204         // Masks
5205         // - Additional bitmasks
5206     })(TransformFlags = ts.TransformFlags || (ts.TransformFlags = {}));
5207     var EmitFlags;
5208     (function (EmitFlags) {
5209         EmitFlags[EmitFlags["None"] = 0] = "None";
5210         EmitFlags[EmitFlags["SingleLine"] = 1] = "SingleLine";
5211         EmitFlags[EmitFlags["AdviseOnEmitNode"] = 2] = "AdviseOnEmitNode";
5212         EmitFlags[EmitFlags["NoSubstitution"] = 4] = "NoSubstitution";
5213         EmitFlags[EmitFlags["CapturesThis"] = 8] = "CapturesThis";
5214         EmitFlags[EmitFlags["NoLeadingSourceMap"] = 16] = "NoLeadingSourceMap";
5215         EmitFlags[EmitFlags["NoTrailingSourceMap"] = 32] = "NoTrailingSourceMap";
5216         EmitFlags[EmitFlags["NoSourceMap"] = 48] = "NoSourceMap";
5217         EmitFlags[EmitFlags["NoNestedSourceMaps"] = 64] = "NoNestedSourceMaps";
5218         EmitFlags[EmitFlags["NoTokenLeadingSourceMaps"] = 128] = "NoTokenLeadingSourceMaps";
5219         EmitFlags[EmitFlags["NoTokenTrailingSourceMaps"] = 256] = "NoTokenTrailingSourceMaps";
5220         EmitFlags[EmitFlags["NoTokenSourceMaps"] = 384] = "NoTokenSourceMaps";
5221         EmitFlags[EmitFlags["NoLeadingComments"] = 512] = "NoLeadingComments";
5222         EmitFlags[EmitFlags["NoTrailingComments"] = 1024] = "NoTrailingComments";
5223         EmitFlags[EmitFlags["NoComments"] = 1536] = "NoComments";
5224         EmitFlags[EmitFlags["NoNestedComments"] = 2048] = "NoNestedComments";
5225         EmitFlags[EmitFlags["HelperName"] = 4096] = "HelperName";
5226         EmitFlags[EmitFlags["ExportName"] = 8192] = "ExportName";
5227         EmitFlags[EmitFlags["LocalName"] = 16384] = "LocalName";
5228         EmitFlags[EmitFlags["InternalName"] = 32768] = "InternalName";
5229         EmitFlags[EmitFlags["Indented"] = 65536] = "Indented";
5230         EmitFlags[EmitFlags["NoIndentation"] = 131072] = "NoIndentation";
5231         EmitFlags[EmitFlags["AsyncFunctionBody"] = 262144] = "AsyncFunctionBody";
5232         EmitFlags[EmitFlags["ReuseTempVariableScope"] = 524288] = "ReuseTempVariableScope";
5233         EmitFlags[EmitFlags["CustomPrologue"] = 1048576] = "CustomPrologue";
5234         EmitFlags[EmitFlags["NoHoisting"] = 2097152] = "NoHoisting";
5235         EmitFlags[EmitFlags["HasEndOfDeclarationMarker"] = 4194304] = "HasEndOfDeclarationMarker";
5236         EmitFlags[EmitFlags["Iterator"] = 8388608] = "Iterator";
5237         EmitFlags[EmitFlags["NoAsciiEscaping"] = 16777216] = "NoAsciiEscaping";
5238         /*@internal*/ EmitFlags[EmitFlags["TypeScriptClassWrapper"] = 33554432] = "TypeScriptClassWrapper";
5239         /*@internal*/ EmitFlags[EmitFlags["NeverApplyImportHelper"] = 67108864] = "NeverApplyImportHelper";
5240         /*@internal*/ EmitFlags[EmitFlags["IgnoreSourceNewlines"] = 134217728] = "IgnoreSourceNewlines";
5241     })(EmitFlags = ts.EmitFlags || (ts.EmitFlags = {}));
5242     /**
5243      * Used by the checker, this enum keeps track of external emit helpers that should be type
5244      * checked.
5245      */
5246     /* @internal */
5247     var ExternalEmitHelpers;
5248     (function (ExternalEmitHelpers) {
5249         ExternalEmitHelpers[ExternalEmitHelpers["Extends"] = 1] = "Extends";
5250         ExternalEmitHelpers[ExternalEmitHelpers["Assign"] = 2] = "Assign";
5251         ExternalEmitHelpers[ExternalEmitHelpers["Rest"] = 4] = "Rest";
5252         ExternalEmitHelpers[ExternalEmitHelpers["Decorate"] = 8] = "Decorate";
5253         ExternalEmitHelpers[ExternalEmitHelpers["Metadata"] = 16] = "Metadata";
5254         ExternalEmitHelpers[ExternalEmitHelpers["Param"] = 32] = "Param";
5255         ExternalEmitHelpers[ExternalEmitHelpers["Awaiter"] = 64] = "Awaiter";
5256         ExternalEmitHelpers[ExternalEmitHelpers["Generator"] = 128] = "Generator";
5257         ExternalEmitHelpers[ExternalEmitHelpers["Values"] = 256] = "Values";
5258         ExternalEmitHelpers[ExternalEmitHelpers["Read"] = 512] = "Read";
5259         ExternalEmitHelpers[ExternalEmitHelpers["Spread"] = 1024] = "Spread";
5260         ExternalEmitHelpers[ExternalEmitHelpers["SpreadArrays"] = 2048] = "SpreadArrays";
5261         ExternalEmitHelpers[ExternalEmitHelpers["Await"] = 4096] = "Await";
5262         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGenerator"] = 8192] = "AsyncGenerator";
5263         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegator"] = 16384] = "AsyncDelegator";
5264         ExternalEmitHelpers[ExternalEmitHelpers["AsyncValues"] = 32768] = "AsyncValues";
5265         ExternalEmitHelpers[ExternalEmitHelpers["ExportStar"] = 65536] = "ExportStar";
5266         ExternalEmitHelpers[ExternalEmitHelpers["ImportStar"] = 131072] = "ImportStar";
5267         ExternalEmitHelpers[ExternalEmitHelpers["ImportDefault"] = 262144] = "ImportDefault";
5268         ExternalEmitHelpers[ExternalEmitHelpers["MakeTemplateObject"] = 524288] = "MakeTemplateObject";
5269         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldGet"] = 1048576] = "ClassPrivateFieldGet";
5270         ExternalEmitHelpers[ExternalEmitHelpers["ClassPrivateFieldSet"] = 2097152] = "ClassPrivateFieldSet";
5271         ExternalEmitHelpers[ExternalEmitHelpers["CreateBinding"] = 4194304] = "CreateBinding";
5272         ExternalEmitHelpers[ExternalEmitHelpers["FirstEmitHelper"] = 1] = "FirstEmitHelper";
5273         ExternalEmitHelpers[ExternalEmitHelpers["LastEmitHelper"] = 4194304] = "LastEmitHelper";
5274         // Helpers included by ES2015 for..of
5275         ExternalEmitHelpers[ExternalEmitHelpers["ForOfIncludes"] = 256] = "ForOfIncludes";
5276         // Helpers included by ES2017 for..await..of
5277         ExternalEmitHelpers[ExternalEmitHelpers["ForAwaitOfIncludes"] = 32768] = "ForAwaitOfIncludes";
5278         // Helpers included by ES2017 async generators
5279         ExternalEmitHelpers[ExternalEmitHelpers["AsyncGeneratorIncludes"] = 12288] = "AsyncGeneratorIncludes";
5280         // Helpers included by yield* in ES2017 async generators
5281         ExternalEmitHelpers[ExternalEmitHelpers["AsyncDelegatorIncludes"] = 53248] = "AsyncDelegatorIncludes";
5282         // Helpers included by ES2015 spread
5283         ExternalEmitHelpers[ExternalEmitHelpers["SpreadIncludes"] = 1536] = "SpreadIncludes";
5284     })(ExternalEmitHelpers = ts.ExternalEmitHelpers || (ts.ExternalEmitHelpers = {}));
5285     var EmitHint;
5286     (function (EmitHint) {
5287         EmitHint[EmitHint["SourceFile"] = 0] = "SourceFile";
5288         EmitHint[EmitHint["Expression"] = 1] = "Expression";
5289         EmitHint[EmitHint["IdentifierName"] = 2] = "IdentifierName";
5290         EmitHint[EmitHint["MappedTypeParameter"] = 3] = "MappedTypeParameter";
5291         EmitHint[EmitHint["Unspecified"] = 4] = "Unspecified";
5292         EmitHint[EmitHint["EmbeddedStatement"] = 5] = "EmbeddedStatement";
5293         EmitHint[EmitHint["JsxAttributeValue"] = 6] = "JsxAttributeValue";
5294     })(EmitHint = ts.EmitHint || (ts.EmitHint = {}));
5295     var OuterExpressionKinds;
5296     (function (OuterExpressionKinds) {
5297         OuterExpressionKinds[OuterExpressionKinds["Parentheses"] = 1] = "Parentheses";
5298         OuterExpressionKinds[OuterExpressionKinds["TypeAssertions"] = 2] = "TypeAssertions";
5299         OuterExpressionKinds[OuterExpressionKinds["NonNullAssertions"] = 4] = "NonNullAssertions";
5300         OuterExpressionKinds[OuterExpressionKinds["PartiallyEmittedExpressions"] = 8] = "PartiallyEmittedExpressions";
5301         OuterExpressionKinds[OuterExpressionKinds["Assertions"] = 6] = "Assertions";
5302         OuterExpressionKinds[OuterExpressionKinds["All"] = 15] = "All";
5303     })(OuterExpressionKinds = ts.OuterExpressionKinds || (ts.OuterExpressionKinds = {}));
5304     /* @internal */
5305     var LexicalEnvironmentFlags;
5306     (function (LexicalEnvironmentFlags) {
5307         LexicalEnvironmentFlags[LexicalEnvironmentFlags["None"] = 0] = "None";
5308         LexicalEnvironmentFlags[LexicalEnvironmentFlags["InParameters"] = 1] = "InParameters";
5309         LexicalEnvironmentFlags[LexicalEnvironmentFlags["VariablesHoistedInParameters"] = 2] = "VariablesHoistedInParameters"; // a temp variable was hoisted while visiting a parameter list
5310     })(LexicalEnvironmentFlags = ts.LexicalEnvironmentFlags || (ts.LexicalEnvironmentFlags = {}));
5311     /*@internal*/
5312     var BundleFileSectionKind;
5313     (function (BundleFileSectionKind) {
5314         BundleFileSectionKind["Prologue"] = "prologue";
5315         BundleFileSectionKind["EmitHelpers"] = "emitHelpers";
5316         BundleFileSectionKind["NoDefaultLib"] = "no-default-lib";
5317         BundleFileSectionKind["Reference"] = "reference";
5318         BundleFileSectionKind["Type"] = "type";
5319         BundleFileSectionKind["Lib"] = "lib";
5320         BundleFileSectionKind["Prepend"] = "prepend";
5321         BundleFileSectionKind["Text"] = "text";
5322         BundleFileSectionKind["Internal"] = "internal";
5323         // comments?
5324     })(BundleFileSectionKind = ts.BundleFileSectionKind || (ts.BundleFileSectionKind = {}));
5325     var ListFormat;
5326     (function (ListFormat) {
5327         ListFormat[ListFormat["None"] = 0] = "None";
5328         // Line separators
5329         ListFormat[ListFormat["SingleLine"] = 0] = "SingleLine";
5330         ListFormat[ListFormat["MultiLine"] = 1] = "MultiLine";
5331         ListFormat[ListFormat["PreserveLines"] = 2] = "PreserveLines";
5332         ListFormat[ListFormat["LinesMask"] = 3] = "LinesMask";
5333         // Delimiters
5334         ListFormat[ListFormat["NotDelimited"] = 0] = "NotDelimited";
5335         ListFormat[ListFormat["BarDelimited"] = 4] = "BarDelimited";
5336         ListFormat[ListFormat["AmpersandDelimited"] = 8] = "AmpersandDelimited";
5337         ListFormat[ListFormat["CommaDelimited"] = 16] = "CommaDelimited";
5338         ListFormat[ListFormat["AsteriskDelimited"] = 32] = "AsteriskDelimited";
5339         ListFormat[ListFormat["DelimitersMask"] = 60] = "DelimitersMask";
5340         ListFormat[ListFormat["AllowTrailingComma"] = 64] = "AllowTrailingComma";
5341         // Whitespace
5342         ListFormat[ListFormat["Indented"] = 128] = "Indented";
5343         ListFormat[ListFormat["SpaceBetweenBraces"] = 256] = "SpaceBetweenBraces";
5344         ListFormat[ListFormat["SpaceBetweenSiblings"] = 512] = "SpaceBetweenSiblings";
5345         // Brackets/Braces
5346         ListFormat[ListFormat["Braces"] = 1024] = "Braces";
5347         ListFormat[ListFormat["Parenthesis"] = 2048] = "Parenthesis";
5348         ListFormat[ListFormat["AngleBrackets"] = 4096] = "AngleBrackets";
5349         ListFormat[ListFormat["SquareBrackets"] = 8192] = "SquareBrackets";
5350         ListFormat[ListFormat["BracketsMask"] = 15360] = "BracketsMask";
5351         ListFormat[ListFormat["OptionalIfUndefined"] = 16384] = "OptionalIfUndefined";
5352         ListFormat[ListFormat["OptionalIfEmpty"] = 32768] = "OptionalIfEmpty";
5353         ListFormat[ListFormat["Optional"] = 49152] = "Optional";
5354         // Other
5355         ListFormat[ListFormat["PreferNewLine"] = 65536] = "PreferNewLine";
5356         ListFormat[ListFormat["NoTrailingNewLine"] = 131072] = "NoTrailingNewLine";
5357         ListFormat[ListFormat["NoInterveningComments"] = 262144] = "NoInterveningComments";
5358         ListFormat[ListFormat["NoSpaceIfEmpty"] = 524288] = "NoSpaceIfEmpty";
5359         ListFormat[ListFormat["SingleElement"] = 1048576] = "SingleElement";
5360         ListFormat[ListFormat["SpaceAfterList"] = 2097152] = "SpaceAfterList";
5361         // Precomputed Formats
5362         ListFormat[ListFormat["Modifiers"] = 262656] = "Modifiers";
5363         ListFormat[ListFormat["HeritageClauses"] = 512] = "HeritageClauses";
5364         ListFormat[ListFormat["SingleLineTypeLiteralMembers"] = 768] = "SingleLineTypeLiteralMembers";
5365         ListFormat[ListFormat["MultiLineTypeLiteralMembers"] = 32897] = "MultiLineTypeLiteralMembers";
5366         ListFormat[ListFormat["SingleLineTupleTypeElements"] = 528] = "SingleLineTupleTypeElements";
5367         ListFormat[ListFormat["MultiLineTupleTypeElements"] = 657] = "MultiLineTupleTypeElements";
5368         ListFormat[ListFormat["UnionTypeConstituents"] = 516] = "UnionTypeConstituents";
5369         ListFormat[ListFormat["IntersectionTypeConstituents"] = 520] = "IntersectionTypeConstituents";
5370         ListFormat[ListFormat["ObjectBindingPatternElements"] = 525136] = "ObjectBindingPatternElements";
5371         ListFormat[ListFormat["ArrayBindingPatternElements"] = 524880] = "ArrayBindingPatternElements";
5372         ListFormat[ListFormat["ObjectLiteralExpressionProperties"] = 526226] = "ObjectLiteralExpressionProperties";
5373         ListFormat[ListFormat["ArrayLiteralExpressionElements"] = 8914] = "ArrayLiteralExpressionElements";
5374         ListFormat[ListFormat["CommaListElements"] = 528] = "CommaListElements";
5375         ListFormat[ListFormat["CallExpressionArguments"] = 2576] = "CallExpressionArguments";
5376         ListFormat[ListFormat["NewExpressionArguments"] = 18960] = "NewExpressionArguments";
5377         ListFormat[ListFormat["TemplateExpressionSpans"] = 262144] = "TemplateExpressionSpans";
5378         ListFormat[ListFormat["SingleLineBlockStatements"] = 768] = "SingleLineBlockStatements";
5379         ListFormat[ListFormat["MultiLineBlockStatements"] = 129] = "MultiLineBlockStatements";
5380         ListFormat[ListFormat["VariableDeclarationList"] = 528] = "VariableDeclarationList";
5381         ListFormat[ListFormat["SingleLineFunctionBodyStatements"] = 768] = "SingleLineFunctionBodyStatements";
5382         ListFormat[ListFormat["MultiLineFunctionBodyStatements"] = 1] = "MultiLineFunctionBodyStatements";
5383         ListFormat[ListFormat["ClassHeritageClauses"] = 0] = "ClassHeritageClauses";
5384         ListFormat[ListFormat["ClassMembers"] = 129] = "ClassMembers";
5385         ListFormat[ListFormat["InterfaceMembers"] = 129] = "InterfaceMembers";
5386         ListFormat[ListFormat["EnumMembers"] = 145] = "EnumMembers";
5387         ListFormat[ListFormat["CaseBlockClauses"] = 129] = "CaseBlockClauses";
5388         ListFormat[ListFormat["NamedImportsOrExportsElements"] = 525136] = "NamedImportsOrExportsElements";
5389         ListFormat[ListFormat["JsxElementOrFragmentChildren"] = 262144] = "JsxElementOrFragmentChildren";
5390         ListFormat[ListFormat["JsxElementAttributes"] = 262656] = "JsxElementAttributes";
5391         ListFormat[ListFormat["CaseOrDefaultClauseStatements"] = 163969] = "CaseOrDefaultClauseStatements";
5392         ListFormat[ListFormat["HeritageClauseTypes"] = 528] = "HeritageClauseTypes";
5393         ListFormat[ListFormat["SourceFileStatements"] = 131073] = "SourceFileStatements";
5394         ListFormat[ListFormat["Decorators"] = 2146305] = "Decorators";
5395         ListFormat[ListFormat["TypeArguments"] = 53776] = "TypeArguments";
5396         ListFormat[ListFormat["TypeParameters"] = 53776] = "TypeParameters";
5397         ListFormat[ListFormat["Parameters"] = 2576] = "Parameters";
5398         ListFormat[ListFormat["IndexSignatureParameters"] = 8848] = "IndexSignatureParameters";
5399         ListFormat[ListFormat["JSDocComment"] = 33] = "JSDocComment";
5400     })(ListFormat = ts.ListFormat || (ts.ListFormat = {}));
5401     /* @internal */
5402     var PragmaKindFlags;
5403     (function (PragmaKindFlags) {
5404         PragmaKindFlags[PragmaKindFlags["None"] = 0] = "None";
5405         /**
5406          * Triple slash comment of the form
5407          * /// <pragma-name argname="value" />
5408          */
5409         PragmaKindFlags[PragmaKindFlags["TripleSlashXML"] = 1] = "TripleSlashXML";
5410         /**
5411          * Single line comment of the form
5412          * // @pragma-name argval1 argval2
5413          * or
5414          * /// @pragma-name argval1 argval2
5415          */
5416         PragmaKindFlags[PragmaKindFlags["SingleLine"] = 2] = "SingleLine";
5417         /**
5418          * Multiline non-jsdoc pragma of the form
5419          * /* @pragma-name argval1 argval2 * /
5420          */
5421         PragmaKindFlags[PragmaKindFlags["MultiLine"] = 4] = "MultiLine";
5422         PragmaKindFlags[PragmaKindFlags["All"] = 7] = "All";
5423         PragmaKindFlags[PragmaKindFlags["Default"] = 7] = "Default";
5424     })(PragmaKindFlags = ts.PragmaKindFlags || (ts.PragmaKindFlags = {}));
5425     // While not strictly a type, this is here because `PragmaMap` needs to be here to be used with `SourceFile`, and we don't
5426     //  fancy effectively defining it twice, once in value-space and once in type-space
5427     /* @internal */
5428     ts.commentPragmas = {
5429         "reference": {
5430             args: [
5431                 { name: "types", optional: true, captureSpan: true },
5432                 { name: "lib", optional: true, captureSpan: true },
5433                 { name: "path", optional: true, captureSpan: true },
5434                 { name: "no-default-lib", optional: true }
5435             ],
5436             kind: 1 /* TripleSlashXML */
5437         },
5438         "amd-dependency": {
5439             args: [{ name: "path" }, { name: "name", optional: true }],
5440             kind: 1 /* TripleSlashXML */
5441         },
5442         "amd-module": {
5443             args: [{ name: "name" }],
5444             kind: 1 /* TripleSlashXML */
5445         },
5446         "ts-check": {
5447             kind: 2 /* SingleLine */
5448         },
5449         "ts-nocheck": {
5450             kind: 2 /* SingleLine */
5451         },
5452         "jsx": {
5453             args: [{ name: "factory" }],
5454             kind: 4 /* MultiLine */
5455         },
5456         "jsxfrag": {
5457             args: [{ name: "factory" }],
5458             kind: 4 /* MultiLine */
5459         },
5460         "jsximportsource": {
5461             args: [{ name: "factory" }],
5462             kind: 4 /* MultiLine */
5463         },
5464         "jsxruntime": {
5465             args: [{ name: "factory" }],
5466             kind: 4 /* MultiLine */
5467         },
5468     };
5469 })(ts || (ts = {}));
5470 /* @internal */
5471 var ts;
5472 (function (ts) {
5473     /**
5474      * Internally, we represent paths as strings with '/' as the directory separator.
5475      * When we make system calls (eg: LanguageServiceHost.getDirectory()),
5476      * we expect the host to correctly handle paths in our specified format.
5477      */
5478     ts.directorySeparator = "/";
5479     var altDirectorySeparator = "\\";
5480     var urlSchemeSeparator = "://";
5481     var backslashRegExp = /\\/g;
5482     //// Path Tests
5483     /**
5484      * Determines whether a charCode corresponds to `/` or `\`.
5485      */
5486     function isAnyDirectorySeparator(charCode) {
5487         return charCode === 47 /* slash */ || charCode === 92 /* backslash */;
5488     }
5489     ts.isAnyDirectorySeparator = isAnyDirectorySeparator;
5490     /**
5491      * Determines whether a path starts with a URL scheme (e.g. starts with `http://`, `ftp://`, `file://`, etc.).
5492      */
5493     function isUrl(path) {
5494         return getEncodedRootLength(path) < 0;
5495     }
5496     ts.isUrl = isUrl;
5497     /**
5498      * Determines whether a path is an absolute disk path (e.g. starts with `/`, or a dos path
5499      * like `c:`, `c:\` or `c:/`).
5500      */
5501     function isRootedDiskPath(path) {
5502         return getEncodedRootLength(path) > 0;
5503     }
5504     ts.isRootedDiskPath = isRootedDiskPath;
5505     /**
5506      * Determines whether a path consists only of a path root.
5507      */
5508     function isDiskPathRoot(path) {
5509         var rootLength = getEncodedRootLength(path);
5510         return rootLength > 0 && rootLength === path.length;
5511     }
5512     ts.isDiskPathRoot = isDiskPathRoot;
5513     /**
5514      * Determines whether a path starts with an absolute path component (i.e. `/`, `c:/`, `file://`, etc.).
5515      *
5516      * ```ts
5517      * // POSIX
5518      * pathIsAbsolute("/path/to/file.ext") === true
5519      * // DOS
5520      * pathIsAbsolute("c:/path/to/file.ext") === true
5521      * // URL
5522      * pathIsAbsolute("file:///path/to/file.ext") === true
5523      * // Non-absolute
5524      * pathIsAbsolute("path/to/file.ext") === false
5525      * pathIsAbsolute("./path/to/file.ext") === false
5526      * ```
5527      */
5528     function pathIsAbsolute(path) {
5529         return getEncodedRootLength(path) !== 0;
5530     }
5531     ts.pathIsAbsolute = pathIsAbsolute;
5532     /**
5533      * Determines whether a path starts with a relative path component (i.e. `.` or `..`).
5534      */
5535     function pathIsRelative(path) {
5536         return /^\.\.?($|[\\/])/.test(path);
5537     }
5538     ts.pathIsRelative = pathIsRelative;
5539     /**
5540      * Determines whether a path is neither relative nor absolute, e.g. "path/to/file".
5541      * Also known misleadingly as "non-relative".
5542      */
5543     function pathIsBareSpecifier(path) {
5544         return !pathIsAbsolute(path) && !pathIsRelative(path);
5545     }
5546     ts.pathIsBareSpecifier = pathIsBareSpecifier;
5547     function hasExtension(fileName) {
5548         return ts.stringContains(getBaseFileName(fileName), ".");
5549     }
5550     ts.hasExtension = hasExtension;
5551     function fileExtensionIs(path, extension) {
5552         return path.length > extension.length && ts.endsWith(path, extension);
5553     }
5554     ts.fileExtensionIs = fileExtensionIs;
5555     function fileExtensionIsOneOf(path, extensions) {
5556         for (var _i = 0, extensions_1 = extensions; _i < extensions_1.length; _i++) {
5557             var extension = extensions_1[_i];
5558             if (fileExtensionIs(path, extension)) {
5559                 return true;
5560             }
5561         }
5562         return false;
5563     }
5564     ts.fileExtensionIsOneOf = fileExtensionIsOneOf;
5565     /**
5566      * Determines whether a path has a trailing separator (`/` or `\\`).
5567      */
5568     function hasTrailingDirectorySeparator(path) {
5569         return path.length > 0 && isAnyDirectorySeparator(path.charCodeAt(path.length - 1));
5570     }
5571     ts.hasTrailingDirectorySeparator = hasTrailingDirectorySeparator;
5572     //// Path Parsing
5573     function isVolumeCharacter(charCode) {
5574         return (charCode >= 97 /* a */ && charCode <= 122 /* z */) ||
5575             (charCode >= 65 /* A */ && charCode <= 90 /* Z */);
5576     }
5577     function getFileUrlVolumeSeparatorEnd(url, start) {
5578         var ch0 = url.charCodeAt(start);
5579         if (ch0 === 58 /* colon */)
5580             return start + 1;
5581         if (ch0 === 37 /* percent */ && url.charCodeAt(start + 1) === 51 /* _3 */) {
5582             var ch2 = url.charCodeAt(start + 2);
5583             if (ch2 === 97 /* a */ || ch2 === 65 /* A */)
5584                 return start + 3;
5585         }
5586         return -1;
5587     }
5588     /**
5589      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
5590      * If the root is part of a URL, the twos-complement of the root length is returned.
5591      */
5592     function getEncodedRootLength(path) {
5593         if (!path)
5594             return 0;
5595         var ch0 = path.charCodeAt(0);
5596         // POSIX or UNC
5597         if (ch0 === 47 /* slash */ || ch0 === 92 /* backslash */) {
5598             if (path.charCodeAt(1) !== ch0)
5599                 return 1; // POSIX: "/" (or non-normalized "\")
5600             var p1 = path.indexOf(ch0 === 47 /* slash */ ? ts.directorySeparator : altDirectorySeparator, 2);
5601             if (p1 < 0)
5602                 return path.length; // UNC: "//server" or "\\server"
5603             return p1 + 1; // UNC: "//server/" or "\\server\"
5604         }
5605         // DOS
5606         if (isVolumeCharacter(ch0) && path.charCodeAt(1) === 58 /* colon */) {
5607             var ch2 = path.charCodeAt(2);
5608             if (ch2 === 47 /* slash */ || ch2 === 92 /* backslash */)
5609                 return 3; // DOS: "c:/" or "c:\"
5610             if (path.length === 2)
5611                 return 2; // DOS: "c:" (but not "c:d")
5612         }
5613         // URL
5614         var schemeEnd = path.indexOf(urlSchemeSeparator);
5615         if (schemeEnd !== -1) {
5616             var authorityStart = schemeEnd + urlSchemeSeparator.length;
5617             var authorityEnd = path.indexOf(ts.directorySeparator, authorityStart);
5618             if (authorityEnd !== -1) { // URL: "file:///", "file://server/", "file://server/path"
5619                 // For local "file" URLs, include the leading DOS volume (if present).
5620                 // Per https://www.ietf.org/rfc/rfc1738.txt, a host of "" or "localhost" is a
5621                 // special case interpreted as "the machine from which the URL is being interpreted".
5622                 var scheme = path.slice(0, schemeEnd);
5623                 var authority = path.slice(authorityStart, authorityEnd);
5624                 if (scheme === "file" && (authority === "" || authority === "localhost") &&
5625                     isVolumeCharacter(path.charCodeAt(authorityEnd + 1))) {
5626                     var volumeSeparatorEnd = getFileUrlVolumeSeparatorEnd(path, authorityEnd + 2);
5627                     if (volumeSeparatorEnd !== -1) {
5628                         if (path.charCodeAt(volumeSeparatorEnd) === 47 /* slash */) {
5629                             // URL: "file:///c:/", "file://localhost/c:/", "file:///c%3a/", "file://localhost/c%3a/"
5630                             return ~(volumeSeparatorEnd + 1);
5631                         }
5632                         if (volumeSeparatorEnd === path.length) {
5633                             // URL: "file:///c:", "file://localhost/c:", "file:///c$3a", "file://localhost/c%3a"
5634                             // but not "file:///c:d" or "file:///c%3ad"
5635                             return ~volumeSeparatorEnd;
5636                         }
5637                     }
5638                 }
5639                 return ~(authorityEnd + 1); // URL: "file://server/", "http://server/"
5640             }
5641             return ~path.length; // URL: "file://server", "http://server"
5642         }
5643         // relative
5644         return 0;
5645     }
5646     /**
5647      * Returns length of the root part of a path or URL (i.e. length of "/", "x:/", "//server/share/, file:///user/files").
5648      *
5649      * For example:
5650      * ```ts
5651      * getRootLength("a") === 0                   // ""
5652      * getRootLength("/") === 1                   // "/"
5653      * getRootLength("c:") === 2                  // "c:"
5654      * getRootLength("c:d") === 0                 // ""
5655      * getRootLength("c:/") === 3                 // "c:/"
5656      * getRootLength("c:\\") === 3                // "c:\\"
5657      * getRootLength("//server") === 7            // "//server"
5658      * getRootLength("//server/share") === 8      // "//server/"
5659      * getRootLength("\\\\server") === 7          // "\\\\server"
5660      * getRootLength("\\\\server\\share") === 8   // "\\\\server\\"
5661      * getRootLength("file:///path") === 8        // "file:///"
5662      * getRootLength("file:///c:") === 10         // "file:///c:"
5663      * getRootLength("file:///c:d") === 8         // "file:///"
5664      * getRootLength("file:///c:/path") === 11    // "file:///c:/"
5665      * getRootLength("file://server") === 13      // "file://server"
5666      * getRootLength("file://server/path") === 14 // "file://server/"
5667      * getRootLength("http://server") === 13      // "http://server"
5668      * getRootLength("http://server/path") === 14 // "http://server/"
5669      * ```
5670      */
5671     function getRootLength(path) {
5672         var rootLength = getEncodedRootLength(path);
5673         return rootLength < 0 ? ~rootLength : rootLength;
5674     }
5675     ts.getRootLength = getRootLength;
5676     function getDirectoryPath(path) {
5677         path = normalizeSlashes(path);
5678         // If the path provided is itself the root, then return it.
5679         var rootLength = getRootLength(path);
5680         if (rootLength === path.length)
5681             return path;
5682         // return the leading portion of the path up to the last (non-terminal) directory separator
5683         // but not including any trailing directory separator.
5684         path = removeTrailingDirectorySeparator(path);
5685         return path.slice(0, Math.max(rootLength, path.lastIndexOf(ts.directorySeparator)));
5686     }
5687     ts.getDirectoryPath = getDirectoryPath;
5688     function getBaseFileName(path, extensions, ignoreCase) {
5689         path = normalizeSlashes(path);
5690         // if the path provided is itself the root, then it has not file name.
5691         var rootLength = getRootLength(path);
5692         if (rootLength === path.length)
5693             return "";
5694         // return the trailing portion of the path starting after the last (non-terminal) directory
5695         // separator but not including any trailing directory separator.
5696         path = removeTrailingDirectorySeparator(path);
5697         var name = path.slice(Math.max(getRootLength(path), path.lastIndexOf(ts.directorySeparator) + 1));
5698         var extension = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(name, extensions, ignoreCase) : undefined;
5699         return extension ? name.slice(0, name.length - extension.length) : name;
5700     }
5701     ts.getBaseFileName = getBaseFileName;
5702     function tryGetExtensionFromPath(path, extension, stringEqualityComparer) {
5703         if (!ts.startsWith(extension, "."))
5704             extension = "." + extension;
5705         if (path.length >= extension.length && path.charCodeAt(path.length - extension.length) === 46 /* dot */) {
5706             var pathExtension = path.slice(path.length - extension.length);
5707             if (stringEqualityComparer(pathExtension, extension)) {
5708                 return pathExtension;
5709             }
5710         }
5711     }
5712     function getAnyExtensionFromPathWorker(path, extensions, stringEqualityComparer) {
5713         if (typeof extensions === "string") {
5714             return tryGetExtensionFromPath(path, extensions, stringEqualityComparer) || "";
5715         }
5716         for (var _i = 0, extensions_2 = extensions; _i < extensions_2.length; _i++) {
5717             var extension = extensions_2[_i];
5718             var result = tryGetExtensionFromPath(path, extension, stringEqualityComparer);
5719             if (result)
5720                 return result;
5721         }
5722         return "";
5723     }
5724     function getAnyExtensionFromPath(path, extensions, ignoreCase) {
5725         // Retrieves any string from the final "." onwards from a base file name.
5726         // Unlike extensionFromPath, which throws an exception on unrecognized extensions.
5727         if (extensions) {
5728             return getAnyExtensionFromPathWorker(removeTrailingDirectorySeparator(path), extensions, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive);
5729         }
5730         var baseFileName = getBaseFileName(path);
5731         var extensionIndex = baseFileName.lastIndexOf(".");
5732         if (extensionIndex >= 0) {
5733             return baseFileName.substring(extensionIndex);
5734         }
5735         return "";
5736     }
5737     ts.getAnyExtensionFromPath = getAnyExtensionFromPath;
5738     function pathComponents(path, rootLength) {
5739         var root = path.substring(0, rootLength);
5740         var rest = path.substring(rootLength).split(ts.directorySeparator);
5741         if (rest.length && !ts.lastOrUndefined(rest))
5742             rest.pop();
5743         return __spreadArrays([root], rest);
5744     }
5745     /**
5746      * Parse a path into an array containing a root component (at index 0) and zero or more path
5747      * components (at indices > 0). The result is not normalized.
5748      * If the path is relative, the root component is `""`.
5749      * If the path is absolute, the root component includes the first path separator (`/`).
5750      *
5751      * ```ts
5752      * // POSIX
5753      * getPathComponents("/path/to/file.ext") === ["/", "path", "to", "file.ext"]
5754      * getPathComponents("/path/to/") === ["/", "path", "to"]
5755      * getPathComponents("/") === ["/"]
5756      * // DOS
5757      * getPathComponents("c:/path/to/file.ext") === ["c:/", "path", "to", "file.ext"]
5758      * getPathComponents("c:/path/to/") === ["c:/", "path", "to"]
5759      * getPathComponents("c:/") === ["c:/"]
5760      * getPathComponents("c:") === ["c:"]
5761      * // URL
5762      * getPathComponents("http://typescriptlang.org/path/to/file.ext") === ["http://typescriptlang.org/", "path", "to", "file.ext"]
5763      * getPathComponents("http://typescriptlang.org/path/to/") === ["http://typescriptlang.org/", "path", "to"]
5764      * getPathComponents("http://typescriptlang.org/") === ["http://typescriptlang.org/"]
5765      * getPathComponents("http://typescriptlang.org") === ["http://typescriptlang.org"]
5766      * getPathComponents("file://server/path/to/file.ext") === ["file://server/", "path", "to", "file.ext"]
5767      * getPathComponents("file://server/path/to/") === ["file://server/", "path", "to"]
5768      * getPathComponents("file://server/") === ["file://server/"]
5769      * getPathComponents("file://server") === ["file://server"]
5770      * getPathComponents("file:///path/to/file.ext") === ["file:///", "path", "to", "file.ext"]
5771      * getPathComponents("file:///path/to/") === ["file:///", "path", "to"]
5772      * getPathComponents("file:///") === ["file:///"]
5773      * getPathComponents("file://") === ["file://"]
5774      */
5775     function getPathComponents(path, currentDirectory) {
5776         if (currentDirectory === void 0) { currentDirectory = ""; }
5777         path = combinePaths(currentDirectory, path);
5778         return pathComponents(path, getRootLength(path));
5779     }
5780     ts.getPathComponents = getPathComponents;
5781     //// Path Formatting
5782     /**
5783      * Formats a parsed path consisting of a root component (at index 0) and zero or more path
5784      * segments (at indices > 0).
5785      *
5786      * ```ts
5787      * getPathFromPathComponents(["/", "path", "to", "file.ext"]) === "/path/to/file.ext"
5788      * ```
5789      */
5790     function getPathFromPathComponents(pathComponents) {
5791         if (pathComponents.length === 0)
5792             return "";
5793         var root = pathComponents[0] && ensureTrailingDirectorySeparator(pathComponents[0]);
5794         return root + pathComponents.slice(1).join(ts.directorySeparator);
5795     }
5796     ts.getPathFromPathComponents = getPathFromPathComponents;
5797     //// Path Normalization
5798     /**
5799      * Normalize path separators, converting `\` into `/`.
5800      */
5801     function normalizeSlashes(path) {
5802         return path.replace(backslashRegExp, ts.directorySeparator);
5803     }
5804     ts.normalizeSlashes = normalizeSlashes;
5805     /**
5806      * Reduce an array of path components to a more simplified path by navigating any
5807      * `"."` or `".."` entries in the path.
5808      */
5809     function reducePathComponents(components) {
5810         if (!ts.some(components))
5811             return [];
5812         var reduced = [components[0]];
5813         for (var i = 1; i < components.length; i++) {
5814             var component = components[i];
5815             if (!component)
5816                 continue;
5817             if (component === ".")
5818                 continue;
5819             if (component === "..") {
5820                 if (reduced.length > 1) {
5821                     if (reduced[reduced.length - 1] !== "..") {
5822                         reduced.pop();
5823                         continue;
5824                     }
5825                 }
5826                 else if (reduced[0])
5827                     continue;
5828             }
5829             reduced.push(component);
5830         }
5831         return reduced;
5832     }
5833     ts.reducePathComponents = reducePathComponents;
5834     /**
5835      * Combines paths. If a path is absolute, it replaces any previous path. Relative paths are not simplified.
5836      *
5837      * ```ts
5838      * // Non-rooted
5839      * combinePaths("path", "to", "file.ext") === "path/to/file.ext"
5840      * combinePaths("path", "dir", "..", "to", "file.ext") === "path/dir/../to/file.ext"
5841      * // POSIX
5842      * combinePaths("/path", "to", "file.ext") === "/path/to/file.ext"
5843      * combinePaths("/path", "/to", "file.ext") === "/to/file.ext"
5844      * // DOS
5845      * combinePaths("c:/path", "to", "file.ext") === "c:/path/to/file.ext"
5846      * combinePaths("c:/path", "c:/to", "file.ext") === "c:/to/file.ext"
5847      * // URL
5848      * combinePaths("file:///path", "to", "file.ext") === "file:///path/to/file.ext"
5849      * combinePaths("file:///path", "file:///to", "file.ext") === "file:///to/file.ext"
5850      * ```
5851      */
5852     function combinePaths(path) {
5853         var paths = [];
5854         for (var _i = 1; _i < arguments.length; _i++) {
5855             paths[_i - 1] = arguments[_i];
5856         }
5857         if (path)
5858             path = normalizeSlashes(path);
5859         for (var _a = 0, paths_1 = paths; _a < paths_1.length; _a++) {
5860             var relativePath = paths_1[_a];
5861             if (!relativePath)
5862                 continue;
5863             relativePath = normalizeSlashes(relativePath);
5864             if (!path || getRootLength(relativePath) !== 0) {
5865                 path = relativePath;
5866             }
5867             else {
5868                 path = ensureTrailingDirectorySeparator(path) + relativePath;
5869             }
5870         }
5871         return path;
5872     }
5873     ts.combinePaths = combinePaths;
5874     /**
5875      * Combines and resolves paths. If a path is absolute, it replaces any previous path. Any
5876      * `.` and `..` path components are resolved. Trailing directory separators are preserved.
5877      *
5878      * ```ts
5879      * resolvePath("/path", "to", "file.ext") === "path/to/file.ext"
5880      * resolvePath("/path", "to", "file.ext/") === "path/to/file.ext/"
5881      * resolvePath("/path", "dir", "..", "to", "file.ext") === "path/to/file.ext"
5882      * ```
5883      */
5884     function resolvePath(path) {
5885         var paths = [];
5886         for (var _i = 1; _i < arguments.length; _i++) {
5887             paths[_i - 1] = arguments[_i];
5888         }
5889         return normalizePath(ts.some(paths) ? combinePaths.apply(void 0, __spreadArrays([path], paths)) : normalizeSlashes(path));
5890     }
5891     ts.resolvePath = resolvePath;
5892     /**
5893      * Parse a path into an array containing a root component (at index 0) and zero or more path
5894      * components (at indices > 0). The result is normalized.
5895      * If the path is relative, the root component is `""`.
5896      * If the path is absolute, the root component includes the first path separator (`/`).
5897      *
5898      * ```ts
5899      * getNormalizedPathComponents("to/dir/../file.ext", "/path/") === ["/", "path", "to", "file.ext"]
5900      * ```
5901      */
5902     function getNormalizedPathComponents(path, currentDirectory) {
5903         return reducePathComponents(getPathComponents(path, currentDirectory));
5904     }
5905     ts.getNormalizedPathComponents = getNormalizedPathComponents;
5906     function getNormalizedAbsolutePath(fileName, currentDirectory) {
5907         return getPathFromPathComponents(getNormalizedPathComponents(fileName, currentDirectory));
5908     }
5909     ts.getNormalizedAbsolutePath = getNormalizedAbsolutePath;
5910     function normalizePath(path) {
5911         path = normalizeSlashes(path);
5912         var normalized = getPathFromPathComponents(reducePathComponents(getPathComponents(path)));
5913         return normalized && hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(normalized) : normalized;
5914     }
5915     ts.normalizePath = normalizePath;
5916     function getPathWithoutRoot(pathComponents) {
5917         if (pathComponents.length === 0)
5918             return "";
5919         return pathComponents.slice(1).join(ts.directorySeparator);
5920     }
5921     function getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory) {
5922         return getPathWithoutRoot(getNormalizedPathComponents(fileName, currentDirectory));
5923     }
5924     ts.getNormalizedAbsolutePathWithoutRoot = getNormalizedAbsolutePathWithoutRoot;
5925     function toPath(fileName, basePath, getCanonicalFileName) {
5926         var nonCanonicalizedPath = isRootedDiskPath(fileName)
5927             ? normalizePath(fileName)
5928             : getNormalizedAbsolutePath(fileName, basePath);
5929         return getCanonicalFileName(nonCanonicalizedPath);
5930     }
5931     ts.toPath = toPath;
5932     function normalizePathAndParts(path) {
5933         path = normalizeSlashes(path);
5934         var _a = reducePathComponents(getPathComponents(path)), root = _a[0], parts = _a.slice(1);
5935         if (parts.length) {
5936             var joinedParts = root + parts.join(ts.directorySeparator);
5937             return { path: hasTrailingDirectorySeparator(path) ? ensureTrailingDirectorySeparator(joinedParts) : joinedParts, parts: parts };
5938         }
5939         else {
5940             return { path: root, parts: parts };
5941         }
5942     }
5943     ts.normalizePathAndParts = normalizePathAndParts;
5944     function removeTrailingDirectorySeparator(path) {
5945         if (hasTrailingDirectorySeparator(path)) {
5946             return path.substr(0, path.length - 1);
5947         }
5948         return path;
5949     }
5950     ts.removeTrailingDirectorySeparator = removeTrailingDirectorySeparator;
5951     function ensureTrailingDirectorySeparator(path) {
5952         if (!hasTrailingDirectorySeparator(path)) {
5953             return path + ts.directorySeparator;
5954         }
5955         return path;
5956     }
5957     ts.ensureTrailingDirectorySeparator = ensureTrailingDirectorySeparator;
5958     /**
5959      * Ensures a path is either absolute (prefixed with `/` or `c:`) or dot-relative (prefixed
5960      * with `./` or `../`) so as not to be confused with an unprefixed module name.
5961      *
5962      * ```ts
5963      * ensurePathIsNonModuleName("/path/to/file.ext") === "/path/to/file.ext"
5964      * ensurePathIsNonModuleName("./path/to/file.ext") === "./path/to/file.ext"
5965      * ensurePathIsNonModuleName("../path/to/file.ext") === "../path/to/file.ext"
5966      * ensurePathIsNonModuleName("path/to/file.ext") === "./path/to/file.ext"
5967      * ```
5968      */
5969     function ensurePathIsNonModuleName(path) {
5970         return !pathIsAbsolute(path) && !pathIsRelative(path) ? "./" + path : path;
5971     }
5972     ts.ensurePathIsNonModuleName = ensurePathIsNonModuleName;
5973     function changeAnyExtension(path, ext, extensions, ignoreCase) {
5974         var pathext = extensions !== undefined && ignoreCase !== undefined ? getAnyExtensionFromPath(path, extensions, ignoreCase) : getAnyExtensionFromPath(path);
5975         return pathext ? path.slice(0, path.length - pathext.length) + (ts.startsWith(ext, ".") ? ext : "." + ext) : path;
5976     }
5977     ts.changeAnyExtension = changeAnyExtension;
5978     //// Path Comparisons
5979     // check path for these segments: '', '.'. '..'
5980     var relativePathSegmentRegExp = /(^|\/)\.{0,2}($|\/)/;
5981     function comparePathsWorker(a, b, componentComparer) {
5982         if (a === b)
5983             return 0 /* EqualTo */;
5984         if (a === undefined)
5985             return -1 /* LessThan */;
5986         if (b === undefined)
5987             return 1 /* GreaterThan */;
5988         // NOTE: Performance optimization - shortcut if the root segments differ as there would be no
5989         //       need to perform path reduction.
5990         var aRoot = a.substring(0, getRootLength(a));
5991         var bRoot = b.substring(0, getRootLength(b));
5992         var result = ts.compareStringsCaseInsensitive(aRoot, bRoot);
5993         if (result !== 0 /* EqualTo */) {
5994             return result;
5995         }
5996         // NOTE: Performance optimization - shortcut if there are no relative path segments in
5997         //       the non-root portion of the path
5998         var aRest = a.substring(aRoot.length);
5999         var bRest = b.substring(bRoot.length);
6000         if (!relativePathSegmentRegExp.test(aRest) && !relativePathSegmentRegExp.test(bRest)) {
6001             return componentComparer(aRest, bRest);
6002         }
6003         // The path contains a relative path segment. Normalize the paths and perform a slower component
6004         // by component comparison.
6005         var aComponents = reducePathComponents(getPathComponents(a));
6006         var bComponents = reducePathComponents(getPathComponents(b));
6007         var sharedLength = Math.min(aComponents.length, bComponents.length);
6008         for (var i = 1; i < sharedLength; i++) {
6009             var result_2 = componentComparer(aComponents[i], bComponents[i]);
6010             if (result_2 !== 0 /* EqualTo */) {
6011                 return result_2;
6012             }
6013         }
6014         return ts.compareValues(aComponents.length, bComponents.length);
6015     }
6016     /**
6017      * Performs a case-sensitive comparison of two paths. Path roots are always compared case-insensitively.
6018      */
6019     function comparePathsCaseSensitive(a, b) {
6020         return comparePathsWorker(a, b, ts.compareStringsCaseSensitive);
6021     }
6022     ts.comparePathsCaseSensitive = comparePathsCaseSensitive;
6023     /**
6024      * Performs a case-insensitive comparison of two paths.
6025      */
6026     function comparePathsCaseInsensitive(a, b) {
6027         return comparePathsWorker(a, b, ts.compareStringsCaseInsensitive);
6028     }
6029     ts.comparePathsCaseInsensitive = comparePathsCaseInsensitive;
6030     function comparePaths(a, b, currentDirectory, ignoreCase) {
6031         if (typeof currentDirectory === "string") {
6032             a = combinePaths(currentDirectory, a);
6033             b = combinePaths(currentDirectory, b);
6034         }
6035         else if (typeof currentDirectory === "boolean") {
6036             ignoreCase = currentDirectory;
6037         }
6038         return comparePathsWorker(a, b, ts.getStringComparer(ignoreCase));
6039     }
6040     ts.comparePaths = comparePaths;
6041     function containsPath(parent, child, currentDirectory, ignoreCase) {
6042         if (typeof currentDirectory === "string") {
6043             parent = combinePaths(currentDirectory, parent);
6044             child = combinePaths(currentDirectory, child);
6045         }
6046         else if (typeof currentDirectory === "boolean") {
6047             ignoreCase = currentDirectory;
6048         }
6049         if (parent === undefined || child === undefined)
6050             return false;
6051         if (parent === child)
6052             return true;
6053         var parentComponents = reducePathComponents(getPathComponents(parent));
6054         var childComponents = reducePathComponents(getPathComponents(child));
6055         if (childComponents.length < parentComponents.length) {
6056             return false;
6057         }
6058         var componentEqualityComparer = ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive;
6059         for (var i = 0; i < parentComponents.length; i++) {
6060             var equalityComparer = i === 0 ? ts.equateStringsCaseInsensitive : componentEqualityComparer;
6061             if (!equalityComparer(parentComponents[i], childComponents[i])) {
6062                 return false;
6063             }
6064         }
6065         return true;
6066     }
6067     ts.containsPath = containsPath;
6068     /**
6069      * Determines whether `fileName` starts with the specified `directoryName` using the provided path canonicalization callback.
6070      * Comparison is case-sensitive between the canonical paths.
6071      *
6072      * @deprecated Use `containsPath` if possible.
6073      */
6074     function startsWithDirectory(fileName, directoryName, getCanonicalFileName) {
6075         var canonicalFileName = getCanonicalFileName(fileName);
6076         var canonicalDirectoryName = getCanonicalFileName(directoryName);
6077         return ts.startsWith(canonicalFileName, canonicalDirectoryName + "/") || ts.startsWith(canonicalFileName, canonicalDirectoryName + "\\");
6078     }
6079     ts.startsWithDirectory = startsWithDirectory;
6080     //// Relative Paths
6081     function getPathComponentsRelativeTo(from, to, stringEqualityComparer, getCanonicalFileName) {
6082         var fromComponents = reducePathComponents(getPathComponents(from));
6083         var toComponents = reducePathComponents(getPathComponents(to));
6084         var start;
6085         for (start = 0; start < fromComponents.length && start < toComponents.length; start++) {
6086             var fromComponent = getCanonicalFileName(fromComponents[start]);
6087             var toComponent = getCanonicalFileName(toComponents[start]);
6088             var comparer = start === 0 ? ts.equateStringsCaseInsensitive : stringEqualityComparer;
6089             if (!comparer(fromComponent, toComponent))
6090                 break;
6091         }
6092         if (start === 0) {
6093             return toComponents;
6094         }
6095         var components = toComponents.slice(start);
6096         var relative = [];
6097         for (; start < fromComponents.length; start++) {
6098             relative.push("..");
6099         }
6100         return __spreadArrays([""], relative, components);
6101     }
6102     ts.getPathComponentsRelativeTo = getPathComponentsRelativeTo;
6103     function getRelativePathFromDirectory(fromDirectory, to, getCanonicalFileNameOrIgnoreCase) {
6104         ts.Debug.assert((getRootLength(fromDirectory) > 0) === (getRootLength(to) > 0), "Paths must either both be absolute or both be relative");
6105         var getCanonicalFileName = typeof getCanonicalFileNameOrIgnoreCase === "function" ? getCanonicalFileNameOrIgnoreCase : ts.identity;
6106         var ignoreCase = typeof getCanonicalFileNameOrIgnoreCase === "boolean" ? getCanonicalFileNameOrIgnoreCase : false;
6107         var pathComponents = getPathComponentsRelativeTo(fromDirectory, to, ignoreCase ? ts.equateStringsCaseInsensitive : ts.equateStringsCaseSensitive, getCanonicalFileName);
6108         return getPathFromPathComponents(pathComponents);
6109     }
6110     ts.getRelativePathFromDirectory = getRelativePathFromDirectory;
6111     function convertToRelativePath(absoluteOrRelativePath, basePath, getCanonicalFileName) {
6112         return !isRootedDiskPath(absoluteOrRelativePath)
6113             ? absoluteOrRelativePath
6114             : getRelativePathToDirectoryOrUrl(basePath, absoluteOrRelativePath, basePath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
6115     }
6116     ts.convertToRelativePath = convertToRelativePath;
6117     function getRelativePathFromFile(from, to, getCanonicalFileName) {
6118         return ensurePathIsNonModuleName(getRelativePathFromDirectory(getDirectoryPath(from), to, getCanonicalFileName));
6119     }
6120     ts.getRelativePathFromFile = getRelativePathFromFile;
6121     function getRelativePathToDirectoryOrUrl(directoryPathOrUrl, relativeOrAbsolutePath, currentDirectory, getCanonicalFileName, isAbsolutePathAnUrl) {
6122         var pathComponents = getPathComponentsRelativeTo(resolvePath(currentDirectory, directoryPathOrUrl), resolvePath(currentDirectory, relativeOrAbsolutePath), ts.equateStringsCaseSensitive, getCanonicalFileName);
6123         var firstComponent = pathComponents[0];
6124         if (isAbsolutePathAnUrl && isRootedDiskPath(firstComponent)) {
6125             var prefix = firstComponent.charAt(0) === ts.directorySeparator ? "file://" : "file:///";
6126             pathComponents[0] = prefix + firstComponent;
6127         }
6128         return getPathFromPathComponents(pathComponents);
6129     }
6130     ts.getRelativePathToDirectoryOrUrl = getRelativePathToDirectoryOrUrl;
6131     function forEachAncestorDirectory(directory, callback) {
6132         while (true) {
6133             var result = callback(directory);
6134             if (result !== undefined) {
6135                 return result;
6136             }
6137             var parentPath = getDirectoryPath(directory);
6138             if (parentPath === directory) {
6139                 return undefined;
6140             }
6141             directory = parentPath;
6142         }
6143     }
6144     ts.forEachAncestorDirectory = forEachAncestorDirectory;
6145     function isNodeModulesDirectory(dirPath) {
6146         return ts.endsWith(dirPath, "/node_modules");
6147     }
6148     ts.isNodeModulesDirectory = isNodeModulesDirectory;
6149 })(ts || (ts = {}));
6150 var ts;
6151 (function (ts) {
6152     /**
6153      * djb2 hashing algorithm
6154      * http://www.cse.yorku.ca/~oz/hash.html
6155      */
6156     /* @internal */
6157     function generateDjb2Hash(data) {
6158         var acc = 5381;
6159         for (var i = 0; i < data.length; i++) {
6160             acc = ((acc << 5) + acc) + data.charCodeAt(i);
6161         }
6162         return acc.toString();
6163     }
6164     ts.generateDjb2Hash = generateDjb2Hash;
6165     /**
6166      * Set a high stack trace limit to provide more information in case of an error.
6167      * Called for command-line and server use cases.
6168      * Not called if TypeScript is used as a library.
6169      */
6170     /* @internal */
6171     function setStackTraceLimit() {
6172         if (Error.stackTraceLimit < 100) { // Also tests that we won't set the property if it doesn't exist.
6173             Error.stackTraceLimit = 100;
6174         }
6175     }
6176     ts.setStackTraceLimit = setStackTraceLimit;
6177     var FileWatcherEventKind;
6178     (function (FileWatcherEventKind) {
6179         FileWatcherEventKind[FileWatcherEventKind["Created"] = 0] = "Created";
6180         FileWatcherEventKind[FileWatcherEventKind["Changed"] = 1] = "Changed";
6181         FileWatcherEventKind[FileWatcherEventKind["Deleted"] = 2] = "Deleted";
6182     })(FileWatcherEventKind = ts.FileWatcherEventKind || (ts.FileWatcherEventKind = {}));
6183     /* @internal */
6184     var PollingInterval;
6185     (function (PollingInterval) {
6186         PollingInterval[PollingInterval["High"] = 2000] = "High";
6187         PollingInterval[PollingInterval["Medium"] = 500] = "Medium";
6188         PollingInterval[PollingInterval["Low"] = 250] = "Low";
6189     })(PollingInterval = ts.PollingInterval || (ts.PollingInterval = {}));
6190     /* @internal */
6191     ts.missingFileModifiedTime = new Date(0); // Any subsequent modification will occur after this time
6192     function createPollingIntervalBasedLevels(levels) {
6193         var _a;
6194         return _a = {},
6195             _a[PollingInterval.Low] = levels.Low,
6196             _a[PollingInterval.Medium] = levels.Medium,
6197             _a[PollingInterval.High] = levels.High,
6198             _a;
6199     }
6200     var defaultChunkLevels = { Low: 32, Medium: 64, High: 256 };
6201     var pollingChunkSize = createPollingIntervalBasedLevels(defaultChunkLevels);
6202     /* @internal */
6203     ts.unchangedPollThresholds = createPollingIntervalBasedLevels(defaultChunkLevels);
6204     /* @internal */
6205     function setCustomPollingValues(system) {
6206         if (!system.getEnvironmentVariable) {
6207             return;
6208         }
6209         var pollingIntervalChanged = setCustomLevels("TSC_WATCH_POLLINGINTERVAL", PollingInterval);
6210         pollingChunkSize = getCustomPollingBasedLevels("TSC_WATCH_POLLINGCHUNKSIZE", defaultChunkLevels) || pollingChunkSize;
6211         ts.unchangedPollThresholds = getCustomPollingBasedLevels("TSC_WATCH_UNCHANGEDPOLLTHRESHOLDS", defaultChunkLevels) || ts.unchangedPollThresholds;
6212         function getLevel(envVar, level) {
6213             return system.getEnvironmentVariable(envVar + "_" + level.toUpperCase());
6214         }
6215         function getCustomLevels(baseVariable) {
6216             var customLevels;
6217             setCustomLevel("Low");
6218             setCustomLevel("Medium");
6219             setCustomLevel("High");
6220             return customLevels;
6221             function setCustomLevel(level) {
6222                 var customLevel = getLevel(baseVariable, level);
6223                 if (customLevel) {
6224                     (customLevels || (customLevels = {}))[level] = Number(customLevel);
6225                 }
6226             }
6227         }
6228         function setCustomLevels(baseVariable, levels) {
6229             var customLevels = getCustomLevels(baseVariable);
6230             if (customLevels) {
6231                 setLevel("Low");
6232                 setLevel("Medium");
6233                 setLevel("High");
6234                 return true;
6235             }
6236             return false;
6237             function setLevel(level) {
6238                 levels[level] = customLevels[level] || levels[level];
6239             }
6240         }
6241         function getCustomPollingBasedLevels(baseVariable, defaultLevels) {
6242             var customLevels = getCustomLevels(baseVariable);
6243             return (pollingIntervalChanged || customLevels) &&
6244                 createPollingIntervalBasedLevels(customLevels ? __assign(__assign({}, defaultLevels), customLevels) : defaultLevels);
6245         }
6246     }
6247     ts.setCustomPollingValues = setCustomPollingValues;
6248     /* @internal */
6249     function createDynamicPriorityPollingWatchFile(host) {
6250         var watchedFiles = [];
6251         var changedFilesInLastPoll = [];
6252         var lowPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Low);
6253         var mediumPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.Medium);
6254         var highPollingIntervalQueue = createPollingIntervalQueue(PollingInterval.High);
6255         return watchFile;
6256         function watchFile(fileName, callback, defaultPollingInterval) {
6257             var file = {
6258                 fileName: fileName,
6259                 callback: callback,
6260                 unchangedPolls: 0,
6261                 mtime: getModifiedTime(fileName)
6262             };
6263             watchedFiles.push(file);
6264             addToPollingIntervalQueue(file, defaultPollingInterval);
6265             return {
6266                 close: function () {
6267                     file.isClosed = true;
6268                     // Remove from watchedFiles
6269                     ts.unorderedRemoveItem(watchedFiles, file);
6270                     // Do not update polling interval queue since that will happen as part of polling
6271                 }
6272             };
6273         }
6274         function createPollingIntervalQueue(pollingInterval) {
6275             var queue = [];
6276             queue.pollingInterval = pollingInterval;
6277             queue.pollIndex = 0;
6278             queue.pollScheduled = false;
6279             return queue;
6280         }
6281         function pollPollingIntervalQueue(queue) {
6282             queue.pollIndex = pollQueue(queue, queue.pollingInterval, queue.pollIndex, pollingChunkSize[queue.pollingInterval]);
6283             // Set the next polling index and timeout
6284             if (queue.length) {
6285                 scheduleNextPoll(queue.pollingInterval);
6286             }
6287             else {
6288                 ts.Debug.assert(queue.pollIndex === 0);
6289                 queue.pollScheduled = false;
6290             }
6291         }
6292         function pollLowPollingIntervalQueue(queue) {
6293             // Always poll complete list of changedFilesInLastPoll
6294             pollQueue(changedFilesInLastPoll, PollingInterval.Low, /*pollIndex*/ 0, changedFilesInLastPoll.length);
6295             // Finally do the actual polling of the queue
6296             pollPollingIntervalQueue(queue);
6297             // Schedule poll if there are files in changedFilesInLastPoll but no files in the actual queue
6298             // as pollPollingIntervalQueue wont schedule for next poll
6299             if (!queue.pollScheduled && changedFilesInLastPoll.length) {
6300                 scheduleNextPoll(PollingInterval.Low);
6301             }
6302         }
6303         function pollQueue(queue, pollingInterval, pollIndex, chunkSize) {
6304             // Max visit would be all elements of the queue
6305             var needsVisit = queue.length;
6306             var definedValueCopyToIndex = pollIndex;
6307             for (var polled = 0; polled < chunkSize && needsVisit > 0; nextPollIndex(), needsVisit--) {
6308                 var watchedFile = queue[pollIndex];
6309                 if (!watchedFile) {
6310                     continue;
6311                 }
6312                 else if (watchedFile.isClosed) {
6313                     queue[pollIndex] = undefined;
6314                     continue;
6315                 }
6316                 polled++;
6317                 var fileChanged = onWatchedFileStat(watchedFile, getModifiedTime(watchedFile.fileName));
6318                 if (watchedFile.isClosed) {
6319                     // Closed watcher as part of callback
6320                     queue[pollIndex] = undefined;
6321                 }
6322                 else if (fileChanged) {
6323                     watchedFile.unchangedPolls = 0;
6324                     // Changed files go to changedFilesInLastPoll queue
6325                     if (queue !== changedFilesInLastPoll) {
6326                         queue[pollIndex] = undefined;
6327                         addChangedFileToLowPollingIntervalQueue(watchedFile);
6328                     }
6329                 }
6330                 else if (watchedFile.unchangedPolls !== ts.unchangedPollThresholds[pollingInterval]) {
6331                     watchedFile.unchangedPolls++;
6332                 }
6333                 else if (queue === changedFilesInLastPoll) {
6334                     // Restart unchangedPollCount for unchanged file and move to low polling interval queue
6335                     watchedFile.unchangedPolls = 1;
6336                     queue[pollIndex] = undefined;
6337                     addToPollingIntervalQueue(watchedFile, PollingInterval.Low);
6338                 }
6339                 else if (pollingInterval !== PollingInterval.High) {
6340                     watchedFile.unchangedPolls++;
6341                     queue[pollIndex] = undefined;
6342                     addToPollingIntervalQueue(watchedFile, pollingInterval === PollingInterval.Low ? PollingInterval.Medium : PollingInterval.High);
6343                 }
6344                 if (queue[pollIndex]) {
6345                     // Copy this file to the non hole location
6346                     if (definedValueCopyToIndex < pollIndex) {
6347                         queue[definedValueCopyToIndex] = watchedFile;
6348                         queue[pollIndex] = undefined;
6349                     }
6350                     definedValueCopyToIndex++;
6351                 }
6352             }
6353             // Return next poll index
6354             return pollIndex;
6355             function nextPollIndex() {
6356                 pollIndex++;
6357                 if (pollIndex === queue.length) {
6358                     if (definedValueCopyToIndex < pollIndex) {
6359                         // There are holes from nextDefinedValueIndex to end of queue, change queue size
6360                         queue.length = definedValueCopyToIndex;
6361                     }
6362                     pollIndex = 0;
6363                     definedValueCopyToIndex = 0;
6364                 }
6365             }
6366         }
6367         function pollingIntervalQueue(pollingInterval) {
6368             switch (pollingInterval) {
6369                 case PollingInterval.Low:
6370                     return lowPollingIntervalQueue;
6371                 case PollingInterval.Medium:
6372                     return mediumPollingIntervalQueue;
6373                 case PollingInterval.High:
6374                     return highPollingIntervalQueue;
6375             }
6376         }
6377         function addToPollingIntervalQueue(file, pollingInterval) {
6378             pollingIntervalQueue(pollingInterval).push(file);
6379             scheduleNextPollIfNotAlreadyScheduled(pollingInterval);
6380         }
6381         function addChangedFileToLowPollingIntervalQueue(file) {
6382             changedFilesInLastPoll.push(file);
6383             scheduleNextPollIfNotAlreadyScheduled(PollingInterval.Low);
6384         }
6385         function scheduleNextPollIfNotAlreadyScheduled(pollingInterval) {
6386             if (!pollingIntervalQueue(pollingInterval).pollScheduled) {
6387                 scheduleNextPoll(pollingInterval);
6388             }
6389         }
6390         function scheduleNextPoll(pollingInterval) {
6391             pollingIntervalQueue(pollingInterval).pollScheduled = host.setTimeout(pollingInterval === PollingInterval.Low ? pollLowPollingIntervalQueue : pollPollingIntervalQueue, pollingInterval, pollingIntervalQueue(pollingInterval));
6392         }
6393         function getModifiedTime(fileName) {
6394             return host.getModifiedTime(fileName) || ts.missingFileModifiedTime;
6395         }
6396     }
6397     ts.createDynamicPriorityPollingWatchFile = createDynamicPriorityPollingWatchFile;
6398     function createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames) {
6399         // One file can have multiple watchers
6400         var fileWatcherCallbacks = ts.createMultiMap();
6401         var dirWatchers = new ts.Map();
6402         var toCanonicalName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6403         return nonPollingWatchFile;
6404         function nonPollingWatchFile(fileName, callback, _pollingInterval, fallbackOptions) {
6405             var filePath = toCanonicalName(fileName);
6406             fileWatcherCallbacks.add(filePath, callback);
6407             var dirPath = ts.getDirectoryPath(filePath) || ".";
6408             var watcher = dirWatchers.get(dirPath) ||
6409                 createDirectoryWatcher(ts.getDirectoryPath(fileName) || ".", dirPath, fallbackOptions);
6410             watcher.referenceCount++;
6411             return {
6412                 close: function () {
6413                     if (watcher.referenceCount === 1) {
6414                         watcher.close();
6415                         dirWatchers.delete(dirPath);
6416                     }
6417                     else {
6418                         watcher.referenceCount--;
6419                     }
6420                     fileWatcherCallbacks.remove(filePath, callback);
6421                 }
6422             };
6423         }
6424         function createDirectoryWatcher(dirName, dirPath, fallbackOptions) {
6425             var watcher = fsWatch(dirName, 1 /* Directory */, function (_eventName, relativeFileName) {
6426                 // When files are deleted from disk, the triggered "rename" event would have a relativefileName of "undefined"
6427                 if (!ts.isString(relativeFileName)) {
6428                     return;
6429                 }
6430                 var fileName = ts.getNormalizedAbsolutePath(relativeFileName, dirName);
6431                 // Some applications save a working file via rename operations
6432                 var callbacks = fileName && fileWatcherCallbacks.get(toCanonicalName(fileName));
6433                 if (callbacks) {
6434                     for (var _i = 0, callbacks_1 = callbacks; _i < callbacks_1.length; _i++) {
6435                         var fileCallback = callbacks_1[_i];
6436                         fileCallback(fileName, FileWatcherEventKind.Changed);
6437                     }
6438                 }
6439             }, 
6440             /*recursive*/ false, PollingInterval.Medium, fallbackOptions);
6441             watcher.referenceCount = 0;
6442             dirWatchers.set(dirPath, watcher);
6443             return watcher;
6444         }
6445     }
6446     /* @internal */
6447     function createSingleFileWatcherPerName(watchFile, useCaseSensitiveFileNames) {
6448         var cache = new ts.Map();
6449         var callbacksCache = ts.createMultiMap();
6450         var toCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
6451         return function (fileName, callback, pollingInterval, options) {
6452             var path = toCanonicalFileName(fileName);
6453             var existing = cache.get(path);
6454             if (existing) {
6455                 existing.refCount++;
6456             }
6457             else {
6458                 cache.set(path, {
6459                     watcher: watchFile(fileName, function (fileName, eventKind) { return ts.forEach(callbacksCache.get(path), function (cb) { return cb(fileName, eventKind); }); }, pollingInterval, options),
6460                     refCount: 1
6461                 });
6462             }
6463             callbacksCache.add(path, callback);
6464             return {
6465                 close: function () {
6466                     var watcher = ts.Debug.checkDefined(cache.get(path));
6467                     callbacksCache.remove(path, callback);
6468                     watcher.refCount--;
6469                     if (watcher.refCount)
6470                         return;
6471                     cache.delete(path);
6472                     ts.closeFileWatcherOf(watcher);
6473                 }
6474             };
6475         };
6476     }
6477     ts.createSingleFileWatcherPerName = createSingleFileWatcherPerName;
6478     /**
6479      * Returns true if file status changed
6480      */
6481     /*@internal*/
6482     function onWatchedFileStat(watchedFile, modifiedTime) {
6483         var oldTime = watchedFile.mtime.getTime();
6484         var newTime = modifiedTime.getTime();
6485         if (oldTime !== newTime) {
6486             watchedFile.mtime = modifiedTime;
6487             watchedFile.callback(watchedFile.fileName, getFileWatcherEventKind(oldTime, newTime));
6488             return true;
6489         }
6490         return false;
6491     }
6492     ts.onWatchedFileStat = onWatchedFileStat;
6493     /*@internal*/
6494     function getFileWatcherEventKind(oldTime, newTime) {
6495         return oldTime === 0
6496             ? FileWatcherEventKind.Created
6497             : newTime === 0
6498                 ? FileWatcherEventKind.Deleted
6499                 : FileWatcherEventKind.Changed;
6500     }
6501     ts.getFileWatcherEventKind = getFileWatcherEventKind;
6502     /*@internal*/
6503     ts.ignoredPaths = ["/node_modules/.", "/.git", "/.#"];
6504     /*@internal*/
6505     ts.sysLog = ts.noop; // eslint-disable-line prefer-const
6506     /*@internal*/
6507     function setSysLog(logger) {
6508         ts.sysLog = logger;
6509     }
6510     ts.setSysLog = setSysLog;
6511     /**
6512      * Watch the directory recursively using host provided method to watch child directories
6513      * that means if this is recursive watcher, watch the children directories as well
6514      * (eg on OS that dont support recursive watch using fs.watch use fs.watchFile)
6515      */
6516     /*@internal*/
6517     function createDirectoryWatcherSupportingRecursive(host) {
6518         var cache = new ts.Map();
6519         var callbackCache = ts.createMultiMap();
6520         var cacheToUpdateChildWatches = new ts.Map();
6521         var timerToUpdateChildWatches;
6522         var filePathComparer = ts.getStringComparer(!host.useCaseSensitiveFileNames);
6523         var toCanonicalFilePath = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
6524         return function (dirName, callback, recursive, options) { return recursive ?
6525             createDirectoryWatcher(dirName, options, callback) :
6526             host.watchDirectory(dirName, callback, recursive, options); };
6527         /**
6528          * Create the directory watcher for the dirPath.
6529          */
6530         function createDirectoryWatcher(dirName, options, callback) {
6531             var dirPath = toCanonicalFilePath(dirName);
6532             var directoryWatcher = cache.get(dirPath);
6533             if (directoryWatcher) {
6534                 directoryWatcher.refCount++;
6535             }
6536             else {
6537                 directoryWatcher = {
6538                     watcher: host.watchDirectory(dirName, function (fileName) {
6539                         if (isIgnoredPath(fileName))
6540                             return;
6541                         if (options === null || options === void 0 ? void 0 : options.synchronousWatchDirectory) {
6542                             // Call the actual callback
6543                             invokeCallbacks(dirPath, fileName);
6544                             // Iterate through existing children and update the watches if needed
6545                             updateChildWatches(dirName, dirPath, options);
6546                         }
6547                         else {
6548                             nonSyncUpdateChildWatches(dirName, dirPath, fileName, options);
6549                         }
6550                     }, /*recursive*/ false, options),
6551                     refCount: 1,
6552                     childWatches: ts.emptyArray
6553                 };
6554                 cache.set(dirPath, directoryWatcher);
6555                 updateChildWatches(dirName, dirPath, options);
6556             }
6557             var callbackToAdd = callback && { dirName: dirName, callback: callback };
6558             if (callbackToAdd) {
6559                 callbackCache.add(dirPath, callbackToAdd);
6560             }
6561             return {
6562                 dirName: dirName,
6563                 close: function () {
6564                     var directoryWatcher = ts.Debug.checkDefined(cache.get(dirPath));
6565                     if (callbackToAdd)
6566                         callbackCache.remove(dirPath, callbackToAdd);
6567                     directoryWatcher.refCount--;
6568                     if (directoryWatcher.refCount)
6569                         return;
6570                     cache.delete(dirPath);
6571                     ts.closeFileWatcherOf(directoryWatcher);
6572                     directoryWatcher.childWatches.forEach(ts.closeFileWatcher);
6573                 }
6574             };
6575         }
6576         function invokeCallbacks(dirPath, fileNameOrInvokeMap, fileNames) {
6577             var fileName;
6578             var invokeMap;
6579             if (ts.isString(fileNameOrInvokeMap)) {
6580                 fileName = fileNameOrInvokeMap;
6581             }
6582             else {
6583                 invokeMap = fileNameOrInvokeMap;
6584             }
6585             // Call the actual callback
6586             callbackCache.forEach(function (callbacks, rootDirName) {
6587                 var _a;
6588                 if (invokeMap && invokeMap.get(rootDirName) === true)
6589                     return;
6590                 if (rootDirName === dirPath || (ts.startsWith(dirPath, rootDirName) && dirPath[rootDirName.length] === ts.directorySeparator)) {
6591                     if (invokeMap) {
6592                         if (fileNames) {
6593                             var existing = invokeMap.get(rootDirName);
6594                             if (existing) {
6595                                 (_a = existing).push.apply(_a, fileNames);
6596                             }
6597                             else {
6598                                 invokeMap.set(rootDirName, fileNames.slice());
6599                             }
6600                         }
6601                         else {
6602                             invokeMap.set(rootDirName, true);
6603                         }
6604                     }
6605                     else {
6606                         callbacks.forEach(function (_a) {
6607                             var callback = _a.callback;
6608                             return callback(fileName);
6609                         });
6610                     }
6611                 }
6612             });
6613         }
6614         function nonSyncUpdateChildWatches(dirName, dirPath, fileName, options) {
6615             // Iterate through existing children and update the watches if needed
6616             var parentWatcher = cache.get(dirPath);
6617             if (parentWatcher && host.directoryExists(dirName)) {
6618                 // Schedule the update and postpone invoke for callbacks
6619                 scheduleUpdateChildWatches(dirName, dirPath, fileName, options);
6620                 return;
6621             }
6622             // Call the actual callbacks and remove child watches
6623             invokeCallbacks(dirPath, fileName);
6624             removeChildWatches(parentWatcher);
6625         }
6626         function scheduleUpdateChildWatches(dirName, dirPath, fileName, options) {
6627             var existing = cacheToUpdateChildWatches.get(dirPath);
6628             if (existing) {
6629                 existing.fileNames.push(fileName);
6630             }
6631             else {
6632                 cacheToUpdateChildWatches.set(dirPath, { dirName: dirName, options: options, fileNames: [fileName] });
6633             }
6634             if (timerToUpdateChildWatches) {
6635                 host.clearTimeout(timerToUpdateChildWatches);
6636                 timerToUpdateChildWatches = undefined;
6637             }
6638             timerToUpdateChildWatches = host.setTimeout(onTimerToUpdateChildWatches, 1000);
6639         }
6640         function onTimerToUpdateChildWatches() {
6641             timerToUpdateChildWatches = undefined;
6642             ts.sysLog("sysLog:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size);
6643             var start = ts.timestamp();
6644             var invokeMap = new ts.Map();
6645             while (!timerToUpdateChildWatches && cacheToUpdateChildWatches.size) {
6646                 var _a = cacheToUpdateChildWatches.entries().next(), _b = _a.value, dirPath = _b[0], _c = _b[1], dirName = _c.dirName, options = _c.options, fileNames = _c.fileNames, done = _a.done;
6647                 ts.Debug.assert(!done);
6648                 cacheToUpdateChildWatches.delete(dirPath);
6649                 // Because the child refresh is fresh, we would need to invalidate whole root directory being watched
6650                 // to ensure that all the changes are reflected at this time
6651                 var hasChanges = updateChildWatches(dirName, dirPath, options);
6652                 invokeCallbacks(dirPath, invokeMap, hasChanges ? undefined : fileNames);
6653             }
6654             ts.sysLog("sysLog:: invokingWatchers:: " + (ts.timestamp() - start) + "ms:: " + cacheToUpdateChildWatches.size);
6655             callbackCache.forEach(function (callbacks, rootDirName) {
6656                 var existing = invokeMap.get(rootDirName);
6657                 if (existing) {
6658                     callbacks.forEach(function (_a) {
6659                         var callback = _a.callback, dirName = _a.dirName;
6660                         if (ts.isArray(existing)) {
6661                             existing.forEach(callback);
6662                         }
6663                         else {
6664                             callback(dirName);
6665                         }
6666                     });
6667                 }
6668             });
6669             var elapsed = ts.timestamp() - start;
6670             ts.sysLog("sysLog:: Elapsed " + elapsed + "ms:: onTimerToUpdateChildWatches:: " + cacheToUpdateChildWatches.size + " " + timerToUpdateChildWatches);
6671         }
6672         function removeChildWatches(parentWatcher) {
6673             if (!parentWatcher)
6674                 return;
6675             var existingChildWatches = parentWatcher.childWatches;
6676             parentWatcher.childWatches = ts.emptyArray;
6677             for (var _i = 0, existingChildWatches_1 = existingChildWatches; _i < existingChildWatches_1.length; _i++) {
6678                 var childWatcher = existingChildWatches_1[_i];
6679                 childWatcher.close();
6680                 removeChildWatches(cache.get(toCanonicalFilePath(childWatcher.dirName)));
6681             }
6682         }
6683         function updateChildWatches(parentDir, parentDirPath, options) {
6684             // Iterate through existing children and update the watches if needed
6685             var parentWatcher = cache.get(parentDirPath);
6686             if (!parentWatcher)
6687                 return false;
6688             var newChildWatches;
6689             var hasChanges = ts.enumerateInsertsAndDeletes(host.directoryExists(parentDir) ? ts.mapDefined(host.getAccessibleSortedChildDirectories(parentDir), function (child) {
6690                 var childFullName = ts.getNormalizedAbsolutePath(child, parentDir);
6691                 // Filter our the symbolic link directories since those arent included in recursive watch
6692                 // which is same behaviour when recursive: true is passed to fs.watch
6693                 return !isIgnoredPath(childFullName) && filePathComparer(childFullName, ts.normalizePath(host.realpath(childFullName))) === 0 /* EqualTo */ ? childFullName : undefined;
6694             }) : ts.emptyArray, parentWatcher.childWatches, function (child, childWatcher) { return filePathComparer(child, childWatcher.dirName); }, createAndAddChildDirectoryWatcher, ts.closeFileWatcher, addChildDirectoryWatcher);
6695             parentWatcher.childWatches = newChildWatches || ts.emptyArray;
6696             return hasChanges;
6697             /**
6698              * Create new childDirectoryWatcher and add it to the new ChildDirectoryWatcher list
6699              */
6700             function createAndAddChildDirectoryWatcher(childName) {
6701                 var result = createDirectoryWatcher(childName, options);
6702                 addChildDirectoryWatcher(result);
6703             }
6704             /**
6705              * Add child directory watcher to the new ChildDirectoryWatcher list
6706              */
6707             function addChildDirectoryWatcher(childWatcher) {
6708                 (newChildWatches || (newChildWatches = [])).push(childWatcher);
6709             }
6710         }
6711         function isIgnoredPath(path) {
6712             return ts.some(ts.ignoredPaths, function (searchPath) { return isInPath(path, searchPath); });
6713         }
6714         function isInPath(path, searchPath) {
6715             if (ts.stringContains(path, searchPath))
6716                 return true;
6717             if (host.useCaseSensitiveFileNames)
6718                 return false;
6719             return ts.stringContains(toCanonicalFilePath(path), searchPath);
6720         }
6721     }
6722     ts.createDirectoryWatcherSupportingRecursive = createDirectoryWatcherSupportingRecursive;
6723     /*@internal*/
6724     var FileSystemEntryKind;
6725     (function (FileSystemEntryKind) {
6726         FileSystemEntryKind[FileSystemEntryKind["File"] = 0] = "File";
6727         FileSystemEntryKind[FileSystemEntryKind["Directory"] = 1] = "Directory";
6728     })(FileSystemEntryKind = ts.FileSystemEntryKind || (ts.FileSystemEntryKind = {}));
6729     /*@internal*/
6730     function createFileWatcherCallback(callback) {
6731         return function (_fileName, eventKind) { return callback(eventKind === FileWatcherEventKind.Changed ? "change" : "rename", ""); };
6732     }
6733     ts.createFileWatcherCallback = createFileWatcherCallback;
6734     function createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists) {
6735         return function (eventName) {
6736             if (eventName === "rename") {
6737                 callback(fileName, fileExists(fileName) ? FileWatcherEventKind.Created : FileWatcherEventKind.Deleted);
6738             }
6739             else {
6740                 // Change
6741                 callback(fileName, FileWatcherEventKind.Changed);
6742             }
6743         };
6744     }
6745     function createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback) {
6746         return function (eventName, relativeFileName) {
6747             // In watchDirectory we only care about adding and removing files (when event name is
6748             // "rename"); changes made within files are handled by corresponding fileWatchers (when
6749             // event name is "change")
6750             if (eventName === "rename") {
6751                 // When deleting a file, the passed baseFileName is null
6752                 callback(!relativeFileName ? directoryName : ts.normalizePath(ts.combinePaths(directoryName, relativeFileName)));
6753             }
6754         };
6755     }
6756     /*@internal*/
6757     function createSystemWatchFunctions(_a) {
6758         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;
6759         var dynamicPollingWatchFile;
6760         var nonPollingWatchFile;
6761         var hostRecursiveDirectoryWatcher;
6762         return {
6763             watchFile: watchFile,
6764             watchDirectory: watchDirectory
6765         };
6766         function watchFile(fileName, callback, pollingInterval, options) {
6767             options = updateOptionsForWatchFile(options, useNonPollingWatchers);
6768             var watchFileKind = ts.Debug.checkDefined(options.watchFile);
6769             switch (watchFileKind) {
6770                 case ts.WatchFileKind.FixedPollingInterval:
6771                     return pollingWatchFile(fileName, callback, PollingInterval.Low, /*options*/ undefined);
6772                 case ts.WatchFileKind.PriorityPollingInterval:
6773                     return pollingWatchFile(fileName, callback, pollingInterval, /*options*/ undefined);
6774                 case ts.WatchFileKind.DynamicPriorityPolling:
6775                     return ensureDynamicPollingWatchFile()(fileName, callback, pollingInterval, /*options*/ undefined);
6776                 case ts.WatchFileKind.UseFsEvents:
6777                     return fsWatch(fileName, 0 /* File */, createFsWatchCallbackForFileWatcherCallback(fileName, callback, fileExists), 
6778                     /*recursive*/ false, pollingInterval, ts.getFallbackOptions(options));
6779                 case ts.WatchFileKind.UseFsEventsOnParentDirectory:
6780                     if (!nonPollingWatchFile) {
6781                         nonPollingWatchFile = createUseFsEventsOnParentDirectoryWatchFile(fsWatch, useCaseSensitiveFileNames);
6782                     }
6783                     return nonPollingWatchFile(fileName, callback, pollingInterval, ts.getFallbackOptions(options));
6784                 default:
6785                     ts.Debug.assertNever(watchFileKind);
6786             }
6787         }
6788         function ensureDynamicPollingWatchFile() {
6789             return dynamicPollingWatchFile ||
6790                 (dynamicPollingWatchFile = createDynamicPriorityPollingWatchFile({ getModifiedTime: getModifiedTime, setTimeout: setTimeout }));
6791         }
6792         function updateOptionsForWatchFile(options, useNonPollingWatchers) {
6793             if (options && options.watchFile !== undefined)
6794                 return options;
6795             switch (tscWatchFile) {
6796                 case "PriorityPollingInterval":
6797                     // Use polling interval based on priority when create watch using host.watchFile
6798                     return { watchFile: ts.WatchFileKind.PriorityPollingInterval };
6799                 case "DynamicPriorityPolling":
6800                     // Use polling interval but change the interval depending on file changes and their default polling interval
6801                     return { watchFile: ts.WatchFileKind.DynamicPriorityPolling };
6802                 case "UseFsEvents":
6803                     // Use notifications from FS to watch with falling back to fs.watchFile
6804                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.PriorityInterval, options);
6805                 case "UseFsEventsWithFallbackDynamicPolling":
6806                     // Use notifications from FS to watch with falling back to dynamic watch file
6807                     return generateWatchFileOptions(ts.WatchFileKind.UseFsEvents, ts.PollingWatchKind.DynamicPriority, options);
6808                 case "UseFsEventsOnParentDirectory":
6809                     useNonPollingWatchers = true;
6810                 // fall through
6811                 default:
6812                     return useNonPollingWatchers ?
6813                         // Use notifications from FS to watch with falling back to fs.watchFile
6814                         generateWatchFileOptions(ts.WatchFileKind.UseFsEventsOnParentDirectory, ts.PollingWatchKind.PriorityInterval, options) :
6815                         // Default to do not use fixed polling interval
6816                         { watchFile: ts.WatchFileKind.FixedPollingInterval };
6817             }
6818         }
6819         function generateWatchFileOptions(watchFile, fallbackPolling, options) {
6820             var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
6821             return {
6822                 watchFile: watchFile,
6823                 fallbackPolling: defaultFallbackPolling === undefined ?
6824                     fallbackPolling :
6825                     defaultFallbackPolling
6826             };
6827         }
6828         function watchDirectory(directoryName, callback, recursive, options) {
6829             if (fsSupportsRecursiveFsWatch) {
6830                 return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
6831             }
6832             if (!hostRecursiveDirectoryWatcher) {
6833                 hostRecursiveDirectoryWatcher = createDirectoryWatcherSupportingRecursive({
6834                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
6835                     directoryExists: directoryExists,
6836                     getAccessibleSortedChildDirectories: getAccessibleSortedChildDirectories,
6837                     watchDirectory: nonRecursiveWatchDirectory,
6838                     realpath: realpath,
6839                     setTimeout: setTimeout,
6840                     clearTimeout: clearTimeout
6841                 });
6842             }
6843             return hostRecursiveDirectoryWatcher(directoryName, callback, recursive, options);
6844         }
6845         function nonRecursiveWatchDirectory(directoryName, callback, recursive, options) {
6846             ts.Debug.assert(!recursive);
6847             options = updateOptionsForWatchDirectory(options);
6848             var watchDirectoryKind = ts.Debug.checkDefined(options.watchDirectory);
6849             switch (watchDirectoryKind) {
6850                 case ts.WatchDirectoryKind.FixedPollingInterval:
6851                     return pollingWatchFile(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
6852                     /*options*/ undefined);
6853                 case ts.WatchDirectoryKind.DynamicPriorityPolling:
6854                     return ensureDynamicPollingWatchFile()(directoryName, function () { return callback(directoryName); }, PollingInterval.Medium, 
6855                     /*options*/ undefined);
6856                 case ts.WatchDirectoryKind.UseFsEvents:
6857                     return fsWatch(directoryName, 1 /* Directory */, createFsWatchCallbackForDirectoryWatcherCallback(directoryName, callback), recursive, PollingInterval.Medium, ts.getFallbackOptions(options));
6858                 default:
6859                     ts.Debug.assertNever(watchDirectoryKind);
6860             }
6861         }
6862         function updateOptionsForWatchDirectory(options) {
6863             if (options && options.watchDirectory !== undefined)
6864                 return options;
6865             switch (tscWatchDirectory) {
6866                 case "RecursiveDirectoryUsingFsWatchFile":
6867                     // Use polling interval based on priority when create watch using host.watchFile
6868                     return { watchDirectory: ts.WatchDirectoryKind.FixedPollingInterval };
6869                 case "RecursiveDirectoryUsingDynamicPriorityPolling":
6870                     // Use polling interval but change the interval depending on file changes and their default polling interval
6871                     return { watchDirectory: ts.WatchDirectoryKind.DynamicPriorityPolling };
6872                 default:
6873                     var defaultFallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
6874                     return {
6875                         watchDirectory: ts.WatchDirectoryKind.UseFsEvents,
6876                         fallbackPolling: defaultFallbackPolling !== undefined ?
6877                             defaultFallbackPolling :
6878                             undefined
6879                     };
6880             }
6881         }
6882     }
6883     ts.createSystemWatchFunctions = createSystemWatchFunctions;
6884     /**
6885      * patch writefile to create folder before writing the file
6886      */
6887     /*@internal*/
6888     function patchWriteFileEnsuringDirectory(sys) {
6889         // patch writefile to create folder before writing the file
6890         var originalWriteFile = sys.writeFile;
6891         sys.writeFile = function (path, data, writeBom) {
6892             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); });
6893         };
6894     }
6895     ts.patchWriteFileEnsuringDirectory = patchWriteFileEnsuringDirectory;
6896     function getNodeMajorVersion() {
6897         if (typeof process === "undefined") {
6898             return undefined;
6899         }
6900         var version = process.version;
6901         if (!version) {
6902             return undefined;
6903         }
6904         var dot = version.indexOf(".");
6905         if (dot === -1) {
6906             return undefined;
6907         }
6908         return parseInt(version.substring(1, dot));
6909     }
6910     ts.getNodeMajorVersion = getNodeMajorVersion;
6911     // TODO: GH#18217 this is used as if it's certainly defined in many places.
6912     // eslint-disable-next-line prefer-const
6913     ts.sys = (function () {
6914         // NodeJS detects "\uFEFF" at the start of the string and *replaces* it with the actual
6915         // byte order mark from the specified encoding. Using any other byte order mark does
6916         // not actually work.
6917         var byteOrderMarkIndicator = "\uFEFF";
6918         function getNodeSystem() {
6919             var nativePattern = /^native |^\([^)]+\)$|^(internal[\\/]|[a-zA-Z0-9_\s]+(\.js)?$)/;
6920             var _fs = require("fs");
6921             var _path = require("path");
6922             var _os = require("os");
6923             // crypto can be absent on reduced node installations
6924             var _crypto;
6925             try {
6926                 _crypto = require("crypto");
6927             }
6928             catch (_a) {
6929                 _crypto = undefined;
6930             }
6931             var activeSession;
6932             var profilePath = "./profile.cpuprofile";
6933             var Buffer = require("buffer").Buffer;
6934             var nodeVersion = getNodeMajorVersion();
6935             var isNode4OrLater = nodeVersion >= 4;
6936             var isLinuxOrMacOs = process.platform === "linux" || process.platform === "darwin";
6937             var platform = _os.platform();
6938             var useCaseSensitiveFileNames = isFileSystemCaseSensitive();
6939             var fsSupportsRecursiveFsWatch = isNode4OrLater && (process.platform === "win32" || process.platform === "darwin");
6940             var _b = createSystemWatchFunctions({
6941                 pollingWatchFile: createSingleFileWatcherPerName(fsWatchFileWorker, useCaseSensitiveFileNames),
6942                 getModifiedTime: getModifiedTime,
6943                 setTimeout: setTimeout,
6944                 clearTimeout: clearTimeout,
6945                 fsWatch: fsWatch,
6946                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
6947                 fileExists: fileExists,
6948                 // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
6949                 // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
6950                 fsSupportsRecursiveFsWatch: fsSupportsRecursiveFsWatch,
6951                 directoryExists: directoryExists,
6952                 getAccessibleSortedChildDirectories: function (path) { return getAccessibleFileSystemEntries(path).directories; },
6953                 realpath: realpath,
6954                 tscWatchFile: process.env.TSC_WATCHFILE,
6955                 useNonPollingWatchers: process.env.TSC_NONPOLLING_WATCHER,
6956                 tscWatchDirectory: process.env.TSC_WATCHDIRECTORY,
6957             }), watchFile = _b.watchFile, watchDirectory = _b.watchDirectory;
6958             var nodeSystem = {
6959                 args: process.argv.slice(2),
6960                 newLine: _os.EOL,
6961                 useCaseSensitiveFileNames: useCaseSensitiveFileNames,
6962                 write: function (s) {
6963                     process.stdout.write(s);
6964                 },
6965                 writeOutputIsTTY: function () {
6966                     return process.stdout.isTTY;
6967                 },
6968                 readFile: readFile,
6969                 writeFile: writeFile,
6970                 watchFile: watchFile,
6971                 watchDirectory: watchDirectory,
6972                 resolvePath: function (path) { return _path.resolve(path); },
6973                 fileExists: fileExists,
6974                 directoryExists: directoryExists,
6975                 createDirectory: function (directoryName) {
6976                     if (!nodeSystem.directoryExists(directoryName)) {
6977                         // Wrapped in a try-catch to prevent crashing if we are in a race
6978                         // with another copy of ourselves to create the same directory
6979                         try {
6980                             _fs.mkdirSync(directoryName);
6981                         }
6982                         catch (e) {
6983                             if (e.code !== "EEXIST") {
6984                                 // Failed for some other reason (access denied?); still throw
6985                                 throw e;
6986                             }
6987                         }
6988                     }
6989                 },
6990                 getExecutingFilePath: function () {
6991                     return __filename;
6992                 },
6993                 getCurrentDirectory: function () {
6994                     return process.cwd();
6995                 },
6996                 getDirectories: getDirectories,
6997                 getEnvironmentVariable: function (name) {
6998                     return process.env[name] || "";
6999                 },
7000                 readDirectory: readDirectory,
7001                 getModifiedTime: getModifiedTime,
7002                 setModifiedTime: setModifiedTime,
7003                 deleteFile: deleteFile,
7004                 createHash: _crypto ? createSHA256Hash : generateDjb2Hash,
7005                 createSHA256Hash: _crypto ? createSHA256Hash : undefined,
7006                 getMemoryUsage: function () {
7007                     if (global.gc) {
7008                         global.gc();
7009                     }
7010                     return process.memoryUsage().heapUsed;
7011                 },
7012                 getFileSize: function (path) {
7013                     try {
7014                         var stat = _fs.statSync(path);
7015                         if (stat.isFile()) {
7016                             return stat.size;
7017                         }
7018                     }
7019                     catch ( /*ignore*/_a) { /*ignore*/ }
7020                     return 0;
7021                 },
7022                 exit: function (exitCode) {
7023                     disableCPUProfiler(function () { return process.exit(exitCode); });
7024                 },
7025                 enableCPUProfiler: enableCPUProfiler,
7026                 disableCPUProfiler: disableCPUProfiler,
7027                 realpath: realpath,
7028                 debugMode: !!process.env.NODE_INSPECTOR_IPC || !!process.env.VSCODE_INSPECTOR_OPTIONS || ts.some(process.execArgv, function (arg) { return /^--(inspect|debug)(-brk)?(=\d+)?$/i.test(arg); }),
7029                 tryEnableSourceMapsForHost: function () {
7030                     try {
7031                         require("source-map-support").install();
7032                     }
7033                     catch (_a) {
7034                         // Could not enable source maps.
7035                     }
7036                 },
7037                 setTimeout: setTimeout,
7038                 clearTimeout: clearTimeout,
7039                 clearScreen: function () {
7040                     process.stdout.write("\x1Bc");
7041                 },
7042                 setBlocking: function () {
7043                     if (process.stdout && process.stdout._handle && process.stdout._handle.setBlocking) {
7044                         process.stdout._handle.setBlocking(true);
7045                     }
7046                 },
7047                 bufferFrom: bufferFrom,
7048                 base64decode: function (input) { return bufferFrom(input, "base64").toString("utf8"); },
7049                 base64encode: function (input) { return bufferFrom(input).toString("base64"); },
7050                 require: function (baseDir, moduleName) {
7051                     try {
7052                         var modulePath = ts.resolveJSModule(moduleName, baseDir, nodeSystem);
7053                         return { module: require(modulePath), modulePath: modulePath, error: undefined };
7054                     }
7055                     catch (error) {
7056                         return { module: undefined, modulePath: undefined, error: error };
7057                     }
7058                 }
7059             };
7060             return nodeSystem;
7061             /**
7062              * Uses the builtin inspector APIs to capture a CPU profile
7063              * See https://nodejs.org/api/inspector.html#inspector_example_usage for details
7064              */
7065             function enableCPUProfiler(path, cb) {
7066                 if (activeSession) {
7067                     cb();
7068                     return false;
7069                 }
7070                 var inspector = require("inspector");
7071                 if (!inspector || !inspector.Session) {
7072                     cb();
7073                     return false;
7074                 }
7075                 var session = new inspector.Session();
7076                 session.connect();
7077                 session.post("Profiler.enable", function () {
7078                     session.post("Profiler.start", function () {
7079                         activeSession = session;
7080                         profilePath = path;
7081                         cb();
7082                     });
7083                 });
7084                 return true;
7085             }
7086             /**
7087              * Strips non-TS paths from the profile, so users with private projects shouldn't
7088              * need to worry about leaking paths by submitting a cpu profile to us
7089              */
7090             function cleanupPaths(profile) {
7091                 var externalFileCounter = 0;
7092                 var remappedPaths = new ts.Map();
7093                 var normalizedDir = ts.normalizeSlashes(__dirname);
7094                 // Windows rooted dir names need an extra `/` prepended to be valid file:/// urls
7095                 var fileUrlRoot = "file://" + (ts.getRootLength(normalizedDir) === 1 ? "" : "/") + normalizedDir;
7096                 for (var _i = 0, _a = profile.nodes; _i < _a.length; _i++) {
7097                     var node = _a[_i];
7098                     if (node.callFrame.url) {
7099                         var url = ts.normalizeSlashes(node.callFrame.url);
7100                         if (ts.containsPath(fileUrlRoot, url, useCaseSensitiveFileNames)) {
7101                             node.callFrame.url = ts.getRelativePathToDirectoryOrUrl(fileUrlRoot, url, fileUrlRoot, ts.createGetCanonicalFileName(useCaseSensitiveFileNames), /*isAbsolutePathAnUrl*/ true);
7102                         }
7103                         else if (!nativePattern.test(url)) {
7104                             node.callFrame.url = (remappedPaths.has(url) ? remappedPaths : remappedPaths.set(url, "external" + externalFileCounter + ".js")).get(url);
7105                             externalFileCounter++;
7106                         }
7107                     }
7108                 }
7109                 return profile;
7110             }
7111             function disableCPUProfiler(cb) {
7112                 if (activeSession && activeSession !== "stopping") {
7113                     var s_1 = activeSession;
7114                     activeSession.post("Profiler.stop", function (err, _a) {
7115                         var profile = _a.profile;
7116                         if (!err) {
7117                             try {
7118                                 if (_fs.statSync(profilePath).isDirectory()) {
7119                                     profilePath = _path.join(profilePath, (new Date()).toISOString().replace(/:/g, "-") + "+P" + process.pid + ".cpuprofile");
7120                                 }
7121                             }
7122                             catch (_b) {
7123                                 // do nothing and ignore fallible fs operation
7124                             }
7125                             try {
7126                                 _fs.mkdirSync(_path.dirname(profilePath), { recursive: true });
7127                             }
7128                             catch (_c) {
7129                                 // do nothing and ignore fallible fs operation
7130                             }
7131                             _fs.writeFileSync(profilePath, JSON.stringify(cleanupPaths(profile)));
7132                         }
7133                         activeSession = undefined;
7134                         s_1.disconnect();
7135                         cb();
7136                     });
7137                     activeSession = "stopping";
7138                     return true;
7139                 }
7140                 else {
7141                     cb();
7142                     return false;
7143                 }
7144             }
7145             function bufferFrom(input, encoding) {
7146                 // See https://github.com/Microsoft/TypeScript/issues/25652
7147                 return Buffer.from && Buffer.from !== Int8Array.from
7148                     ? Buffer.from(input, encoding)
7149                     : new Buffer(input, encoding);
7150             }
7151             function isFileSystemCaseSensitive() {
7152                 // win32\win64 are case insensitive platforms
7153                 if (platform === "win32" || platform === "win64") {
7154                     return false;
7155                 }
7156                 // If this file exists under a different case, we must be case-insensitve.
7157                 return !fileExists(swapCase(__filename));
7158             }
7159             /** Convert all lowercase chars to uppercase, and vice-versa */
7160             function swapCase(s) {
7161                 return s.replace(/\w/g, function (ch) {
7162                     var up = ch.toUpperCase();
7163                     return ch === up ? ch.toLowerCase() : up;
7164                 });
7165             }
7166             function fsWatchFileWorker(fileName, callback, pollingInterval) {
7167                 _fs.watchFile(fileName, { persistent: true, interval: pollingInterval }, fileChanged);
7168                 var eventKind;
7169                 return {
7170                     close: function () { return _fs.unwatchFile(fileName, fileChanged); }
7171                 };
7172                 function fileChanged(curr, prev) {
7173                     // 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)
7174                     // In such case, prevTime returned is same as prev time of event when file was deleted as per node documentation
7175                     var isPreviouslyDeleted = +prev.mtime === 0 || eventKind === FileWatcherEventKind.Deleted;
7176                     if (+curr.mtime === 0) {
7177                         if (isPreviouslyDeleted) {
7178                             // Already deleted file, no need to callback again
7179                             return;
7180                         }
7181                         eventKind = FileWatcherEventKind.Deleted;
7182                     }
7183                     else if (isPreviouslyDeleted) {
7184                         eventKind = FileWatcherEventKind.Created;
7185                     }
7186                     // If there is no change in modified time, ignore the event
7187                     else if (+curr.mtime === +prev.mtime) {
7188                         return;
7189                     }
7190                     else {
7191                         // File changed
7192                         eventKind = FileWatcherEventKind.Changed;
7193                     }
7194                     callback(fileName, eventKind);
7195                 }
7196             }
7197             function fsWatch(fileOrDirectory, entryKind, callback, recursive, fallbackPollingInterval, fallbackOptions) {
7198                 var options;
7199                 var lastDirectoryPartWithDirectorySeparator;
7200                 var lastDirectoryPart;
7201                 if (isLinuxOrMacOs) {
7202                     lastDirectoryPartWithDirectorySeparator = fileOrDirectory.substr(fileOrDirectory.lastIndexOf(ts.directorySeparator));
7203                     lastDirectoryPart = lastDirectoryPartWithDirectorySeparator.slice(ts.directorySeparator.length);
7204                 }
7205                 /** Watcher for the file system entry depending on whether it is missing or present */
7206                 var watcher = !fileSystemEntryExists(fileOrDirectory, entryKind) ?
7207                     watchMissingFileSystemEntry() :
7208                     watchPresentFileSystemEntry();
7209                 return {
7210                     close: function () {
7211                         // Close the watcher (either existing file system entry watcher or missing file system entry watcher)
7212                         watcher.close();
7213                         watcher = undefined;
7214                     }
7215                 };
7216                 /**
7217                  * Invoke the callback with rename and update the watcher if not closed
7218                  * @param createWatcher
7219                  */
7220                 function invokeCallbackAndUpdateWatcher(createWatcher) {
7221                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing watcher to " + (createWatcher === watchPresentFileSystemEntry ? "Present" : "Missing") + "FileSystemEntryWatcher");
7222                     // Call the callback for current directory
7223                     callback("rename", "");
7224                     // If watcher is not closed, update it
7225                     if (watcher) {
7226                         watcher.close();
7227                         watcher = createWatcher();
7228                     }
7229                 }
7230                 /**
7231                  * Watch the file or directory that is currently present
7232                  * and when the watched file or directory is deleted, switch to missing file system entry watcher
7233                  */
7234                 function watchPresentFileSystemEntry() {
7235                     // Node 4.0 `fs.watch` function supports the "recursive" option on both OSX and Windows
7236                     // (ref: https://github.com/nodejs/node/pull/2649 and https://github.com/Microsoft/TypeScript/issues/4643)
7237                     if (options === undefined) {
7238                         if (fsSupportsRecursiveFsWatch) {
7239                             options = { persistent: true, recursive: !!recursive };
7240                         }
7241                         else {
7242                             options = { persistent: true };
7243                         }
7244                     }
7245                     try {
7246                         var presentWatcher = _fs.watch(fileOrDirectory, options, isLinuxOrMacOs ?
7247                             callbackChangingToMissingFileSystemEntry :
7248                             callback);
7249                         // Watch the missing file or directory or error
7250                         presentWatcher.on("error", function () { return invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry); });
7251                         return presentWatcher;
7252                     }
7253                     catch (e) {
7254                         // Catch the exception and use polling instead
7255                         // 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
7256                         // so instead of throwing error, use fs.watchFile
7257                         return watchPresentFileSystemEntryWithFsWatchFile();
7258                     }
7259                 }
7260                 function callbackChangingToMissingFileSystemEntry(event, relativeName) {
7261                     // because relativeName is not guaranteed to be correct we need to check on each rename with few combinations
7262                     // Eg on ubuntu while watching app/node_modules the relativeName is "node_modules" which is neither relative nor full path
7263                     return event === "rename" &&
7264                         (!relativeName ||
7265                             relativeName === lastDirectoryPart ||
7266                             relativeName.lastIndexOf(lastDirectoryPartWithDirectorySeparator) === relativeName.length - lastDirectoryPartWithDirectorySeparator.length) &&
7267                         !fileSystemEntryExists(fileOrDirectory, entryKind) ?
7268                         invokeCallbackAndUpdateWatcher(watchMissingFileSystemEntry) :
7269                         callback(event, relativeName);
7270                 }
7271                 /**
7272                  * Watch the file or directory using fs.watchFile since fs.watch threw exception
7273                  * 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
7274                  */
7275                 function watchPresentFileSystemEntryWithFsWatchFile() {
7276                     ts.sysLog("sysLog:: " + fileOrDirectory + ":: Changing to fsWatchFile");
7277                     return watchFile(fileOrDirectory, createFileWatcherCallback(callback), fallbackPollingInterval, fallbackOptions);
7278                 }
7279                 /**
7280                  * Watch the file or directory that is missing
7281                  * and switch to existing file or directory when the missing filesystem entry is created
7282                  */
7283                 function watchMissingFileSystemEntry() {
7284                     return watchFile(fileOrDirectory, function (_fileName, eventKind) {
7285                         if (eventKind === FileWatcherEventKind.Created && fileSystemEntryExists(fileOrDirectory, entryKind)) {
7286                             // Call the callback for current file or directory
7287                             // For now it could be callback for the inner directory creation,
7288                             // but just return current directory, better than current no-op
7289                             invokeCallbackAndUpdateWatcher(watchPresentFileSystemEntry);
7290                         }
7291                     }, fallbackPollingInterval, fallbackOptions);
7292                 }
7293             }
7294             function readFileWorker(fileName, _encoding) {
7295                 var buffer;
7296                 try {
7297                     buffer = _fs.readFileSync(fileName);
7298                 }
7299                 catch (e) {
7300                     return undefined;
7301                 }
7302                 var len = buffer.length;
7303                 if (len >= 2 && buffer[0] === 0xFE && buffer[1] === 0xFF) {
7304                     // Big endian UTF-16 byte order mark detected. Since big endian is not supported by node.js,
7305                     // flip all byte pairs and treat as little endian.
7306                     len &= ~1; // Round down to a multiple of 2
7307                     for (var i = 0; i < len; i += 2) {
7308                         var temp = buffer[i];
7309                         buffer[i] = buffer[i + 1];
7310                         buffer[i + 1] = temp;
7311                     }
7312                     return buffer.toString("utf16le", 2);
7313                 }
7314                 if (len >= 2 && buffer[0] === 0xFF && buffer[1] === 0xFE) {
7315                     // Little endian UTF-16 byte order mark detected
7316                     return buffer.toString("utf16le", 2);
7317                 }
7318                 if (len >= 3 && buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) {
7319                     // UTF-8 byte order mark detected
7320                     return buffer.toString("utf8", 3);
7321                 }
7322                 // Default is UTF-8 with no byte order mark
7323                 return buffer.toString("utf8");
7324             }
7325             function readFile(fileName, _encoding) {
7326                 ts.perfLogger.logStartReadFile(fileName);
7327                 var file = readFileWorker(fileName, _encoding);
7328                 ts.perfLogger.logStopReadFile();
7329                 return file;
7330             }
7331             function writeFile(fileName, data, writeByteOrderMark) {
7332                 ts.perfLogger.logEvent("WriteFile: " + fileName);
7333                 // If a BOM is required, emit one
7334                 if (writeByteOrderMark) {
7335                     data = byteOrderMarkIndicator + data;
7336                 }
7337                 var fd;
7338                 try {
7339                     fd = _fs.openSync(fileName, "w");
7340                     _fs.writeSync(fd, data, /*position*/ undefined, "utf8");
7341                 }
7342                 finally {
7343                     if (fd !== undefined) {
7344                         _fs.closeSync(fd);
7345                     }
7346                 }
7347             }
7348             function getAccessibleFileSystemEntries(path) {
7349                 ts.perfLogger.logEvent("ReadDir: " + (path || "."));
7350                 try {
7351                     var entries = _fs.readdirSync(path || ".", { withFileTypes: true });
7352                     var files = [];
7353                     var directories = [];
7354                     for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
7355                         var dirent = entries_1[_i];
7356                         // withFileTypes is not supported before Node 10.10.
7357                         var entry = typeof dirent === "string" ? dirent : dirent.name;
7358                         // This is necessary because on some file system node fails to exclude
7359                         // "." and "..". See https://github.com/nodejs/node/issues/4002
7360                         if (entry === "." || entry === "..") {
7361                             continue;
7362                         }
7363                         var stat = void 0;
7364                         if (typeof dirent === "string" || dirent.isSymbolicLink()) {
7365                             var name = ts.combinePaths(path, entry);
7366                             try {
7367                                 stat = _fs.statSync(name);
7368                             }
7369                             catch (e) {
7370                                 continue;
7371                             }
7372                         }
7373                         else {
7374                             stat = dirent;
7375                         }
7376                         if (stat.isFile()) {
7377                             files.push(entry);
7378                         }
7379                         else if (stat.isDirectory()) {
7380                             directories.push(entry);
7381                         }
7382                     }
7383                     files.sort();
7384                     directories.sort();
7385                     return { files: files, directories: directories };
7386                 }
7387                 catch (e) {
7388                     return ts.emptyFileSystemEntries;
7389                 }
7390             }
7391             function readDirectory(path, extensions, excludes, includes, depth) {
7392                 return ts.matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, process.cwd(), depth, getAccessibleFileSystemEntries, realpath);
7393             }
7394             function fileSystemEntryExists(path, entryKind) {
7395                 // Since the error thrown by fs.statSync isn't used, we can avoid collecting a stack trace to improve
7396                 // the CPU time performance.
7397                 var originalStackTraceLimit = Error.stackTraceLimit;
7398                 Error.stackTraceLimit = 0;
7399                 try {
7400                     var stat = _fs.statSync(path);
7401                     switch (entryKind) {
7402                         case 0 /* File */: return stat.isFile();
7403                         case 1 /* Directory */: return stat.isDirectory();
7404                         default: return false;
7405                     }
7406                 }
7407                 catch (e) {
7408                     return false;
7409                 }
7410                 finally {
7411                     Error.stackTraceLimit = originalStackTraceLimit;
7412                 }
7413             }
7414             function fileExists(path) {
7415                 return fileSystemEntryExists(path, 0 /* File */);
7416             }
7417             function directoryExists(path) {
7418                 return fileSystemEntryExists(path, 1 /* Directory */);
7419             }
7420             function getDirectories(path) {
7421                 return getAccessibleFileSystemEntries(path).directories.slice();
7422             }
7423             function realpath(path) {
7424                 try {
7425                     return _fs.realpathSync(path);
7426                 }
7427                 catch (_a) {
7428                     return path;
7429                 }
7430             }
7431             function getModifiedTime(path) {
7432                 try {
7433                     return _fs.statSync(path).mtime;
7434                 }
7435                 catch (e) {
7436                     return undefined;
7437                 }
7438             }
7439             function setModifiedTime(path, time) {
7440                 try {
7441                     _fs.utimesSync(path, time, time);
7442                 }
7443                 catch (e) {
7444                     return;
7445                 }
7446             }
7447             function deleteFile(path) {
7448                 try {
7449                     return _fs.unlinkSync(path);
7450                 }
7451                 catch (e) {
7452                     return;
7453                 }
7454             }
7455             function createSHA256Hash(data) {
7456                 var hash = _crypto.createHash("sha256");
7457                 hash.update(data);
7458                 return hash.digest("hex");
7459             }
7460         }
7461         var sys;
7462         if (typeof process !== "undefined" && process.nextTick && !process.browser && typeof require !== "undefined") {
7463             // process and process.nextTick checks if current environment is node-like
7464             // process.browser check excludes webpack and browserify
7465             sys = getNodeSystem();
7466         }
7467         if (sys) {
7468             // patch writefile to create folder before writing the file
7469             patchWriteFileEnsuringDirectory(sys);
7470         }
7471         return sys;
7472     })();
7473     if (ts.sys && ts.sys.getEnvironmentVariable) {
7474         setCustomPollingValues(ts.sys);
7475         ts.Debug.setAssertionLevel(/^development$/i.test(ts.sys.getEnvironmentVariable("NODE_ENV"))
7476             ? 1 /* Normal */
7477             : 0 /* None */);
7478     }
7479     if (ts.sys && ts.sys.debugMode) {
7480         ts.Debug.isDebugging = true;
7481     }
7482 })(ts || (ts = {}));
7483 // <auto-generated />
7484 // generated from './diagnosticInformationMap.generated.ts' by 'src/compiler'
7485 /* @internal */
7486 var ts;
7487 (function (ts) {
7488     function diag(code, category, key, message, reportsUnnecessary, elidedInCompatabilityPyramid, reportsDeprecated) {
7489         return { code: code, category: category, key: key, message: message, reportsUnnecessary: reportsUnnecessary, elidedInCompatabilityPyramid: elidedInCompatabilityPyramid, reportsDeprecated: reportsDeprecated };
7490     }
7491     ts.Diagnostics = {
7492         Unterminated_string_literal: diag(1002, ts.DiagnosticCategory.Error, "Unterminated_string_literal_1002", "Unterminated string literal."),
7493         Identifier_expected: diag(1003, ts.DiagnosticCategory.Error, "Identifier_expected_1003", "Identifier expected."),
7494         _0_expected: diag(1005, ts.DiagnosticCategory.Error, "_0_expected_1005", "'{0}' expected."),
7495         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."),
7496         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."),
7497         Trailing_comma_not_allowed: diag(1009, ts.DiagnosticCategory.Error, "Trailing_comma_not_allowed_1009", "Trailing comma not allowed."),
7498         Asterisk_Slash_expected: diag(1010, ts.DiagnosticCategory.Error, "Asterisk_Slash_expected_1010", "'*/' expected."),
7499         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."),
7500         Unexpected_token: diag(1012, ts.DiagnosticCategory.Error, "Unexpected_token_1012", "Unexpected token."),
7501         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."),
7502         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."),
7503         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."),
7504         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."),
7505         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."),
7506         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."),
7507         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."),
7508         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."),
7509         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."),
7510         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."),
7511         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'."),
7512         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."),
7513         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."),
7514         Accessibility_modifier_already_seen: diag(1028, ts.DiagnosticCategory.Error, "Accessibility_modifier_already_seen_1028", "Accessibility modifier already seen."),
7515         _0_modifier_must_precede_1_modifier: diag(1029, ts.DiagnosticCategory.Error, "_0_modifier_must_precede_1_modifier_1029", "'{0}' modifier must precede '{1}' modifier."),
7516         _0_modifier_already_seen: diag(1030, ts.DiagnosticCategory.Error, "_0_modifier_already_seen_1030", "'{0}' modifier already seen."),
7517         _0_modifier_cannot_appear_on_class_elements_of_this_kind: diag(1031, ts.DiagnosticCategory.Error, "_0_modifier_cannot_appear_on_class_elements_of_this_kind_1031", "'{0}' modifier cannot appear on class elements of this kind."),
7518         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."),
7519         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."),
7520         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."),
7521         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."),
7522         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."),
7523         _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."),
7524         _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."),
7525         _0_modifier_cannot_be_used_here: diag(1042, ts.DiagnosticCategory.Error, "_0_modifier_cannot_be_used_here_1042", "'{0}' modifier cannot be used here."),
7526         _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."),
7527         _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."),
7528         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."),
7529         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."),
7530         A_rest_parameter_cannot_be_optional: diag(1047, ts.DiagnosticCategory.Error, "A_rest_parameter_cannot_be_optional_1047", "A rest parameter cannot be optional."),
7531         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."),
7532         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."),
7533         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."),
7534         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."),
7535         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."),
7536         A_get_accessor_cannot_have_parameters: diag(1054, ts.DiagnosticCategory.Error, "A_get_accessor_cannot_have_parameters_1054", "A 'get' accessor cannot have parameters."),
7537         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."),
7538         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."),
7539         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."),
7540         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."),
7541         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."),
7542         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."),
7543         Enum_member_must_have_initializer: diag(1061, ts.DiagnosticCategory.Error, "Enum_member_must_have_initializer_1061", "Enum member must have initializer."),
7544         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."),
7545         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."),
7546         The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0: diag(1064, ts.DiagnosticCategory.Error, "The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_wri_1064", "The return type of an async function or method must be the global Promise<T> type. Did you mean to write 'Promise<{0}>'?"),
7547         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."),
7548         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."),
7549         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."),
7550         _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."),
7551         _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."),
7552         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."),
7553         Invalid_reference_directive_syntax: diag(1084, ts.DiagnosticCategory.Error, "Invalid_reference_directive_syntax_1084", "Invalid 'reference' directive syntax."),
7554         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}'."),
7555         _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."),
7556         _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."),
7557         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."),
7558         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."),
7559         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."),
7560         An_accessor_cannot_have_type_parameters: diag(1094, ts.DiagnosticCategory.Error, "An_accessor_cannot_have_type_parameters_1094", "An accessor cannot have type parameters."),
7561         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."),
7562         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."),
7563         _0_list_cannot_be_empty: diag(1097, ts.DiagnosticCategory.Error, "_0_list_cannot_be_empty_1097", "'{0}' list cannot be empty."),
7564         Type_parameter_list_cannot_be_empty: diag(1098, ts.DiagnosticCategory.Error, "Type_parameter_list_cannot_be_empty_1098", "Type parameter list cannot be empty."),
7565         Type_argument_list_cannot_be_empty: diag(1099, ts.DiagnosticCategory.Error, "Type_argument_list_cannot_be_empty_1099", "Type argument list cannot be empty."),
7566         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."),
7567         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."),
7568         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."),
7569         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."),
7570         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."),
7571         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."),
7572         Jump_target_cannot_cross_function_boundary: diag(1107, ts.DiagnosticCategory.Error, "Jump_target_cannot_cross_function_boundary_1107", "Jump target cannot cross function boundary."),
7573         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."),
7574         Expression_expected: diag(1109, ts.DiagnosticCategory.Error, "Expression_expected_1109", "Expression expected."),
7575         Type_expected: diag(1110, ts.DiagnosticCategory.Error, "Type_expected_1110", "Type expected."),
7576         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."),
7577         Duplicate_label_0: diag(1114, ts.DiagnosticCategory.Error, "Duplicate_label_0_1114", "Duplicate label '{0}'."),
7578         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."),
7579         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."),
7580         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."),
7581         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."),
7582         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."),
7583         An_export_assignment_cannot_have_modifiers: diag(1120, ts.DiagnosticCategory.Error, "An_export_assignment_cannot_have_modifiers_1120", "An export assignment cannot have modifiers."),
7584         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."),
7585         Variable_declaration_list_cannot_be_empty: diag(1123, ts.DiagnosticCategory.Error, "Variable_declaration_list_cannot_be_empty_1123", "Variable declaration list cannot be empty."),
7586         Digit_expected: diag(1124, ts.DiagnosticCategory.Error, "Digit_expected_1124", "Digit expected."),
7587         Hexadecimal_digit_expected: diag(1125, ts.DiagnosticCategory.Error, "Hexadecimal_digit_expected_1125", "Hexadecimal digit expected."),
7588         Unexpected_end_of_text: diag(1126, ts.DiagnosticCategory.Error, "Unexpected_end_of_text_1126", "Unexpected end of text."),
7589         Invalid_character: diag(1127, ts.DiagnosticCategory.Error, "Invalid_character_1127", "Invalid character."),
7590         Declaration_or_statement_expected: diag(1128, ts.DiagnosticCategory.Error, "Declaration_or_statement_expected_1128", "Declaration or statement expected."),
7591         Statement_expected: diag(1129, ts.DiagnosticCategory.Error, "Statement_expected_1129", "Statement expected."),
7592         case_or_default_expected: diag(1130, ts.DiagnosticCategory.Error, "case_or_default_expected_1130", "'case' or 'default' expected."),
7593         Property_or_signature_expected: diag(1131, ts.DiagnosticCategory.Error, "Property_or_signature_expected_1131", "Property or signature expected."),
7594         Enum_member_expected: diag(1132, ts.DiagnosticCategory.Error, "Enum_member_expected_1132", "Enum member expected."),
7595         Variable_declaration_expected: diag(1134, ts.DiagnosticCategory.Error, "Variable_declaration_expected_1134", "Variable declaration expected."),
7596         Argument_expression_expected: diag(1135, ts.DiagnosticCategory.Error, "Argument_expression_expected_1135", "Argument expression expected."),
7597         Property_assignment_expected: diag(1136, ts.DiagnosticCategory.Error, "Property_assignment_expected_1136", "Property assignment expected."),
7598         Expression_or_comma_expected: diag(1137, ts.DiagnosticCategory.Error, "Expression_or_comma_expected_1137", "Expression or comma expected."),
7599         Parameter_declaration_expected: diag(1138, ts.DiagnosticCategory.Error, "Parameter_declaration_expected_1138", "Parameter declaration expected."),
7600         Type_parameter_declaration_expected: diag(1139, ts.DiagnosticCategory.Error, "Type_parameter_declaration_expected_1139", "Type parameter declaration expected."),
7601         Type_argument_expected: diag(1140, ts.DiagnosticCategory.Error, "Type_argument_expected_1140", "Type argument expected."),
7602         String_literal_expected: diag(1141, ts.DiagnosticCategory.Error, "String_literal_expected_1141", "String literal expected."),
7603         Line_break_not_permitted_here: diag(1142, ts.DiagnosticCategory.Error, "Line_break_not_permitted_here_1142", "Line break not permitted here."),
7604         or_expected: diag(1144, ts.DiagnosticCategory.Error, "or_expected_1144", "'{' or ';' expected."),
7605         Declaration_expected: diag(1146, ts.DiagnosticCategory.Error, "Declaration_expected_1146", "Declaration expected."),
7606         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."),
7607         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'."),
7608         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."),
7609         const_declarations_must_be_initialized: diag(1155, ts.DiagnosticCategory.Error, "const_declarations_must_be_initialized_1155", "'const' declarations must be initialized."),
7610         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."),
7611         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."),
7612         Unterminated_template_literal: diag(1160, ts.DiagnosticCategory.Error, "Unterminated_template_literal_1160", "Unterminated template literal."),
7613         Unterminated_regular_expression_literal: diag(1161, ts.DiagnosticCategory.Error, "Unterminated_regular_expression_literal_1161", "Unterminated regular expression literal."),
7614         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."),
7615         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."),
7616         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."),
7617         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."),
7618         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."),
7619         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."),
7620         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."),
7621         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."),
7622         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."),
7623         extends_clause_already_seen: diag(1172, ts.DiagnosticCategory.Error, "extends_clause_already_seen_1172", "'extends' clause already seen."),
7624         extends_clause_must_precede_implements_clause: diag(1173, ts.DiagnosticCategory.Error, "extends_clause_must_precede_implements_clause_1173", "'extends' clause must precede 'implements' clause."),
7625         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."),
7626         implements_clause_already_seen: diag(1175, ts.DiagnosticCategory.Error, "implements_clause_already_seen_1175", "'implements' clause already seen."),
7627         Interface_declaration_cannot_have_implements_clause: diag(1176, ts.DiagnosticCategory.Error, "Interface_declaration_cannot_have_implements_clause_1176", "Interface declaration cannot have 'implements' clause."),
7628         Binary_digit_expected: diag(1177, ts.DiagnosticCategory.Error, "Binary_digit_expected_1177", "Binary digit expected."),
7629         Octal_digit_expected: diag(1178, ts.DiagnosticCategory.Error, "Octal_digit_expected_1178", "Octal digit expected."),
7630         Unexpected_token_expected: diag(1179, ts.DiagnosticCategory.Error, "Unexpected_token_expected_1179", "Unexpected token. '{' expected."),
7631         Property_destructuring_pattern_expected: diag(1180, ts.DiagnosticCategory.Error, "Property_destructuring_pattern_expected_1180", "Property destructuring pattern expected."),
7632         Array_element_destructuring_pattern_expected: diag(1181, ts.DiagnosticCategory.Error, "Array_element_destructuring_pattern_expected_1181", "Array element destructuring pattern expected."),
7633         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."),
7634         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."),
7635         Modifiers_cannot_appear_here: diag(1184, ts.DiagnosticCategory.Error, "Modifiers_cannot_appear_here_1184", "Modifiers cannot appear here."),
7636         Merge_conflict_marker_encountered: diag(1185, ts.DiagnosticCategory.Error, "Merge_conflict_marker_encountered_1185", "Merge conflict marker encountered."),
7637         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."),
7638         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."),
7639         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."),
7640         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."),
7641         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."),
7642         An_import_declaration_cannot_have_modifiers: diag(1191, ts.DiagnosticCategory.Error, "An_import_declaration_cannot_have_modifiers_1191", "An import declaration cannot have modifiers."),
7643         Module_0_has_no_default_export: diag(1192, ts.DiagnosticCategory.Error, "Module_0_has_no_default_export_1192", "Module '{0}' has no default export."),
7644         An_export_declaration_cannot_have_modifiers: diag(1193, ts.DiagnosticCategory.Error, "An_export_declaration_cannot_have_modifiers_1193", "An export declaration cannot have modifiers."),
7645         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."),
7646         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."),
7647         Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified: diag(1196, ts.DiagnosticCategory.Error, "Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified_1196", "Catch clause variable type annotation must be 'any' or 'unknown' if specified."),
7648         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."),
7649         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."),
7650         Unterminated_Unicode_escape_sequence: diag(1199, ts.DiagnosticCategory.Error, "Unterminated_Unicode_escape_sequence_1199", "Unterminated Unicode escape sequence."),
7651         Line_terminator_not_permitted_before_arrow: diag(1200, ts.DiagnosticCategory.Error, "Line_terminator_not_permitted_before_arrow_1200", "Line terminator not permitted before arrow."),
7652         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."),
7653         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."),
7654         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'."),
7655         Decorators_are_not_valid_here: diag(1206, ts.DiagnosticCategory.Error, "Decorators_are_not_valid_here_1206", "Decorators are not valid here."),
7656         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."),
7657         _0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module: diag(1208, ts.DiagnosticCategory.Error, "_0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_imp_1208", "'{0}' cannot be compiled under '--isolatedModules' because it is considered a global script file. Add an import, export, or an empty 'export {}' statement to make it a module."),
7658         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."),
7659         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."),
7660         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."),
7661         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."),
7662         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."),
7663         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."),
7664         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."),
7665         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'."),
7666         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."),
7667         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."),
7668         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."),
7669         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."),
7670         _0_tag_already_specified: diag(1223, ts.DiagnosticCategory.Error, "_0_tag_already_specified_1223", "'{0}' tag already specified."),
7671         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."),
7672         Cannot_find_parameter_0: diag(1225, ts.DiagnosticCategory.Error, "Cannot_find_parameter_0_1225", "Cannot find parameter '{0}'."),
7673         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}'."),
7674         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}'."),
7675         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."),
7676         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."),
7677         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."),
7678         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."),
7679         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."),
7680         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."),
7681         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."),
7682         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."),
7683         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'."),
7684         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'."),
7685         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."),
7686         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."),
7687         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."),
7688         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."),
7689         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."),
7690         _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."),
7691         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."),
7692         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."),
7693         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."),
7694         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."),
7695         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."),
7696         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."),
7697         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'."),
7698         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."),
7699         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."),
7700         _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."),
7701         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."),
7702         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."),
7703         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."),
7704         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."),
7705         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"),
7706         Keywords_cannot_contain_escape_characters: diag(1260, ts.DiagnosticCategory.Error, "Keywords_cannot_contain_escape_characters_1260", "Keywords cannot contain escape characters."),
7707         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."),
7708         Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module: diag(1262, ts.DiagnosticCategory.Error, "Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module_1262", "Identifier expected. '{0}' is a reserved word at the top-level of a module."),
7709         Declarations_with_initializers_cannot_also_have_definite_assignment_assertions: diag(1263, ts.DiagnosticCategory.Error, "Declarations_with_initializers_cannot_also_have_definite_assignment_assertions_1263", "Declarations with initializers cannot also have definite assignment assertions."),
7710         Declarations_with_definite_assignment_assertions_must_also_have_type_annotations: diag(1264, ts.DiagnosticCategory.Error, "Declarations_with_definite_assignment_assertions_must_also_have_type_annotations_1264", "Declarations with definite assignment assertions must also have type annotations."),
7711         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."),
7712         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."),
7713         Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern: diag(1312, ts.DiagnosticCategory.Error, "Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_1312", "Did you mean to use a ':'? An '=' can only follow a property name when the containing object literal is part of a destructuring pattern."),
7714         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."),
7715         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."),
7716         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."),
7717         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."),
7718         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."),
7719         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."),
7720         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."),
7721         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."),
7722         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."),
7723         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."),
7724         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'."),
7725         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."),
7726         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."),
7727         Dynamic_import_cannot_have_type_arguments: diag(1326, ts.DiagnosticCategory.Error, "Dynamic_import_cannot_have_type_arguments_1326", "Dynamic import cannot have type arguments."),
7728         String_literal_with_double_quotes_expected: diag(1327, ts.DiagnosticCategory.Error, "String_literal_with_double_quotes_expected_1327", "String literal with double quotes expected."),
7729         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."),
7730         _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}()'?"),
7731         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'."),
7732         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'."),
7733         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'."),
7734         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."),
7735         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."),
7736         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."),
7737         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."),
7738         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."),
7739         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."),
7740         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."),
7741         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}')'?"),
7742         Type_arguments_cannot_be_used_here: diag(1342, ts.DiagnosticCategory.Error, "Type_arguments_cannot_be_used_here_1342", "Type arguments cannot be used here."),
7743         The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system: diag(1343, ts.DiagnosticCategory.Error, "The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system_1343", "The 'import.meta' meta-property is only allowed when the '--module' option is 'es2020', 'esnext', or 'system'."),
7744         A_label_is_not_allowed_here: diag(1344, ts.DiagnosticCategory.Error, "A_label_is_not_allowed_here_1344", "'A label is not allowed here."),
7745         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."),
7746         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."),
7747         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."),
7748         Non_simple_parameter_declared_here: diag(1348, ts.DiagnosticCategory.Error, "Non_simple_parameter_declared_here_1348", "Non-simple parameter declared here."),
7749         use_strict_directive_used_here: diag(1349, ts.DiagnosticCategory.Error, "use_strict_directive_used_here_1349", "'use strict' directive used here."),
7750         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."),
7751         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."),
7752         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."),
7753         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."),
7754         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."),
7755         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."),
7756         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'?"),
7757         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 '}'."),
7758         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."),
7759         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."),
7760         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?"),
7761         _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'."),
7762         _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'."),
7763         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."),
7764         Convert_to_type_only_export: diag(1364, ts.DiagnosticCategory.Message, "Convert_to_type_only_export_1364", "Convert to type-only export"),
7765         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"),
7766         Split_into_two_separate_import_declarations: diag(1366, ts.DiagnosticCategory.Message, "Split_into_two_separate_import_declarations_1366", "Split into two separate import declarations"),
7767         Split_all_invalid_type_only_imports: diag(1367, ts.DiagnosticCategory.Message, "Split_all_invalid_type_only_imports_1367", "Split all invalid type-only imports"),
7768         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"),
7769         Did_you_mean_0: diag(1369, ts.DiagnosticCategory.Message, "Did_you_mean_0_1369", "Did you mean '{0}'?"),
7770         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'."),
7771         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'."),
7772         Convert_to_type_only_import: diag(1373, ts.DiagnosticCategory.Message, "Convert_to_type_only_import_1373", "Convert to type-only import"),
7773         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"),
7774         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."),
7775         _0_was_imported_here: diag(1376, ts.DiagnosticCategory.Message, "_0_was_imported_here_1376", "'{0}' was imported here."),
7776         _0_was_exported_here: diag(1377, ts.DiagnosticCategory.Message, "_0_was_exported_here_1377", "'{0}' was exported here."),
7777         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."),
7778         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'."),
7779         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'."),
7780         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;`?"),
7781         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;`?"),
7782         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'."),
7783         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."),
7784         Function_type_notation_must_be_parenthesized_when_used_in_a_union_type: diag(1385, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_a_union_type_1385", "Function type notation must be parenthesized when used in a union type."),
7785         Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type: diag(1386, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type_1386", "Constructor type notation must be parenthesized when used in a union type."),
7786         Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1387, ts.DiagnosticCategory.Error, "Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1387", "Function type notation must be parenthesized when used in an intersection type."),
7787         Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type: diag(1388, ts.DiagnosticCategory.Error, "Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type_1388", "Constructor type notation must be parenthesized when used in an intersection type."),
7788         _0_is_not_allowed_as_a_variable_declaration_name: diag(1389, ts.DiagnosticCategory.Error, "_0_is_not_allowed_as_a_variable_declaration_name_1389", "'{0}' is not allowed as a variable declaration name."),
7789         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."),
7790         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."),
7791         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),
7792         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),
7793         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),
7794         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),
7795         Duplicate_identifier_0: diag(2300, ts.DiagnosticCategory.Error, "Duplicate_identifier_0_2300", "Duplicate identifier '{0}'."),
7796         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."),
7797         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."),
7798         Circular_definition_of_import_alias_0: diag(2303, ts.DiagnosticCategory.Error, "Circular_definition_of_import_alias_0_2303", "Circular definition of import alias '{0}'."),
7799         Cannot_find_name_0: diag(2304, ts.DiagnosticCategory.Error, "Cannot_find_name_0_2304", "Cannot find name '{0}'."),
7800         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}'."),
7801         File_0_is_not_a_module: diag(2306, ts.DiagnosticCategory.Error, "File_0_is_not_a_module_2306", "File '{0}' is not a module."),
7802         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."),
7803         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."),
7804         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."),
7805         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."),
7806         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."),
7807         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."),
7808         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."),
7809         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)."),
7810         Type_0_is_not_generic: diag(2315, ts.DiagnosticCategory.Error, "Type_0_is_not_generic_2315", "Type '{0}' is not generic."),
7811         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."),
7812         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)."),
7813         Cannot_find_global_type_0: diag(2318, ts.DiagnosticCategory.Error, "Cannot_find_global_type_0_2318", "Cannot find global type '{0}'."),
7814         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."),
7815         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}'."),
7816         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}'."),
7817         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}'."),
7818         Cannot_redeclare_exported_variable_0: diag(2323, ts.DiagnosticCategory.Error, "Cannot_redeclare_exported_variable_0_2323", "Cannot redeclare exported variable '{0}'."),
7819         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}'."),
7820         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}'."),
7821         Types_of_property_0_are_incompatible: diag(2326, ts.DiagnosticCategory.Error, "Types_of_property_0_are_incompatible_2326", "Types of property '{0}' are incompatible."),
7822         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}'."),
7823         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."),
7824         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}'."),
7825         Index_signatures_are_incompatible: diag(2330, ts.DiagnosticCategory.Error, "Index_signatures_are_incompatible_2330", "Index signatures are incompatible."),
7826         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."),
7827         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."),
7828         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."),
7829         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."),
7830         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."),
7831         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."),
7832         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."),
7833         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."),
7834         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}'."),
7835         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."),
7836         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}'."),
7837         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'."),
7838         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}'."),
7839         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}'."),
7840         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}'."),
7841         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."),
7842         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."),
7843         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'?"),
7844         This_expression_is_not_callable: diag(2349, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_2349", "This expression is not callable."),
7845         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."),
7846         This_expression_is_not_constructable: diag(2351, ts.DiagnosticCategory.Error, "This_expression_is_not_constructable_2351", "This expression is not constructable."),
7847         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."),
7848         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}'."),
7849         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."),
7850         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."),
7851         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."),
7852         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."),
7853         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."),
7854         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."),
7855         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'."),
7856         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."),
7857         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."),
7858         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."),
7859         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."),
7860         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}'."),
7861         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'."),
7862         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."),
7863         Type_parameter_name_cannot_be_0: diag(2368, ts.DiagnosticCategory.Error, "Type_parameter_name_cannot_be_0_2368", "Type parameter name cannot be '{0}'."),
7864         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."),
7865         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."),
7866         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."),
7867         Parameter_0_cannot_reference_itself: diag(2372, ts.DiagnosticCategory.Error, "Parameter_0_cannot_reference_itself_2372", "Parameter '{0}' cannot reference itself."),
7868         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."),
7869         Duplicate_string_index_signature: diag(2374, ts.DiagnosticCategory.Error, "Duplicate_string_index_signature_2374", "Duplicate string index signature."),
7870         Duplicate_number_index_signature: diag(2375, ts.DiagnosticCategory.Error, "Duplicate_number_index_signature_2375", "Duplicate number index signature."),
7871         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."),
7872         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."),
7873         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."),
7874         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."),
7875         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."),
7876         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."),
7877         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."),
7878         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."),
7879         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."),
7880         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."),
7881         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."),
7882         Function_overload_must_be_static: diag(2387, ts.DiagnosticCategory.Error, "Function_overload_must_be_static_2387", "Function overload must be static."),
7883         Function_overload_must_not_be_static: diag(2388, ts.DiagnosticCategory.Error, "Function_overload_must_not_be_static_2388", "Function overload must not be static."),
7884         Function_implementation_name_must_be_0: diag(2389, ts.DiagnosticCategory.Error, "Function_implementation_name_must_be_0_2389", "Function implementation name must be '{0}'."),
7885         Constructor_implementation_is_missing: diag(2390, ts.DiagnosticCategory.Error, "Constructor_implementation_is_missing_2390", "Constructor implementation is missing."),
7886         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."),
7887         Multiple_constructor_implementations_are_not_allowed: diag(2392, ts.DiagnosticCategory.Error, "Multiple_constructor_implementations_are_not_allowed_2392", "Multiple constructor implementations are not allowed."),
7888         Duplicate_function_implementation: diag(2393, ts.DiagnosticCategory.Error, "Duplicate_function_implementation_2393", "Duplicate function implementation."),
7889         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."),
7890         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."),
7891         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."),
7892         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}'."),
7893         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."),
7894         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."),
7895         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."),
7896         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."),
7897         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."),
7898         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}'."),
7899         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."),
7900         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'."),
7901         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."),
7902         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}'."),
7903         Setters_cannot_return_a_value: diag(2408, ts.DiagnosticCategory.Error, "Setters_cannot_return_a_value_2408", "Setters cannot return a value."),
7904         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."),
7905         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'."),
7906         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}'."),
7907         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}'."),
7908         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}'."),
7909         Class_name_cannot_be_0: diag(2414, ts.DiagnosticCategory.Error, "Class_name_cannot_be_0_2414", "Class name cannot be '{0}'."),
7910         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}'."),
7911         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}'."),
7912         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}'."),
7913         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}'."),
7914         Types_of_construct_signatures_are_incompatible: diag(2419, ts.DiagnosticCategory.Error, "Types_of_construct_signatures_are_incompatible_2419", "Types of construct signatures are incompatible."),
7915         Class_0_incorrectly_implements_interface_1: diag(2420, ts.DiagnosticCategory.Error, "Class_0_incorrectly_implements_interface_1_2420", "Class '{0}' incorrectly implements interface '{1}'."),
7916         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."),
7917         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."),
7918         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."),
7919         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."),
7920         Interface_name_cannot_be_0: diag(2427, ts.DiagnosticCategory.Error, "Interface_name_cannot_be_0_2427", "Interface name cannot be '{0}'."),
7921         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."),
7922         Interface_0_incorrectly_extends_interface_1: diag(2430, ts.DiagnosticCategory.Error, "Interface_0_incorrectly_extends_interface_1_2430", "Interface '{0}' incorrectly extends interface '{1}'."),
7923         Enum_name_cannot_be_0: diag(2431, ts.DiagnosticCategory.Error, "Enum_name_cannot_be_0_2431", "Enum name cannot be '{0}'."),
7924         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."),
7925         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."),
7926         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."),
7927         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."),
7928         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."),
7929         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."),
7930         Import_name_cannot_be_0: diag(2438, ts.DiagnosticCategory.Error, "Import_name_cannot_be_0_2438", "Import name cannot be '{0}'."),
7931         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."),
7932         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}'."),
7933         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."),
7934         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}'."),
7935         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}'."),
7936         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}'."),
7937         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."),
7938         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}'."),
7939         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."),
7940         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."),
7941         Class_0_used_before_its_declaration: diag(2449, ts.DiagnosticCategory.Error, "Class_0_used_before_its_declaration_2449", "Class '{0}' used before its declaration."),
7942         Enum_0_used_before_its_declaration: diag(2450, ts.DiagnosticCategory.Error, "Enum_0_used_before_its_declaration_2450", "Enum '{0}' used before its declaration."),
7943         Cannot_redeclare_block_scoped_variable_0: diag(2451, ts.DiagnosticCategory.Error, "Cannot_redeclare_block_scoped_variable_0_2451", "Cannot redeclare block-scoped variable '{0}'."),
7944         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."),
7945         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."),
7946         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."),
7947         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}'."),
7948         Type_alias_0_circularly_references_itself: diag(2456, ts.DiagnosticCategory.Error, "Type_alias_0_circularly_references_itself_2456", "Type alias '{0}' circularly references itself."),
7949         Type_alias_name_cannot_be_0: diag(2457, ts.DiagnosticCategory.Error, "Type_alias_name_cannot_be_0_2457", "Type alias name cannot be '{0}'."),
7950         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."),
7951         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."),
7952         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}'."),
7953         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."),
7954         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."),
7955         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."),
7956         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'."),
7957         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."),
7958         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."),
7959         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."),
7960         Cannot_find_global_value_0: diag(2468, ts.DiagnosticCategory.Error, "Cannot_find_global_value_0_2468", "Cannot find global value '{0}'."),
7961         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'."),
7962         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."),
7963         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'."),
7964         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."),
7965         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."),
7966         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."),
7967         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."),
7968         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."),
7969         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."),
7970         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'."),
7971         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}'."),
7972         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."),
7973         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}'."),
7974         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."),
7975         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}'."),
7976         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."),
7977         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."),
7978         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."),
7979         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."),
7980         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."),
7981         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."),
7982         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}'."),
7983         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."),
7984         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."),
7985         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."),
7986         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."),
7987         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 *'."),
7988         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."),
7989         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."),
7990         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."),
7991         _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."),
7992         Cannot_find_namespace_0: diag(2503, ts.DiagnosticCategory.Error, "Cannot_find_namespace_0_2503", "Cannot find namespace '{0}'."),
7993         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."),
7994         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."),
7995         _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."),
7996         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."),
7997         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."),
7998         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."),
7999         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."),
8000         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."),
8001         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."),
8002         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."),
8003         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."),
8004         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}'."),
8005         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."),
8006         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."),
8007         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."),
8008         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."),
8009         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."),
8010         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."),
8011         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."),
8012         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."),
8013         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."),
8014         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."),
8015         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."),
8016         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."),
8017         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."),
8018         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."),
8019         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."),
8020         Object_is_possibly_null: diag(2531, ts.DiagnosticCategory.Error, "Object_is_possibly_null_2531", "Object is possibly 'null'."),
8021         Object_is_possibly_undefined: diag(2532, ts.DiagnosticCategory.Error, "Object_is_possibly_undefined_2532", "Object is possibly 'undefined'."),
8022         Object_is_possibly_null_or_undefined: diag(2533, ts.DiagnosticCategory.Error, "Object_is_possibly_null_or_undefined_2533", "Object is possibly 'null' or 'undefined'."),
8023         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."),
8024         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."),
8025         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}'."),
8026         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}'."),
8027         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."),
8028         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."),
8029         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."),
8030         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."),
8031         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."),
8032         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."),
8033         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."),
8034         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[]'."),
8035         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."),
8036         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."),
8037         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."),
8038         Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later: diag(2550, ts.DiagnosticCategory.Error, "Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_c_2550", "Property '{0}' does not exist on type '{1}'. Do you need to change your target library? Try changing the `lib` compiler option to '{2}' or later."),
8039         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}'?"),
8040         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}'?"),
8041         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."),
8042         Expected_0_arguments_but_got_1: diag(2554, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_2554", "Expected {0} arguments, but got {1}."),
8043         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}."),
8044         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."),
8045         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."),
8046         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}."),
8047         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}'."),
8048         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?"),
8049         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}'?"),
8050         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."),
8051         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."),
8052         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."),
8053         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."),
8054         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."),
8055         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."),
8056         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."),
8057         Object_is_of_type_unknown: diag(2571, ts.DiagnosticCategory.Error, "Object_is_of_type_unknown_2571", "Object is of type 'unknown'."),
8058         Rest_signatures_are_incompatible: diag(2572, ts.DiagnosticCategory.Error, "Rest_signatures_are_incompatible_2572", "Rest signatures are incompatible."),
8059         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."),
8060         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."),
8061         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."),
8062         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}'."),
8063         Return_type_annotation_circularly_references_itself: diag(2577, ts.DiagnosticCategory.Error, "Return_type_annotation_circularly_references_itself_2577", "Return type annotation circularly references itself."),
8064         Unused_ts_expect_error_directive: diag(2578, ts.DiagnosticCategory.Error, "Unused_ts_expect_error_directive_2578", "Unused '@ts-expect-error' directive."),
8065         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode: diag(2580, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashno_2580", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node`."),
8066         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery: diag(2581, ts.DiagnosticCategory.Error, "Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slash_2581", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery`."),
8067         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_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_save_dev_type_2582", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha`."),
8068         Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_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 '{1}' or later."),
8069         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'."),
8070         _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."),
8071         Enum_type_0_circularly_references_itself: diag(2586, ts.DiagnosticCategory.Error, "Enum_type_0_circularly_references_itself_2586", "Enum type '{0}' circularly references itself."),
8072         JSDoc_type_0_circularly_references_itself: diag(2587, ts.DiagnosticCategory.Error, "JSDoc_type_0_circularly_references_itself_2587", "JSDoc type '{0}' circularly references itself."),
8073         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."),
8074         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."),
8075         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."),
8076         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_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_save_dev_types_Slashno_2591", "Cannot find name '{0}'. Do you need to install type definitions for node? Try `npm i --save-dev @types/node` and then add `node` to the types field in your tsconfig."),
8077         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_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_save_dev_types_Slash_2592", "Cannot find name '{0}'. Do you need to install type definitions for jQuery? Try `npm i --save-dev @types/jquery` and then add `jquery` to the types field in your tsconfig."),
8078         Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_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_save_dev_type_2593", "Cannot find name '{0}'. Do you need to install type definitions for a test runner? Try `npm i --save-dev @types/jest` or `npm i --save-dev @types/mocha` and then add `jest` or `mocha` to the types field in your tsconfig."),
8079         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."),
8080         _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."),
8081         _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."),
8082         _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."),
8083         _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."),
8084         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."),
8085         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."),
8086         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."),
8087         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}'."),
8088         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."),
8089         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."),
8090         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."),
8091         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."),
8092         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."),
8093         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."),
8094         _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."),
8095         _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."),
8096         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."),
8097         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?"),
8098         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?"),
8099         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}'."),
8100         _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."),
8101         _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."),
8102         Source_has_0_element_s_but_target_requires_1: diag(2618, ts.DiagnosticCategory.Error, "Source_has_0_element_s_but_target_requires_1_2618", "Source has {0} element(s) but target requires {1}."),
8103         Source_has_0_element_s_but_target_allows_only_1: diag(2619, ts.DiagnosticCategory.Error, "Source_has_0_element_s_but_target_allows_only_1_2619", "Source has {0} element(s) but target allows only {1}."),
8104         Target_requires_0_element_s_but_source_may_have_fewer: diag(2620, ts.DiagnosticCategory.Error, "Target_requires_0_element_s_but_source_may_have_fewer_2620", "Target requires {0} element(s) but source may have fewer."),
8105         Target_allows_only_0_element_s_but_source_may_have_more: diag(2621, ts.DiagnosticCategory.Error, "Target_allows_only_0_element_s_but_source_may_have_more_2621", "Target allows only {0} element(s) but source may have more."),
8106         Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other: diag(2622, ts.DiagnosticCategory.Error, "Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other_2622", "Element at index {0} is variadic in one type but not in the other."),
8107         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."),
8108         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."),
8109         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."),
8110         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}'."),
8111         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."),
8112         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."),
8113         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."),
8114         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}'."),
8115         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."),
8116         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."),
8117         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."),
8118         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}'?"),
8119         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}'?"),
8120         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."),
8121         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."),
8122         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."),
8123         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."),
8124         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."),
8125         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."),
8126         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."),
8127         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."),
8128         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."),
8129         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."),
8130         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."),
8131         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."),
8132         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."),
8133         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."),
8134         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}'."),
8135         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'."),
8136         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."),
8137         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."),
8138         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."),
8139         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."),
8140         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}'."),
8141         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."),
8142         _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."),
8143         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."),
8144         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}'."),
8145         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'?"),
8146         _0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0: diag(2690, ts.DiagnosticCategory.Error, "_0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0_2690", "'{0}' only refers to a type, but is being used as a value here. Did you mean to use '{1} in {0}'?"),
8147         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."),
8148         _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."),
8149         _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."),
8150         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}'."),
8151         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),
8152         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?"),
8153         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."),
8154         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."),
8155         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}'."),
8156         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."),
8157         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."),
8158         _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."),
8159         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."),
8160         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."),
8161         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."),
8162         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."),
8163         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."),
8164         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."),
8165         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."),
8166         _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."),
8167         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."),
8168         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."),
8169         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}\"]'?"),
8170         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."),
8171         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."),
8172         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."),
8173         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}'."),
8174         Duplicate_property_0: diag(2718, ts.DiagnosticCategory.Error, "Duplicate_property_0_2718", "Duplicate property '{0}'."),
8175         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."),
8176         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?"),
8177         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'."),
8178         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'."),
8179         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'."),
8180         _0_has_no_exported_member_named_1_Did_you_mean_2: diag(2724, ts.DiagnosticCategory.Error, "_0_has_no_exported_member_named_1_Did_you_mean_2_2724", "'{0}' has no exported member named '{1}'. Did you mean '{2}'?"),
8181         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}."),
8182         Cannot_find_lib_definition_for_0: diag(2726, ts.DiagnosticCategory.Error, "Cannot_find_lib_definition_for_0_2726", "Cannot find lib definition for '{0}'."),
8183         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}'?"),
8184         _0_is_declared_here: diag(2728, ts.DiagnosticCategory.Message, "_0_is_declared_here_2728", "'{0}' is declared here."),
8185         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."),
8186         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."),
8187         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(...)'."),
8188         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."),
8189         Property_0_was_also_declared_here: diag(2733, ts.DiagnosticCategory.Error, "Property_0_was_also_declared_here_2733", "Property '{0}' was also declared here."),
8190         Are_you_missing_a_semicolon: diag(2734, ts.DiagnosticCategory.Error, "Are_you_missing_a_semicolon_2734", "Are you missing a semicolon?"),
8191         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}'?"),
8192         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}'."),
8193         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."),
8194         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."),
8195         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}"),
8196         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."),
8197         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}'."),
8198         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."),
8199         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."),
8200         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."),
8201         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."),
8202         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."),
8203         _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}'."),
8204         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."),
8205         _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}'?"),
8206         The_implementation_signature_is_declared_here: diag(2750, ts.DiagnosticCategory.Error, "The_implementation_signature_is_declared_here_2750", "The implementation signature is declared here."),
8207         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."),
8208         The_first_export_default_is_here: diag(2752, ts.DiagnosticCategory.Error, "The_first_export_default_is_here_2752", "The first export default is here."),
8209         Another_export_default_is_here: diag(2753, ts.DiagnosticCategory.Error, "Another_export_default_is_here_2753", "Another export default is here."),
8210         super_may_not_use_type_arguments: diag(2754, ts.DiagnosticCategory.Error, "super_may_not_use_type_arguments_2754", "'super' may not use type arguments."),
8211         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."),
8212         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."),
8213         Type_0_has_no_call_signatures: diag(2757, ts.DiagnosticCategory.Error, "Type_0_has_no_call_signatures_2757", "Type '{0}' has no call signatures."),
8214         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."),
8215         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."),
8216         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."),
8217         Type_0_has_no_construct_signatures: diag(2761, ts.DiagnosticCategory.Error, "Type_0_has_no_construct_signatures_2761", "Type '{0}' has no construct signatures."),
8218         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."),
8219         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}'."),
8220         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}'."),
8221         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}'."),
8222         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}'."),
8223         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."),
8224         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."),
8225         No_overload_matches_this_call: diag(2769, ts.DiagnosticCategory.Error, "No_overload_matches_this_call_2769", "No overload matches this call."),
8226         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."),
8227         The_last_overload_is_declared_here: diag(2771, ts.DiagnosticCategory.Error, "The_last_overload_is_declared_here_2771", "The last overload is declared here."),
8228         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."),
8229         Did_you_forget_to_use_await: diag(2773, ts.DiagnosticCategory.Error, "Did_you_forget_to_use_await_2773", "Did you forget to use 'await'?"),
8230         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?"),
8231         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."),
8232         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."),
8233         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."),
8234         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."),
8235         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."),
8236         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."),
8237         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."),
8238         _0_needs_an_explicit_type_annotation: diag(2782, ts.DiagnosticCategory.Message, "_0_needs_an_explicit_type_annotation_2782", "'{0}' needs an explicit type annotation."),
8239         _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."),
8240         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."),
8241         This_spread_always_overwrites_this_property: diag(2785, ts.DiagnosticCategory.Error, "This_spread_always_overwrites_this_property_2785", "This spread always overwrites this property."),
8242         _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."),
8243         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."),
8244         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."),
8245         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."),
8246         The_operand_of_a_delete_operator_must_be_optional: diag(2790, ts.DiagnosticCategory.Error, "The_operand_of_a_delete_operator_must_be_optional_2790", "The operand of a 'delete' operator must be optional."),
8247         Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later: diag(2791, ts.DiagnosticCategory.Error, "Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_lat_2791", "Exponentiation cannot be performed on 'bigint' values unless the 'target' option is set to 'es2016' or later."),
8248         Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option: diag(2792, ts.DiagnosticCategory.Error, "Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_th_2792", "Cannot find module '{0}'. Did you mean to set the 'moduleResolution' option to 'node', or to add aliases to the 'paths' option?"),
8249         The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_are_not_externally_visible: diag(2793, ts.DiagnosticCategory.Error, "The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_2793", "The call would have succeeded against this implementation, but implementation signatures of overloads are not externally visible."),
8250         Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise: diag(2794, ts.DiagnosticCategory.Error, "Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise_2794", "Expected {0} arguments, but got {1}. Did you forget to include 'void' in your type argument to 'Promise'?"),
8251         The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types: diag(2795, ts.DiagnosticCategory.Error, "The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types_2795", "The 'intrinsic' keyword can only be used to declare compiler provided intrinsic types."),
8252         It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked: diag(2796, ts.DiagnosticCategory.Error, "It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tag_2796", "It is likely that you are missing a comma to separate these two template expressions. They form a tagged template expression which cannot be invoked."),
8253         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}'."),
8254         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}'."),
8255         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}'."),
8256         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}'."),
8257         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}'."),
8258         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}'."),
8259         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}'."),
8260         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}'."),
8261         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}'."),
8262         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}'."),
8263         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}'."),
8264         extends_clause_of_exported_class_has_or_is_using_private_name_0: diag(4021, ts.DiagnosticCategory.Error, "extends_clause_of_exported_class_has_or_is_using_private_name_0_4021", "'extends' clause of exported class has or is using private name '{0}'."),
8265         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}'."),
8266         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."),
8267         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}'."),
8268         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}'."),
8269         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."),
8270         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}'."),
8271         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}'."),
8272         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."),
8273         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}'."),
8274         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}'."),
8275         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}'."),
8276         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}'."),
8277         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}'."),
8278         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}'."),
8279         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}'."),
8280         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}'."),
8281         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."),
8282         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}'."),
8283         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}'."),
8284         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."),
8285         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}'."),
8286         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}'."),
8287         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}'."),
8288         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}'."),
8289         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}'."),
8290         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}'."),
8291         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}'."),
8292         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}'."),
8293         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."),
8294         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}'."),
8295         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}'."),
8296         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."),
8297         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}'."),
8298         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}'."),
8299         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}'."),
8300         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}'."),
8301         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."),
8302         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}'."),
8303         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}'."),
8304         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."),
8305         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}'."),
8306         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}'."),
8307         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}'."),
8308         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}'."),
8309         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}'."),
8310         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}'."),
8311         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."),
8312         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}'."),
8313         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}'."),
8314         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."),
8315         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}'."),
8316         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}'."),
8317         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}'."),
8318         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}'."),
8319         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."),
8320         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}'."),
8321         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}'."),
8322         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}'."),
8323         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}'."),
8324         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}'."),
8325         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."),
8326         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}'."),
8327         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}'."),
8328         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."),
8329         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."),
8330         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}'."),
8331         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}'."),
8332         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."),
8333         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}'."),
8334         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}'."),
8335         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}'."),
8336         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}'."),
8337         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}'."),
8338         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}'."),
8339         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."),
8340         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}'."),
8341         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}'."),
8342         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."),
8343         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."),
8344         Tuple_type_arguments_circularly_reference_themselves: diag(4110, ts.DiagnosticCategory.Error, "Tuple_type_arguments_circularly_reference_themselves_4110", "Tuple type arguments circularly reference themselves."),
8345         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."),
8346         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."),
8347         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}'."),
8348         Cannot_read_file_0_Colon_1: diag(5012, ts.DiagnosticCategory.Error, "Cannot_read_file_0_Colon_1_5012", "Cannot read file '{0}': {1}."),
8349         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}."),
8350         Unknown_compiler_option_0: diag(5023, ts.DiagnosticCategory.Error, "Unknown_compiler_option_0_5023", "Unknown compiler option '{0}'."),
8351         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}."),
8352         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}'?"),
8353         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}."),
8354         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."),
8355         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."),
8356         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'."),
8357         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."),
8358         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}'."),
8359         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}'."),
8360         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}'."),
8361         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."),
8362         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."),
8363         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}'."),
8364         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}'."),
8365         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."),
8366         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."),
8367         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."),
8368         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."),
8369         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}'."),
8370         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}'."),
8371         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."),
8372         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."),
8373         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."),
8374         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}'."),
8375         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."),
8376         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'."),
8377         Unknown_build_option_0: diag(5072, ts.DiagnosticCategory.Error, "Unknown_build_option_0_5072", "Unknown build option '{0}'."),
8378         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}."),
8379         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."),
8380         _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}'."),
8381         _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."),
8382         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}'?"),
8383         Unknown_watch_option_0: diag(5078, ts.DiagnosticCategory.Error, "Unknown_watch_option_0_5078", "Unknown watch option '{0}'."),
8384         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}'?"),
8385         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}."),
8386         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}."),
8387         _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}'."),
8388         Cannot_read_file_0: diag(5083, ts.DiagnosticCategory.Error, "Cannot_read_file_0_5083", "Cannot read file '{0}'."),
8389         Tuple_members_must_all_have_names_or_all_not_have_names: diag(5084, ts.DiagnosticCategory.Error, "Tuple_members_must_all_have_names_or_all_not_have_names_5084", "Tuple members must all have names or all not have names."),
8390         A_tuple_member_cannot_be_both_optional_and_rest: diag(5085, ts.DiagnosticCategory.Error, "A_tuple_member_cannot_be_both_optional_and_rest_5085", "A tuple member cannot be both optional and rest."),
8391         A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type: diag(5086, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_c_5086", "A labeled tuple element is declared as optional with a question mark after the name and before the colon, rather than after the type."),
8392         A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type: diag(5087, ts.DiagnosticCategory.Error, "A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type_5087", "A labeled tuple element is declared as rest with a `...` before the name, rather than before the type."),
8393         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."),
8394         Option_0_cannot_be_specified_when_option_jsx_is_1: diag(5089, ts.DiagnosticCategory.Error, "Option_0_cannot_be_specified_when_option_jsx_is_1_5089", "Option '{0}' cannot be specified when option 'jsx' is '{1}'."),
8395         Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash: diag(5090, ts.DiagnosticCategory.Error, "Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash_5090", "Non-relative paths are not allowed when 'baseUrl' is not set. Did you forget a leading './'?"),
8396         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."),
8397         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."),
8398         Generates_corresponding_d_ts_file: diag(6002, ts.DiagnosticCategory.Message, "Generates_corresponding_d_ts_file_6002", "Generates corresponding '.d.ts' file."),
8399         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."),
8400         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."),
8401         Watch_input_files: diag(6005, ts.DiagnosticCategory.Message, "Watch_input_files_6005", "Watch input files."),
8402         Redirect_output_structure_to_the_directory: diag(6006, ts.DiagnosticCategory.Message, "Redirect_output_structure_to_the_directory_6006", "Redirect output structure to the directory."),
8403         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."),
8404         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."),
8405         Do_not_emit_comments_to_output: diag(6009, ts.DiagnosticCategory.Message, "Do_not_emit_comments_to_output_6009", "Do not emit comments to output."),
8406         Do_not_emit_outputs: diag(6010, ts.DiagnosticCategory.Message, "Do_not_emit_outputs_6010", "Do not emit outputs."),
8407         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."),
8408         Skip_type_checking_of_declaration_files: diag(6012, ts.DiagnosticCategory.Message, "Skip_type_checking_of_declaration_files_6012", "Skip type checking of declaration files."),
8409         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."),
8410         Only_emit_d_ts_declaration_files: diag(6014, ts.DiagnosticCategory.Message, "Only_emit_d_ts_declaration_files_6014", "Only emit '.d.ts' declaration files."),
8411         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'."),
8412         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'."),
8413         Print_this_message: diag(6017, ts.DiagnosticCategory.Message, "Print_this_message_6017", "Print this message."),
8414         Print_the_compiler_s_version: diag(6019, ts.DiagnosticCategory.Message, "Print_the_compiler_s_version_6019", "Print the compiler's version."),
8415         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'."),
8416         Syntax_Colon_0: diag(6023, ts.DiagnosticCategory.Message, "Syntax_Colon_0_6023", "Syntax: {0}"),
8417         options: diag(6024, ts.DiagnosticCategory.Message, "options_6024", "options"),
8418         file: diag(6025, ts.DiagnosticCategory.Message, "file_6025", "file"),
8419         Examples_Colon_0: diag(6026, ts.DiagnosticCategory.Message, "Examples_Colon_0_6026", "Examples: {0}"),
8420         Options_Colon: diag(6027, ts.DiagnosticCategory.Message, "Options_Colon_6027", "Options:"),
8421         Version_0: diag(6029, ts.DiagnosticCategory.Message, "Version_0_6029", "Version {0}"),
8422         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."),
8423         Starting_compilation_in_watch_mode: diag(6031, ts.DiagnosticCategory.Message, "Starting_compilation_in_watch_mode_6031", "Starting compilation in watch mode..."),
8424         File_change_detected_Starting_incremental_compilation: diag(6032, ts.DiagnosticCategory.Message, "File_change_detected_Starting_incremental_compilation_6032", "File change detected. Starting incremental compilation..."),
8425         KIND: diag(6034, ts.DiagnosticCategory.Message, "KIND_6034", "KIND"),
8426         FILE: diag(6035, ts.DiagnosticCategory.Message, "FILE_6035", "FILE"),
8427         VERSION: diag(6036, ts.DiagnosticCategory.Message, "VERSION_6036", "VERSION"),
8428         LOCATION: diag(6037, ts.DiagnosticCategory.Message, "LOCATION_6037", "LOCATION"),
8429         DIRECTORY: diag(6038, ts.DiagnosticCategory.Message, "DIRECTORY_6038", "DIRECTORY"),
8430         STRATEGY: diag(6039, ts.DiagnosticCategory.Message, "STRATEGY_6039", "STRATEGY"),
8431         FILE_OR_DIRECTORY: diag(6040, ts.DiagnosticCategory.Message, "FILE_OR_DIRECTORY_6040", "FILE OR DIRECTORY"),
8432         Generates_corresponding_map_file: diag(6043, ts.DiagnosticCategory.Message, "Generates_corresponding_map_file_6043", "Generates corresponding '.map' file."),
8433         Compiler_option_0_expects_an_argument: diag(6044, ts.DiagnosticCategory.Error, "Compiler_option_0_expects_an_argument_6044", "Compiler option '{0}' expects an argument."),
8434         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}'."),
8435         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}."),
8436         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}'."),
8437         Unsupported_locale_0: diag(6049, ts.DiagnosticCategory.Error, "Unsupported_locale_0_6049", "Unsupported locale '{0}'."),
8438         Unable_to_open_file_0: diag(6050, ts.DiagnosticCategory.Error, "Unable_to_open_file_0_6050", "Unable to open file '{0}'."),
8439         Corrupted_locale_file_0: diag(6051, ts.DiagnosticCategory.Error, "Corrupted_locale_file_0_6051", "Corrupted locale file {0}."),
8440         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."),
8441         File_0_not_found: diag(6053, ts.DiagnosticCategory.Error, "File_0_not_found_6053", "File '{0}' not found."),
8442         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}."),
8443         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."),
8444         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."),
8445         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."),
8446         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."),
8447         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)."),
8448         NEWLINE: diag(6061, ts.DiagnosticCategory.Message, "NEWLINE_6061", "NEWLINE"),
8449         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."),
8450         Enables_experimental_support_for_ES7_decorators: diag(6065, ts.DiagnosticCategory.Message, "Enables_experimental_support_for_ES7_decorators_6065", "Enables experimental support for ES7 decorators."),
8451         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."),
8452         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."),
8453         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)."),
8454         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."),
8455         Successfully_created_a_tsconfig_json_file: diag(6071, ts.DiagnosticCategory.Message, "Successfully_created_a_tsconfig_json_file_6071", "Successfully created a tsconfig.json file."),
8456         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."),
8457         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)."),
8458         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."),
8459         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."),
8460         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."),
8461         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."),
8462         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."),
8463         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."),
8464         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'."),
8465         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."),
8466         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}."),
8467         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."),
8468         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"),
8469         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."),
8470         Resolving_module_0_from_1: diag(6086, ts.DiagnosticCategory.Message, "Resolving_module_0_from_1_6086", "======== Resolving module '{0}' from '{1}'. ========"),
8471         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}'."),
8472         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}'."),
8473         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}'. ========"),
8474         Module_name_0_was_not_resolved: diag(6090, ts.DiagnosticCategory.Message, "Module_name_0_was_not_resolved_6090", "======== Module name '{0}' was not resolved. ========"),
8475         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}'."),
8476         Module_name_0_matched_pattern_1: diag(6092, ts.DiagnosticCategory.Message, "Module_name_0_matched_pattern_1_6092", "Module name '{0}', matched pattern '{1}'."),
8477         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}'."),
8478         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}'."),
8479         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}'."),
8480         File_0_does_not_exist: diag(6096, ts.DiagnosticCategory.Message, "File_0_does_not_exist_6096", "File '{0}' does not exist."),
8481         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."),
8482         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}'."),
8483         Found_package_json_at_0: diag(6099, ts.DiagnosticCategory.Message, "Found_package_json_at_0_6099", "Found 'package.json' at '{0}'."),
8484         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."),
8485         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}'."),
8486         Allow_javascript_files_to_be_compiled: diag(6102, ts.DiagnosticCategory.Message, "Allow_javascript_files_to_be_compiled_6102", "Allow javascript files to be compiled."),
8487         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."),
8488         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}'."),
8489         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}'."),
8490         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}'."),
8491         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}'."),
8492         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}'."),
8493         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}'."),
8494         Trying_other_entries_in_rootDirs: diag(6110, ts.DiagnosticCategory.Message, "Trying_other_entries_in_rootDirs_6110", "Trying other entries in 'rootDirs'."),
8495         Module_resolution_using_rootDirs_has_failed: diag(6111, ts.DiagnosticCategory.Message, "Module_resolution_using_rootDirs_has_failed_6111", "Module resolution using 'rootDirs' has failed."),
8496         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."),
8497         Enable_strict_null_checks: diag(6113, ts.DiagnosticCategory.Message, "Enable_strict_null_checks_6113", "Enable strict null checks."),
8498         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'?"),
8499         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."),
8500         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}'. ========"),
8501         Resolving_using_primary_search_paths: diag(6117, ts.DiagnosticCategory.Message, "Resolving_using_primary_search_paths_6117", "Resolving using primary search paths..."),
8502         Resolving_from_node_modules_folder: diag(6118, ts.DiagnosticCategory.Message, "Resolving_from_node_modules_folder_6118", "Resolving from node_modules folder..."),
8503         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}. ========"),
8504         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. ========"),
8505         Resolving_with_primary_search_path_0: diag(6121, ts.DiagnosticCategory.Message, "Resolving_with_primary_search_path_0_6121", "Resolving with primary search path '{0}'."),
8506         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."),
8507         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. ========"),
8508         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."),
8509         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}'."),
8510         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."),
8511         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}'. ========"),
8512         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. ========"),
8513         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}'."),
8514         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'."),
8515         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."),
8516         _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),
8517         Report_errors_on_unused_locals: diag(6134, ts.DiagnosticCategory.Message, "Report_errors_on_unused_locals_6134", "Report errors on unused locals."),
8518         Report_errors_on_unused_parameters: diag(6135, ts.DiagnosticCategory.Message, "Report_errors_on_unused_parameters_6135", "Report errors on unused parameters."),
8519         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."),
8520         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}'."),
8521         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),
8522         Import_emit_helpers_from_tslib: diag(6139, ts.DiagnosticCategory.Message, "Import_emit_helpers_from_tslib_6139", "Import emit helpers from 'tslib'."),
8523         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}'."),
8524         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."),
8525         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."),
8526         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}'."),
8527         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."),
8528         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'."),
8529         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}'."),
8530         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."),
8531         Show_diagnostic_information: diag(6149, ts.DiagnosticCategory.Message, "Show_diagnostic_information_6149", "Show diagnostic information."),
8532         Show_verbose_diagnostic_information: diag(6150, ts.DiagnosticCategory.Message, "Show_verbose_diagnostic_information_6150", "Show verbose diagnostic information."),
8533         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."),
8534         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."),
8535         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')."),
8536         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."),
8537         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."),
8538         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')"),
8539         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."),
8540         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)."),
8541         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."),
8542         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."),
8543         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."),
8544         Disable_size_limitations_on_JavaScript_projects: diag(6162, ts.DiagnosticCategory.Message, "Disable_size_limitations_on_JavaScript_projects_6162", "Disable size limitations on JavaScript projects."),
8545         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."),
8546         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."),
8547         Do_not_truncate_error_messages: diag(6165, ts.DiagnosticCategory.Message, "Do_not_truncate_error_messages_6165", "Do not truncate error messages."),
8548         Output_directory_for_generated_declaration_files: diag(6166, ts.DiagnosticCategory.Message, "Output_directory_for_generated_declaration_files_6166", "Output directory for generated declaration files."),
8549         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'."),
8550         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."),
8551         Show_all_compiler_options: diag(6169, ts.DiagnosticCategory.Message, "Show_all_compiler_options_6169", "Show all compiler options."),
8552         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"),
8553         Command_line_Options: diag(6171, ts.DiagnosticCategory.Message, "Command_line_Options_6171", "Command-line Options"),
8554         Basic_Options: diag(6172, ts.DiagnosticCategory.Message, "Basic_Options_6172", "Basic Options"),
8555         Strict_Type_Checking_Options: diag(6173, ts.DiagnosticCategory.Message, "Strict_Type_Checking_Options_6173", "Strict Type-Checking Options"),
8556         Module_Resolution_Options: diag(6174, ts.DiagnosticCategory.Message, "Module_Resolution_Options_6174", "Module Resolution Options"),
8557         Source_Map_Options: diag(6175, ts.DiagnosticCategory.Message, "Source_Map_Options_6175", "Source Map Options"),
8558         Additional_Checks: diag(6176, ts.DiagnosticCategory.Message, "Additional_Checks_6176", "Additional Checks"),
8559         Experimental_Options: diag(6177, ts.DiagnosticCategory.Message, "Experimental_Options_6177", "Experimental Options"),
8560         Advanced_Options: diag(6178, ts.DiagnosticCategory.Message, "Advanced_Options_6178", "Advanced Options"),
8561         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'."),
8562         Enable_all_strict_type_checking_options: diag(6180, ts.DiagnosticCategory.Message, "Enable_all_strict_type_checking_options_6180", "Enable all strict type-checking options."),
8563         List_of_language_service_plugins: diag(6181, ts.DiagnosticCategory.Message, "List_of_language_service_plugins_6181", "List of language service plugins."),
8564         Scoped_package_detected_looking_in_0: diag(6182, ts.DiagnosticCategory.Message, "Scoped_package_detected_looking_in_0_6182", "Scoped package detected, looking in '{0}'"),
8565         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."),
8566         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."),
8567         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."),
8568         Enable_strict_checking_of_function_types: diag(6186, ts.DiagnosticCategory.Message, "Enable_strict_checking_of_function_types_6186", "Enable strict checking of function types."),
8569         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."),
8570         Numeric_separators_are_not_allowed_here: diag(6188, ts.DiagnosticCategory.Error, "Numeric_separators_are_not_allowed_here_6188", "Numeric separators are not allowed here."),
8571         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."),
8572         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."),
8573         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),
8574         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."),
8575         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."),
8576         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)."),
8577         _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),
8578         Include_modules_imported_with_json_extension: diag(6197, ts.DiagnosticCategory.Message, "Include_modules_imported_with_json_extension_6197", "Include modules imported with '.json' extension"),
8579         All_destructured_elements_are_unused: diag(6198, ts.DiagnosticCategory.Error, "All_destructured_elements_are_unused_6198", "All destructured elements are unused.", /*reportsUnnecessary*/ true),
8580         All_variables_are_unused: diag(6199, ts.DiagnosticCategory.Error, "All_variables_are_unused_6199", "All variables are unused.", /*reportsUnnecessary*/ true),
8581         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}"),
8582         Conflicts_are_in_this_file: diag(6201, ts.DiagnosticCategory.Message, "Conflicts_are_in_this_file_6201", "Conflicts are in this file."),
8583         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}"),
8584         _0_was_also_declared_here: diag(6203, ts.DiagnosticCategory.Message, "_0_was_also_declared_here_6203", "'{0}' was also declared here."),
8585         and_here: diag(6204, ts.DiagnosticCategory.Message, "and_here_6204", "and here."),
8586         All_type_parameters_are_unused: diag(6205, ts.DiagnosticCategory.Error, "All_type_parameters_are_unused_6205", "All type parameters are unused."),
8587         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."),
8588         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}'."),
8589         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}'."),
8590         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."),
8591         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."),
8592         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."),
8593         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?"),
8594         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?"),
8595         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."),
8596         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}'."),
8597         Found_1_error: diag(6216, ts.DiagnosticCategory.Message, "Found_1_error_6216", "Found 1 error."),
8598         Found_0_errors: diag(6217, ts.DiagnosticCategory.Message, "Found_0_errors_6217", "Found {0} errors."),
8599         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}'. ========"),
8600         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}. ========"),
8601         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."),
8602         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."),
8603         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."),
8604         Generates_a_CPU_profile: diag(6223, ts.DiagnosticCategory.Message, "Generates_a_CPU_profile_6223", "Generates a CPU profile."),
8605         Disable_solution_searching_for_this_project: diag(6224, ts.DiagnosticCategory.Message, "Disable_solution_searching_for_this_project_6224", "Disable solution searching for this project."),
8606         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'."),
8607         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'."),
8608         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'."),
8609         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."),
8610         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}'."),
8611         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."),
8612         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}."),
8613         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."),
8614         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."),
8615         This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without: diag(6234, ts.DiagnosticCategory.Error, "This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without_6234", "This expression is not callable because it is a 'get' accessor. Did you mean to use it without '()'?"),
8616         Disable_loading_referenced_projects: diag(6235, ts.DiagnosticCategory.Message, "Disable_loading_referenced_projects_6235", "Disable loading referenced projects."),
8617         Arguments_for_the_rest_parameter_0_were_not_provided: diag(6236, ts.DiagnosticCategory.Error, "Arguments_for_the_rest_parameter_0_were_not_provided_6236", "Arguments for the rest parameter '{0}' were not provided."),
8618         Generates_an_event_trace_and_a_list_of_types: diag(6237, ts.DiagnosticCategory.Message, "Generates_an_event_trace_and_a_list_of_types_6237", "Generates an event trace and a list of types."),
8619         Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react: diag(6238, ts.DiagnosticCategory.Error, "Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react_6238", "Specify the module specifier to be used to import the `jsx` and `jsxs` factory functions from. eg, react"),
8620         Projects_to_reference: diag(6300, ts.DiagnosticCategory.Message, "Projects_to_reference_6300", "Projects to reference"),
8621         Enable_project_compilation: diag(6302, ts.DiagnosticCategory.Message, "Enable_project_compilation_6302", "Enable project compilation"),
8622         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."),
8623         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}'."),
8624         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."),
8625         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."),
8626         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"),
8627         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"),
8628         Referenced_project_0_may_not_disable_emit: diag(6310, ts.DiagnosticCategory.Error, "Referenced_project_0_may_not_disable_emit_6310", "Referenced project '{0}' may not disable emit."),
8629         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}'"),
8630         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}'"),
8631         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"),
8632         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"),
8633         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"),
8634         Projects_in_this_build_Colon_0: diag(6355, ts.DiagnosticCategory.Message, "Projects_in_this_build_Colon_0_6355", "Projects in this build: {0}"),
8635         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}"),
8636         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}'"),
8637         Building_project_0: diag(6358, ts.DiagnosticCategory.Message, "Building_project_0_6358", "Building project '{0}'..."),
8638         Updating_output_timestamps_of_project_0: diag(6359, ts.DiagnosticCategory.Message, "Updating_output_timestamps_of_project_0_6359", "Updating output timestamps of project '{0}'..."),
8639         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"),
8640         Project_0_is_up_to_date: diag(6361, ts.DiagnosticCategory.Message, "Project_0_is_up_to_date_6361", "Project '{0}' is up to date"),
8641         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"),
8642         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"),
8643         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"),
8644         Delete_the_outputs_of_all_projects: diag(6365, ts.DiagnosticCategory.Message, "Delete_the_outputs_of_all_projects_6365", "Delete the outputs of all projects"),
8645         Enable_verbose_logging: diag(6366, ts.DiagnosticCategory.Message, "Enable_verbose_logging_6366", "Enable verbose logging"),
8646         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')"),
8647         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"),
8648         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."),
8649         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."),
8650         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}'..."),
8651         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"),
8652         Updating_output_of_project_0: diag(6373, ts.DiagnosticCategory.Message, "Updating_output_of_project_0_6373", "Updating output of project '{0}'..."),
8653         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}'"),
8654         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}'"),
8655         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}'"),
8656         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}'"),
8657         Enable_incremental_compilation: diag(6378, ts.DiagnosticCategory.Message, "Enable_incremental_compilation_6378", "Enable incremental compilation"),
8658         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."),
8659         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"),
8660         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}'"),
8661         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"),
8662         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"),
8663         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."),
8664         _0_is_deprecated: diag(6385, ts.DiagnosticCategory.Suggestion, "_0_is_deprecated_6385", "'{0}' is deprecated", /*reportsUnnecessary*/ undefined, /*elidedInCompatabilityPyramid*/ undefined, /*reportsDeprecated*/ true),
8665         Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_native_implementation_of_the_Web_Performance_API_could_not_be_found: diag(6386, ts.DiagnosticCategory.Message, "Performance_timings_for_diagnostics_or_extendedDiagnostics_are_not_available_in_this_session_A_nativ_6386", "Performance timings for '--diagnostics' or '--extendedDiagnostics' are not available in this session. A native implementation of the Web Performance API could not be found."),
8666         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}'"),
8667         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."),
8668         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."),
8669         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."),
8670         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?"),
8671         Include_undefined_in_index_signature_results: diag(6800, ts.DiagnosticCategory.Message, "Include_undefined_in_index_signature_results_6800", "Include 'undefined' in index signature results"),
8672         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."),
8673         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."),
8674         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."),
8675         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."),
8676         _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."),
8677         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."),
8678         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."),
8679         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."),
8680         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'."),
8681         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."),
8682         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."),
8683         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."),
8684         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."),
8685         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."),
8686         _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."),
8687         _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."),
8688         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."),
8689         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."),
8690         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."),
8691         Unreachable_code_detected: diag(7027, ts.DiagnosticCategory.Error, "Unreachable_code_detected_7027", "Unreachable code detected.", /*reportsUnnecessary*/ true),
8692         Unused_label: diag(7028, ts.DiagnosticCategory.Error, "Unused_label_7028", "Unused label.", /*reportsUnnecessary*/ true),
8693         Fallthrough_case_in_switch: diag(7029, ts.DiagnosticCategory.Error, "Fallthrough_case_in_switch_7029", "Fallthrough case in switch."),
8694         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."),
8695         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."),
8696         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."),
8697         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."),
8698         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."),
8699         Try_npm_i_save_dev_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_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare__7035", "Try `npm i --save-dev @types/{1}` if it exists or add a new declaration (.d.ts) file containing `declare module '{0}';`"),
8700         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}'."),
8701         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'."),
8702         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."),
8703         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."),
8704         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}`"),
8705         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'."),
8706         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."),
8707         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."),
8708         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."),
8709         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."),
8710         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."),
8711         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."),
8712         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."),
8713         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."),
8714         _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."),
8715         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}'?"),
8716         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}'?"),
8717         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}'."),
8718         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}'."),
8719         _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."),
8720         The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed: diag(7056, ts.DiagnosticCategory.Error, "The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_ty_7056", "The inferred type of this node exceeds the maximum length the compiler will serialize. An explicit type annotation is needed."),
8721         You_cannot_rename_this_element: diag(8000, ts.DiagnosticCategory.Error, "You_cannot_rename_this_element_8000", "You cannot rename this element."),
8722         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."),
8723         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."),
8724         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."),
8725         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."),
8726         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."),
8727         _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."),
8728         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."),
8729         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."),
8730         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."),
8731         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."),
8732         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."),
8733         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."),
8734         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."),
8735         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}'."),
8736         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}'."),
8737         Report_errors_in_js_files: diag(8019, ts.DiagnosticCategory.Message, "Report_errors_in_js_files_8019", "Report errors in .js files."),
8738         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."),
8739         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."),
8740         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."),
8741         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."),
8742         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."),
8743         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."),
8744         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."),
8745         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."),
8746         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."),
8747         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."),
8748         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."),
8749         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."),
8750         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}'."),
8751         A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags: diag(8033, ts.DiagnosticCategory.Error, "A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags_8033", "A JSDoc '@typedef' comment may not contain multiple '@type' tags."),
8752         The_tag_was_first_specified_here: diag(8034, ts.DiagnosticCategory.Error, "The_tag_was_first_specified_here_8034", "The tag was first specified here."),
8753         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."),
8754         class_expressions_are_not_currently_supported: diag(9003, ts.DiagnosticCategory.Error, "class_expressions_are_not_currently_supported_9003", "'class' expressions are not currently supported."),
8755         Language_service_is_disabled: diag(9004, ts.DiagnosticCategory.Error, "Language_service_is_disabled_9004", "Language service is disabled."),
8756         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."),
8757         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."),
8758         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'."),
8759         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."),
8760         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}'."),
8761         JSX_attribute_expected: diag(17003, ts.DiagnosticCategory.Error, "JSX_attribute_expected_17003", "JSX attribute expected."),
8762         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."),
8763         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'."),
8764         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."),
8765         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."),
8766         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."),
8767         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."),
8768         Unknown_type_acquisition_option_0: diag(17010, ts.DiagnosticCategory.Error, "Unknown_type_acquisition_option_0_17010", "Unknown type acquisition option '{0}'."),
8769         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."),
8770         _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}'?"),
8771         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."),
8772         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."),
8773         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."),
8774         The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option: diag(17016, ts.DiagnosticCategory.Error, "The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_com_17016", "The 'jsxFragmentFactory' compiler option must be provided to use JSX fragments with the 'jsxFactory' compiler option."),
8775         An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments: diag(17017, ts.DiagnosticCategory.Error, "An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments_17017", "An @jsxFrag pragma is required when using an @jsx pragma with JSX fragments."),
8776         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}'?"),
8777         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}"),
8778         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."),
8779         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."),
8780         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}'."),
8781         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."),
8782         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."),
8783         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."),
8784         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."),
8785         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."),
8786         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."),
8787         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."),
8788         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."),
8789         Add_missing_super_call: diag(90001, ts.DiagnosticCategory.Message, "Add_missing_super_call_90001", "Add missing 'super()' call"),
8790         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"),
8791         Change_extends_to_implements: diag(90003, ts.DiagnosticCategory.Message, "Change_extends_to_implements_90003", "Change 'extends' to 'implements'"),
8792         Remove_unused_declaration_for_Colon_0: diag(90004, ts.DiagnosticCategory.Message, "Remove_unused_declaration_for_Colon_0_90004", "Remove unused declaration for: '{0}'"),
8793         Remove_import_from_0: diag(90005, ts.DiagnosticCategory.Message, "Remove_import_from_0_90005", "Remove import from '{0}'"),
8794         Implement_interface_0: diag(90006, ts.DiagnosticCategory.Message, "Implement_interface_0_90006", "Implement interface '{0}'"),
8795         Implement_inherited_abstract_class: diag(90007, ts.DiagnosticCategory.Message, "Implement_inherited_abstract_class_90007", "Implement inherited abstract class"),
8796         Add_0_to_unresolved_variable: diag(90008, ts.DiagnosticCategory.Message, "Add_0_to_unresolved_variable_90008", "Add '{0}.' to unresolved variable"),
8797         Remove_variable_statement: diag(90010, ts.DiagnosticCategory.Message, "Remove_variable_statement_90010", "Remove variable statement"),
8798         Remove_template_tag: diag(90011, ts.DiagnosticCategory.Message, "Remove_template_tag_90011", "Remove template tag"),
8799         Remove_type_parameters: diag(90012, ts.DiagnosticCategory.Message, "Remove_type_parameters_90012", "Remove type parameters"),
8800         Import_0_from_module_1: diag(90013, ts.DiagnosticCategory.Message, "Import_0_from_module_1_90013", "Import '{0}' from module \"{1}\""),
8801         Change_0_to_1: diag(90014, ts.DiagnosticCategory.Message, "Change_0_to_1_90014", "Change '{0}' to '{1}'"),
8802         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}\""),
8803         Declare_property_0: diag(90016, ts.DiagnosticCategory.Message, "Declare_property_0_90016", "Declare property '{0}'"),
8804         Add_index_signature_for_property_0: diag(90017, ts.DiagnosticCategory.Message, "Add_index_signature_for_property_0_90017", "Add index signature for property '{0}'"),
8805         Disable_checking_for_this_file: diag(90018, ts.DiagnosticCategory.Message, "Disable_checking_for_this_file_90018", "Disable checking for this file"),
8806         Ignore_this_error_message: diag(90019, ts.DiagnosticCategory.Message, "Ignore_this_error_message_90019", "Ignore this error message"),
8807         Initialize_property_0_in_the_constructor: diag(90020, ts.DiagnosticCategory.Message, "Initialize_property_0_in_the_constructor_90020", "Initialize property '{0}' in the constructor"),
8808         Initialize_static_property_0: diag(90021, ts.DiagnosticCategory.Message, "Initialize_static_property_0_90021", "Initialize static property '{0}'"),
8809         Change_spelling_to_0: diag(90022, ts.DiagnosticCategory.Message, "Change_spelling_to_0_90022", "Change spelling to '{0}'"),
8810         Declare_method_0: diag(90023, ts.DiagnosticCategory.Message, "Declare_method_0_90023", "Declare method '{0}'"),
8811         Declare_static_method_0: diag(90024, ts.DiagnosticCategory.Message, "Declare_static_method_0_90024", "Declare static method '{0}'"),
8812         Prefix_0_with_an_underscore: diag(90025, ts.DiagnosticCategory.Message, "Prefix_0_with_an_underscore_90025", "Prefix '{0}' with an underscore"),
8813         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}'"),
8814         Declare_static_property_0: diag(90027, ts.DiagnosticCategory.Message, "Declare_static_property_0_90027", "Declare static property '{0}'"),
8815         Call_decorator_expression: diag(90028, ts.DiagnosticCategory.Message, "Call_decorator_expression_90028", "Call decorator expression"),
8816         Add_async_modifier_to_containing_function: diag(90029, ts.DiagnosticCategory.Message, "Add_async_modifier_to_containing_function_90029", "Add async modifier to containing function"),
8817         Replace_infer_0_with_unknown: diag(90030, ts.DiagnosticCategory.Message, "Replace_infer_0_with_unknown_90030", "Replace 'infer {0}' with 'unknown'"),
8818         Replace_all_unused_infer_with_unknown: diag(90031, ts.DiagnosticCategory.Message, "Replace_all_unused_infer_with_unknown_90031", "Replace all unused 'infer' with 'unknown'"),
8819         Import_default_0_from_module_1: diag(90032, ts.DiagnosticCategory.Message, "Import_default_0_from_module_1_90032", "Import default '{0}' from module \"{1}\""),
8820         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}\""),
8821         Add_parameter_name: diag(90034, ts.DiagnosticCategory.Message, "Add_parameter_name_90034", "Add parameter name"),
8822         Declare_private_property_0: diag(90035, ts.DiagnosticCategory.Message, "Declare_private_property_0_90035", "Declare private property '{0}'"),
8823         Replace_0_with_Promise_1: diag(90036, ts.DiagnosticCategory.Message, "Replace_0_with_Promise_1_90036", "Replace '{0}' with 'Promise<{1}>'"),
8824         Fix_all_incorrect_return_type_of_an_async_functions: diag(90037, ts.DiagnosticCategory.Message, "Fix_all_incorrect_return_type_of_an_async_functions_90037", "Fix all incorrect return type of an async functions"),
8825         Declare_private_method_0: diag(90038, ts.DiagnosticCategory.Message, "Declare_private_method_0_90038", "Declare private method '{0}'"),
8826         Remove_unused_destructuring_declaration: diag(90039, ts.DiagnosticCategory.Message, "Remove_unused_destructuring_declaration_90039", "Remove unused destructuring declaration"),
8827         Remove_unused_declarations_for_Colon_0: diag(90041, ts.DiagnosticCategory.Message, "Remove_unused_declarations_for_Colon_0_90041", "Remove unused declarations for: '{0}'"),
8828         Declare_a_private_field_named_0: diag(90053, ts.DiagnosticCategory.Message, "Declare_a_private_field_named_0_90053", "Declare a private field named '{0}'."),
8829         Convert_function_to_an_ES2015_class: diag(95001, ts.DiagnosticCategory.Message, "Convert_function_to_an_ES2015_class_95001", "Convert function to an ES2015 class"),
8830         Convert_function_0_to_class: diag(95002, ts.DiagnosticCategory.Message, "Convert_function_0_to_class_95002", "Convert function '{0}' to class"),
8831         Convert_0_to_1_in_0: diag(95003, ts.DiagnosticCategory.Message, "Convert_0_to_1_in_0_95003", "Convert '{0}' to '{1} in {0}'"),
8832         Extract_to_0_in_1: diag(95004, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_95004", "Extract to {0} in {1}"),
8833         Extract_function: diag(95005, ts.DiagnosticCategory.Message, "Extract_function_95005", "Extract function"),
8834         Extract_constant: diag(95006, ts.DiagnosticCategory.Message, "Extract_constant_95006", "Extract constant"),
8835         Extract_to_0_in_enclosing_scope: diag(95007, ts.DiagnosticCategory.Message, "Extract_to_0_in_enclosing_scope_95007", "Extract to {0} in enclosing scope"),
8836         Extract_to_0_in_1_scope: diag(95008, ts.DiagnosticCategory.Message, "Extract_to_0_in_1_scope_95008", "Extract to {0} in {1} scope"),
8837         Annotate_with_type_from_JSDoc: diag(95009, ts.DiagnosticCategory.Message, "Annotate_with_type_from_JSDoc_95009", "Annotate with type from JSDoc"),
8838         Annotate_with_types_from_JSDoc: diag(95010, ts.DiagnosticCategory.Message, "Annotate_with_types_from_JSDoc_95010", "Annotate with types from JSDoc"),
8839         Infer_type_of_0_from_usage: diag(95011, ts.DiagnosticCategory.Message, "Infer_type_of_0_from_usage_95011", "Infer type of '{0}' from usage"),
8840         Infer_parameter_types_from_usage: diag(95012, ts.DiagnosticCategory.Message, "Infer_parameter_types_from_usage_95012", "Infer parameter types from usage"),
8841         Convert_to_default_import: diag(95013, ts.DiagnosticCategory.Message, "Convert_to_default_import_95013", "Convert to default import"),
8842         Install_0: diag(95014, ts.DiagnosticCategory.Message, "Install_0_95014", "Install '{0}'"),
8843         Replace_import_with_0: diag(95015, ts.DiagnosticCategory.Message, "Replace_import_with_0_95015", "Replace import with '{0}'."),
8844         Use_synthetic_default_member: diag(95016, ts.DiagnosticCategory.Message, "Use_synthetic_default_member_95016", "Use synthetic 'default' member."),
8845         Convert_to_ES6_module: diag(95017, ts.DiagnosticCategory.Message, "Convert_to_ES6_module_95017", "Convert to ES6 module"),
8846         Add_undefined_type_to_property_0: diag(95018, ts.DiagnosticCategory.Message, "Add_undefined_type_to_property_0_95018", "Add 'undefined' type to property '{0}'"),
8847         Add_initializer_to_property_0: diag(95019, ts.DiagnosticCategory.Message, "Add_initializer_to_property_0_95019", "Add initializer to property '{0}'"),
8848         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}'"),
8849         Convert_all_type_literals_to_mapped_type: diag(95021, ts.DiagnosticCategory.Message, "Convert_all_type_literals_to_mapped_type_95021", "Convert all type literals to mapped type"),
8850         Add_all_missing_members: diag(95022, ts.DiagnosticCategory.Message, "Add_all_missing_members_95022", "Add all missing members"),
8851         Infer_all_types_from_usage: diag(95023, ts.DiagnosticCategory.Message, "Infer_all_types_from_usage_95023", "Infer all types from usage"),
8852         Delete_all_unused_declarations: diag(95024, ts.DiagnosticCategory.Message, "Delete_all_unused_declarations_95024", "Delete all unused declarations"),
8853         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"),
8854         Fix_all_detected_spelling_errors: diag(95026, ts.DiagnosticCategory.Message, "Fix_all_detected_spelling_errors_95026", "Fix all detected spelling errors"),
8855         Add_initializers_to_all_uninitialized_properties: diag(95027, ts.DiagnosticCategory.Message, "Add_initializers_to_all_uninitialized_properties_95027", "Add initializers to all uninitialized properties"),
8856         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"),
8857         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"),
8858         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"),
8859         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)"),
8860         Implement_all_unimplemented_interfaces: diag(95032, ts.DiagnosticCategory.Message, "Implement_all_unimplemented_interfaces_95032", "Implement all unimplemented interfaces"),
8861         Install_all_missing_types_packages: diag(95033, ts.DiagnosticCategory.Message, "Install_all_missing_types_packages_95033", "Install all missing types packages"),
8862         Rewrite_all_as_indexed_access_types: diag(95034, ts.DiagnosticCategory.Message, "Rewrite_all_as_indexed_access_types_95034", "Rewrite all as indexed access types"),
8863         Convert_all_to_default_imports: diag(95035, ts.DiagnosticCategory.Message, "Convert_all_to_default_imports_95035", "Convert all to default imports"),
8864         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"),
8865         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"),
8866         Change_all_extended_interfaces_to_implements: diag(95038, ts.DiagnosticCategory.Message, "Change_all_extended_interfaces_to_implements_95038", "Change all extended interfaces to 'implements'"),
8867         Add_all_missing_super_calls: diag(95039, ts.DiagnosticCategory.Message, "Add_all_missing_super_calls_95039", "Add all missing super calls"),
8868         Implement_all_inherited_abstract_classes: diag(95040, ts.DiagnosticCategory.Message, "Implement_all_inherited_abstract_classes_95040", "Implement all inherited abstract classes"),
8869         Add_all_missing_async_modifiers: diag(95041, ts.DiagnosticCategory.Message, "Add_all_missing_async_modifiers_95041", "Add all missing 'async' modifiers"),
8870         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"),
8871         Annotate_everything_with_types_from_JSDoc: diag(95043, ts.DiagnosticCategory.Message, "Annotate_everything_with_types_from_JSDoc_95043", "Annotate everything with types from JSDoc"),
8872         Add_to_all_uncalled_decorators: diag(95044, ts.DiagnosticCategory.Message, "Add_to_all_uncalled_decorators_95044", "Add '()' to all uncalled decorators"),
8873         Convert_all_constructor_functions_to_classes: diag(95045, ts.DiagnosticCategory.Message, "Convert_all_constructor_functions_to_classes_95045", "Convert all constructor functions to classes"),
8874         Generate_get_and_set_accessors: diag(95046, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_95046", "Generate 'get' and 'set' accessors"),
8875         Convert_require_to_import: diag(95047, ts.DiagnosticCategory.Message, "Convert_require_to_import_95047", "Convert 'require' to 'import'"),
8876         Convert_all_require_to_import: diag(95048, ts.DiagnosticCategory.Message, "Convert_all_require_to_import_95048", "Convert all 'require' to 'import'"),
8877         Move_to_a_new_file: diag(95049, ts.DiagnosticCategory.Message, "Move_to_a_new_file_95049", "Move to a new file"),
8878         Remove_unreachable_code: diag(95050, ts.DiagnosticCategory.Message, "Remove_unreachable_code_95050", "Remove unreachable code"),
8879         Remove_all_unreachable_code: diag(95051, ts.DiagnosticCategory.Message, "Remove_all_unreachable_code_95051", "Remove all unreachable code"),
8880         Add_missing_typeof: diag(95052, ts.DiagnosticCategory.Message, "Add_missing_typeof_95052", "Add missing 'typeof'"),
8881         Remove_unused_label: diag(95053, ts.DiagnosticCategory.Message, "Remove_unused_label_95053", "Remove unused label"),
8882         Remove_all_unused_labels: diag(95054, ts.DiagnosticCategory.Message, "Remove_all_unused_labels_95054", "Remove all unused labels"),
8883         Convert_0_to_mapped_object_type: diag(95055, ts.DiagnosticCategory.Message, "Convert_0_to_mapped_object_type_95055", "Convert '{0}' to mapped object type"),
8884         Convert_namespace_import_to_named_imports: diag(95056, ts.DiagnosticCategory.Message, "Convert_namespace_import_to_named_imports_95056", "Convert namespace import to named imports"),
8885         Convert_named_imports_to_namespace_import: diag(95057, ts.DiagnosticCategory.Message, "Convert_named_imports_to_namespace_import_95057", "Convert named imports to namespace import"),
8886         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"),
8887         Add_braces_to_arrow_function: diag(95059, ts.DiagnosticCategory.Message, "Add_braces_to_arrow_function_95059", "Add braces to arrow function"),
8888         Remove_braces_from_arrow_function: diag(95060, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_95060", "Remove braces from arrow function"),
8889         Convert_default_export_to_named_export: diag(95061, ts.DiagnosticCategory.Message, "Convert_default_export_to_named_export_95061", "Convert default export to named export"),
8890         Convert_named_export_to_default_export: diag(95062, ts.DiagnosticCategory.Message, "Convert_named_export_to_default_export_95062", "Convert named export to default export"),
8891         Add_missing_enum_member_0: diag(95063, ts.DiagnosticCategory.Message, "Add_missing_enum_member_0_95063", "Add missing enum member '{0}'"),
8892         Add_all_missing_imports: diag(95064, ts.DiagnosticCategory.Message, "Add_all_missing_imports_95064", "Add all missing imports"),
8893         Convert_to_async_function: diag(95065, ts.DiagnosticCategory.Message, "Convert_to_async_function_95065", "Convert to async function"),
8894         Convert_all_to_async_functions: diag(95066, ts.DiagnosticCategory.Message, "Convert_all_to_async_functions_95066", "Convert all to async functions"),
8895         Add_missing_call_parentheses: diag(95067, ts.DiagnosticCategory.Message, "Add_missing_call_parentheses_95067", "Add missing call parentheses"),
8896         Add_all_missing_call_parentheses: diag(95068, ts.DiagnosticCategory.Message, "Add_all_missing_call_parentheses_95068", "Add all missing call parentheses"),
8897         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"),
8898         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"),
8899         Add_missing_new_operator_to_call: diag(95071, ts.DiagnosticCategory.Message, "Add_missing_new_operator_to_call_95071", "Add missing 'new' operator to call"),
8900         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"),
8901         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"),
8902         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"),
8903         Convert_parameters_to_destructured_object: diag(95075, ts.DiagnosticCategory.Message, "Convert_parameters_to_destructured_object_95075", "Convert parameters to destructured object"),
8904         Allow_accessing_UMD_globals_from_modules: diag(95076, ts.DiagnosticCategory.Message, "Allow_accessing_UMD_globals_from_modules_95076", "Allow accessing UMD globals from modules."),
8905         Extract_type: diag(95077, ts.DiagnosticCategory.Message, "Extract_type_95077", "Extract type"),
8906         Extract_to_type_alias: diag(95078, ts.DiagnosticCategory.Message, "Extract_to_type_alias_95078", "Extract to type alias"),
8907         Extract_to_typedef: diag(95079, ts.DiagnosticCategory.Message, "Extract_to_typedef_95079", "Extract to typedef"),
8908         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"),
8909         Add_const_to_unresolved_variable: diag(95081, ts.DiagnosticCategory.Message, "Add_const_to_unresolved_variable_95081", "Add 'const' to unresolved variable"),
8910         Add_const_to_all_unresolved_variables: diag(95082, ts.DiagnosticCategory.Message, "Add_const_to_all_unresolved_variables_95082", "Add 'const' to all unresolved variables"),
8911         Add_await: diag(95083, ts.DiagnosticCategory.Message, "Add_await_95083", "Add 'await'"),
8912         Add_await_to_initializer_for_0: diag(95084, ts.DiagnosticCategory.Message, "Add_await_to_initializer_for_0_95084", "Add 'await' to initializer for '{0}'"),
8913         Fix_all_expressions_possibly_missing_await: diag(95085, ts.DiagnosticCategory.Message, "Fix_all_expressions_possibly_missing_await_95085", "Fix all expressions possibly missing 'await'"),
8914         Remove_unnecessary_await: diag(95086, ts.DiagnosticCategory.Message, "Remove_unnecessary_await_95086", "Remove unnecessary 'await'"),
8915         Remove_all_unnecessary_uses_of_await: diag(95087, ts.DiagnosticCategory.Message, "Remove_all_unnecessary_uses_of_await_95087", "Remove all unnecessary uses of 'await'"),
8916         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"),
8917         Add_await_to_initializers: diag(95089, ts.DiagnosticCategory.Message, "Add_await_to_initializers_95089", "Add 'await' to initializers"),
8918         Extract_to_interface: diag(95090, ts.DiagnosticCategory.Message, "Extract_to_interface_95090", "Extract to interface"),
8919         Convert_to_a_bigint_numeric_literal: diag(95091, ts.DiagnosticCategory.Message, "Convert_to_a_bigint_numeric_literal_95091", "Convert to a bigint numeric literal"),
8920         Convert_all_to_bigint_numeric_literals: diag(95092, ts.DiagnosticCategory.Message, "Convert_all_to_bigint_numeric_literals_95092", "Convert all to bigint numeric literals"),
8921         Convert_const_to_let: diag(95093, ts.DiagnosticCategory.Message, "Convert_const_to_let_95093", "Convert 'const' to 'let'"),
8922         Prefix_with_declare: diag(95094, ts.DiagnosticCategory.Message, "Prefix_with_declare_95094", "Prefix with 'declare'"),
8923         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'"),
8924         Convert_to_template_string: diag(95096, ts.DiagnosticCategory.Message, "Convert_to_template_string_95096", "Convert to template string"),
8925         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"),
8926         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}'"),
8927         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}'"),
8928         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"),
8929         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"),
8930         Add_class_tag: diag(95102, ts.DiagnosticCategory.Message, "Add_class_tag_95102", "Add '@class' tag"),
8931         Add_this_tag: diag(95103, ts.DiagnosticCategory.Message, "Add_this_tag_95103", "Add '@this' tag"),
8932         Add_this_parameter: diag(95104, ts.DiagnosticCategory.Message, "Add_this_parameter_95104", "Add 'this' parameter."),
8933         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"),
8934         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"),
8935         Fix_all_implicit_this_errors: diag(95107, ts.DiagnosticCategory.Message, "Fix_all_implicit_this_errors_95107", "Fix all implicit-'this' errors"),
8936         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"),
8937         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"),
8938         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"),
8939         Add_a_return_statement: diag(95111, ts.DiagnosticCategory.Message, "Add_a_return_statement_95111", "Add a return statement"),
8940         Remove_braces_from_arrow_function_body: diag(95112, ts.DiagnosticCategory.Message, "Remove_braces_from_arrow_function_body_95112", "Remove braces from arrow function body"),
8941         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"),
8942         Add_all_missing_return_statement: diag(95114, ts.DiagnosticCategory.Message, "Add_all_missing_return_statement_95114", "Add all missing return statement"),
8943         Remove_braces_from_all_arrow_function_bodies_with_relevant_issues: diag(95115, ts.DiagnosticCategory.Message, "Remove_braces_from_all_arrow_function_bodies_with_relevant_issues_95115", "Remove braces from all arrow function bodies with relevant issues"),
8944         Wrap_all_object_literal_with_parentheses: diag(95116, ts.DiagnosticCategory.Message, "Wrap_all_object_literal_with_parentheses_95116", "Wrap all object literal with parentheses"),
8945         Move_labeled_tuple_element_modifiers_to_labels: diag(95117, ts.DiagnosticCategory.Message, "Move_labeled_tuple_element_modifiers_to_labels_95117", "Move labeled tuple element modifiers to labels"),
8946         Convert_overload_list_to_single_signature: diag(95118, ts.DiagnosticCategory.Message, "Convert_overload_list_to_single_signature_95118", "Convert overload list to single signature"),
8947         Generate_get_and_set_accessors_for_all_overriding_properties: diag(95119, ts.DiagnosticCategory.Message, "Generate_get_and_set_accessors_for_all_overriding_properties_95119", "Generate 'get' and 'set' accessors for all overriding properties"),
8948         Wrap_in_JSX_fragment: diag(95120, ts.DiagnosticCategory.Message, "Wrap_in_JSX_fragment_95120", "Wrap in JSX fragment"),
8949         Wrap_all_unparented_JSX_in_JSX_fragment: diag(95121, ts.DiagnosticCategory.Message, "Wrap_all_unparented_JSX_in_JSX_fragment_95121", "Wrap all unparented JSX in JSX fragment"),
8950         Convert_arrow_function_or_function_expression: diag(95122, ts.DiagnosticCategory.Message, "Convert_arrow_function_or_function_expression_95122", "Convert arrow function or function expression"),
8951         Convert_to_anonymous_function: diag(95123, ts.DiagnosticCategory.Message, "Convert_to_anonymous_function_95123", "Convert to anonymous function"),
8952         Convert_to_named_function: diag(95124, ts.DiagnosticCategory.Message, "Convert_to_named_function_95124", "Convert to named function"),
8953         Convert_to_arrow_function: diag(95125, ts.DiagnosticCategory.Message, "Convert_to_arrow_function_95125", "Convert to arrow function"),
8954         Remove_parentheses: diag(95126, ts.DiagnosticCategory.Message, "Remove_parentheses_95126", "Remove parentheses"),
8955         Could_not_find_a_containing_arrow_function: diag(95127, ts.DiagnosticCategory.Message, "Could_not_find_a_containing_arrow_function_95127", "Could not find a containing arrow function"),
8956         Containing_function_is_not_an_arrow_function: diag(95128, ts.DiagnosticCategory.Message, "Containing_function_is_not_an_arrow_function_95128", "Containing function is not an arrow function"),
8957         Could_not_find_export_statement: diag(95129, ts.DiagnosticCategory.Message, "Could_not_find_export_statement_95129", "Could not find export statement"),
8958         This_file_already_has_a_default_export: diag(95130, ts.DiagnosticCategory.Message, "This_file_already_has_a_default_export_95130", "This file already has a default export"),
8959         Could_not_find_import_clause: diag(95131, ts.DiagnosticCategory.Message, "Could_not_find_import_clause_95131", "Could not find import clause"),
8960         Could_not_find_namespace_import_or_named_imports: diag(95132, ts.DiagnosticCategory.Message, "Could_not_find_namespace_import_or_named_imports_95132", "Could not find namespace import or named imports"),
8961         Selection_is_not_a_valid_type_node: diag(95133, ts.DiagnosticCategory.Message, "Selection_is_not_a_valid_type_node_95133", "Selection is not a valid type node"),
8962         No_type_could_be_extracted_from_this_type_node: diag(95134, ts.DiagnosticCategory.Message, "No_type_could_be_extracted_from_this_type_node_95134", "No type could be extracted from this type node"),
8963         Could_not_find_property_for_which_to_generate_accessor: diag(95135, ts.DiagnosticCategory.Message, "Could_not_find_property_for_which_to_generate_accessor_95135", "Could not find property for which to generate accessor"),
8964         Name_is_not_valid: diag(95136, ts.DiagnosticCategory.Message, "Name_is_not_valid_95136", "Name is not valid"),
8965         Can_only_convert_property_with_modifier: diag(95137, ts.DiagnosticCategory.Message, "Can_only_convert_property_with_modifier_95137", "Can only convert property with modifier"),
8966         Switch_each_misused_0_to_1: diag(95138, ts.DiagnosticCategory.Message, "Switch_each_misused_0_to_1_95138", "Switch each misused '{0}' to '{1}'"),
8967         Convert_to_optional_chain_expression: diag(95139, ts.DiagnosticCategory.Message, "Convert_to_optional_chain_expression_95139", "Convert to optional chain expression"),
8968         Could_not_find_convertible_access_expression: diag(95140, ts.DiagnosticCategory.Message, "Could_not_find_convertible_access_expression_95140", "Could not find convertible access expression"),
8969         Could_not_find_matching_access_expressions: diag(95141, ts.DiagnosticCategory.Message, "Could_not_find_matching_access_expressions_95141", "Could not find matching access expressions"),
8970         Can_only_convert_logical_AND_access_chains: diag(95142, ts.DiagnosticCategory.Message, "Can_only_convert_logical_AND_access_chains_95142", "Can only convert logical AND access chains"),
8971         Add_void_to_Promise_resolved_without_a_value: diag(95143, ts.DiagnosticCategory.Message, "Add_void_to_Promise_resolved_without_a_value_95143", "Add 'void' to Promise resolved without a value"),
8972         Add_void_to_all_Promises_resolved_without_a_value: diag(95144, ts.DiagnosticCategory.Message, "Add_void_to_all_Promises_resolved_without_a_value_95144", "Add 'void' to all Promises resolved without a value"),
8973         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."),
8974         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'."),
8975         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?"),
8976         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."),
8977         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."),
8978         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."),
8979         constructor_is_a_reserved_word: diag(18012, ts.DiagnosticCategory.Error, "constructor_is_a_reserved_word_18012", "'#constructor' is a reserved word."),
8980         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."),
8981         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."),
8982         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}'."),
8983         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."),
8984         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"),
8985         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"),
8986         _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."),
8987         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."),
8988         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."),
8989         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."),
8990         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."),
8991         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."),
8992         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."),
8993         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."),
8994         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."),
8995         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."),
8996         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."),
8997         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."),
8998         Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment: diag(18034, ts.DiagnosticCategory.Message, "Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compi_18034", "Specify the JSX fragment factory function to use when targeting 'react' JSX emit with 'jsxFactory' compiler option is specified, e.g. 'Fragment'."),
8999         Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name: diag(18035, ts.DiagnosticCategory.Error, "Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name_18035", "Invalid value for 'jsxFragmentFactory'. '{0}' is not a valid identifier or qualified-name."),
9000     };
9001 })(ts || (ts = {}));
9002 var ts;
9003 (function (ts) {
9004     var _a;
9005     /* @internal */
9006     function tokenIsIdentifierOrKeyword(token) {
9007         return token >= 78 /* Identifier */;
9008     }
9009     ts.tokenIsIdentifierOrKeyword = tokenIsIdentifierOrKeyword;
9010     /* @internal */
9011     function tokenIsIdentifierOrKeywordOrGreaterThan(token) {
9012         return token === 31 /* GreaterThanToken */ || tokenIsIdentifierOrKeyword(token);
9013     }
9014     ts.tokenIsIdentifierOrKeywordOrGreaterThan = tokenIsIdentifierOrKeywordOrGreaterThan;
9015     var textToKeywordObj = (_a = {
9016             abstract: 125 /* AbstractKeyword */,
9017             any: 128 /* AnyKeyword */,
9018             as: 126 /* AsKeyword */,
9019             asserts: 127 /* AssertsKeyword */,
9020             bigint: 155 /* BigIntKeyword */,
9021             boolean: 131 /* BooleanKeyword */,
9022             break: 80 /* BreakKeyword */,
9023             case: 81 /* CaseKeyword */,
9024             catch: 82 /* CatchKeyword */,
9025             class: 83 /* ClassKeyword */,
9026             continue: 85 /* ContinueKeyword */,
9027             const: 84 /* ConstKeyword */
9028         },
9029         _a["" + "constructor"] = 132 /* ConstructorKeyword */,
9030         _a.debugger = 86 /* DebuggerKeyword */,
9031         _a.declare = 133 /* DeclareKeyword */,
9032         _a.default = 87 /* DefaultKeyword */,
9033         _a.delete = 88 /* DeleteKeyword */,
9034         _a.do = 89 /* DoKeyword */,
9035         _a.else = 90 /* ElseKeyword */,
9036         _a.enum = 91 /* EnumKeyword */,
9037         _a.export = 92 /* ExportKeyword */,
9038         _a.extends = 93 /* ExtendsKeyword */,
9039         _a.false = 94 /* FalseKeyword */,
9040         _a.finally = 95 /* FinallyKeyword */,
9041         _a.for = 96 /* ForKeyword */,
9042         _a.from = 153 /* FromKeyword */,
9043         _a.function = 97 /* FunctionKeyword */,
9044         _a.get = 134 /* GetKeyword */,
9045         _a.if = 98 /* IfKeyword */,
9046         _a.implements = 116 /* ImplementsKeyword */,
9047         _a.import = 99 /* ImportKeyword */,
9048         _a.in = 100 /* InKeyword */,
9049         _a.infer = 135 /* InferKeyword */,
9050         _a.instanceof = 101 /* InstanceOfKeyword */,
9051         _a.interface = 117 /* InterfaceKeyword */,
9052         _a.intrinsic = 136 /* IntrinsicKeyword */,
9053         _a.is = 137 /* IsKeyword */,
9054         _a.keyof = 138 /* KeyOfKeyword */,
9055         _a.let = 118 /* LetKeyword */,
9056         _a.module = 139 /* ModuleKeyword */,
9057         _a.namespace = 140 /* NamespaceKeyword */,
9058         _a.never = 141 /* NeverKeyword */,
9059         _a.new = 102 /* NewKeyword */,
9060         _a.null = 103 /* NullKeyword */,
9061         _a.number = 144 /* NumberKeyword */,
9062         _a.object = 145 /* ObjectKeyword */,
9063         _a.package = 119 /* PackageKeyword */,
9064         _a.private = 120 /* PrivateKeyword */,
9065         _a.protected = 121 /* ProtectedKeyword */,
9066         _a.public = 122 /* PublicKeyword */,
9067         _a.readonly = 142 /* ReadonlyKeyword */,
9068         _a.require = 143 /* RequireKeyword */,
9069         _a.global = 154 /* GlobalKeyword */,
9070         _a.return = 104 /* ReturnKeyword */,
9071         _a.set = 146 /* SetKeyword */,
9072         _a.static = 123 /* StaticKeyword */,
9073         _a.string = 147 /* StringKeyword */,
9074         _a.super = 105 /* SuperKeyword */,
9075         _a.switch = 106 /* SwitchKeyword */,
9076         _a.symbol = 148 /* SymbolKeyword */,
9077         _a.this = 107 /* ThisKeyword */,
9078         _a.throw = 108 /* ThrowKeyword */,
9079         _a.true = 109 /* TrueKeyword */,
9080         _a.try = 110 /* TryKeyword */,
9081         _a.type = 149 /* TypeKeyword */,
9082         _a.typeof = 111 /* TypeOfKeyword */,
9083         _a.undefined = 150 /* UndefinedKeyword */,
9084         _a.unique = 151 /* UniqueKeyword */,
9085         _a.unknown = 152 /* UnknownKeyword */,
9086         _a.var = 112 /* VarKeyword */,
9087         _a.void = 113 /* VoidKeyword */,
9088         _a.while = 114 /* WhileKeyword */,
9089         _a.with = 115 /* WithKeyword */,
9090         _a.yield = 124 /* YieldKeyword */,
9091         _a.async = 129 /* AsyncKeyword */,
9092         _a.await = 130 /* AwaitKeyword */,
9093         _a.of = 156 /* OfKeyword */,
9094         _a);
9095     var textToKeyword = new ts.Map(ts.getEntries(textToKeywordObj));
9096     var textToToken = new ts.Map(ts.getEntries(__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 */, "^=": 77 /* CaretEqualsToken */, "||=": 74 /* BarBarEqualsToken */, "&&=": 75 /* AmpersandAmpersandEqualsToken */, "??=": 76 /* QuestionQuestionEqualsToken */, "@": 59 /* AtToken */, "`": 61 /* BacktickToken */ })));
9097     /*
9098         As per ECMAScript Language Specification 3th Edition, Section 7.6: Identifiers
9099         IdentifierStart ::
9100             Can contain Unicode 3.0.0 categories:
9101             Uppercase letter (Lu),
9102             Lowercase letter (Ll),
9103             Titlecase letter (Lt),
9104             Modifier letter (Lm),
9105             Other letter (Lo), or
9106             Letter number (Nl).
9107         IdentifierPart :: =
9108             Can contain IdentifierStart + Unicode 3.0.0 categories:
9109             Non-spacing mark (Mn),
9110             Combining spacing mark (Mc),
9111             Decimal number (Nd), or
9112             Connector punctuation (Pc).
9113
9114         Codepoint ranges for ES3 Identifiers are extracted from the Unicode 3.0.0 specification at:
9115         http://www.unicode.org/Public/3.0-Update/UnicodeData-3.0.0.txt
9116     */
9117     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,];
9118     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,];
9119     /*
9120         As per ECMAScript Language Specification 5th Edition, Section 7.6: ISyntaxToken Names and Identifiers
9121         IdentifierStart ::
9122             Can contain Unicode 6.2 categories:
9123             Uppercase letter (Lu),
9124             Lowercase letter (Ll),
9125             Titlecase letter (Lt),
9126             Modifier letter (Lm),
9127             Other letter (Lo), or
9128             Letter number (Nl).
9129         IdentifierPart ::
9130             Can contain IdentifierStart + Unicode 6.2 categories:
9131             Non-spacing mark (Mn),
9132             Combining spacing mark (Mc),
9133             Decimal number (Nd),
9134             Connector punctuation (Pc),
9135             <ZWNJ>, or
9136             <ZWJ>.
9137
9138         Codepoint ranges for ES5 Identifiers are extracted from the Unicode 6.2 specification at:
9139         http://www.unicode.org/Public/6.2.0/ucd/UnicodeData.txt
9140     */
9141     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,];
9142     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,];
9143     /**
9144      * Generated by scripts/regenerate-unicode-identifier-parts.js on node v12.4.0 with unicode 12.1
9145      * based on http://www.unicode.org/reports/tr31/ and https://www.ecma-international.org/ecma-262/6.0/#sec-names-and-keywords
9146      * unicodeESNextIdentifierStart corresponds to the ID_Start and Other_ID_Start property, and
9147      * unicodeESNextIdentifierPart corresponds to ID_Continue, Other_ID_Continue, plus ID_Start and Other_ID_Start
9148      */
9149     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];
9150     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];
9151     /**
9152      * Test for whether a single line comment's text contains a directive.
9153      */
9154     var commentDirectiveRegExSingleLine = /^\s*\/\/\/?\s*@(ts-expect-error|ts-ignore)/;
9155     /**
9156      * Test for whether a multi-line comment's last line contains a directive.
9157      */
9158     var commentDirectiveRegExMultiLine = /^\s*(?:\/|\*)*\s*@(ts-expect-error|ts-ignore)/;
9159     function lookupInUnicodeMap(code, map) {
9160         // Bail out quickly if it couldn't possibly be in the map.
9161         if (code < map[0]) {
9162             return false;
9163         }
9164         // Perform binary search in one of the Unicode range maps
9165         var lo = 0;
9166         var hi = map.length;
9167         var mid;
9168         while (lo + 1 < hi) {
9169             mid = lo + (hi - lo) / 2;
9170             // mid has to be even to catch a range's beginning
9171             mid -= mid % 2;
9172             if (map[mid] <= code && code <= map[mid + 1]) {
9173                 return true;
9174             }
9175             if (code < map[mid]) {
9176                 hi = mid;
9177             }
9178             else {
9179                 lo = mid + 2;
9180             }
9181         }
9182         return false;
9183     }
9184     /* @internal */ function isUnicodeIdentifierStart(code, languageVersion) {
9185         return languageVersion >= 2 /* ES2015 */ ?
9186             lookupInUnicodeMap(code, unicodeESNextIdentifierStart) :
9187             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierStart) :
9188                 lookupInUnicodeMap(code, unicodeES3IdentifierStart);
9189     }
9190     ts.isUnicodeIdentifierStart = isUnicodeIdentifierStart;
9191     function isUnicodeIdentifierPart(code, languageVersion) {
9192         return languageVersion >= 2 /* ES2015 */ ?
9193             lookupInUnicodeMap(code, unicodeESNextIdentifierPart) :
9194             languageVersion === 1 /* ES5 */ ? lookupInUnicodeMap(code, unicodeES5IdentifierPart) :
9195                 lookupInUnicodeMap(code, unicodeES3IdentifierPart);
9196     }
9197     function makeReverseMap(source) {
9198         var result = [];
9199         source.forEach(function (value, name) {
9200             result[value] = name;
9201         });
9202         return result;
9203     }
9204     var tokenStrings = makeReverseMap(textToToken);
9205     function tokenToString(t) {
9206         return tokenStrings[t];
9207     }
9208     ts.tokenToString = tokenToString;
9209     /* @internal */
9210     function stringToToken(s) {
9211         return textToToken.get(s);
9212     }
9213     ts.stringToToken = stringToToken;
9214     /* @internal */
9215     function computeLineStarts(text) {
9216         var result = new Array();
9217         var pos = 0;
9218         var lineStart = 0;
9219         while (pos < text.length) {
9220             var ch = text.charCodeAt(pos);
9221             pos++;
9222             switch (ch) {
9223                 case 13 /* carriageReturn */:
9224                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
9225                         pos++;
9226                     }
9227                 // falls through
9228                 case 10 /* lineFeed */:
9229                     result.push(lineStart);
9230                     lineStart = pos;
9231                     break;
9232                 default:
9233                     if (ch > 127 /* maxAsciiCharacter */ && isLineBreak(ch)) {
9234                         result.push(lineStart);
9235                         lineStart = pos;
9236                     }
9237                     break;
9238             }
9239         }
9240         result.push(lineStart);
9241         return result;
9242     }
9243     ts.computeLineStarts = computeLineStarts;
9244     function getPositionOfLineAndCharacter(sourceFile, line, character, allowEdits) {
9245         return sourceFile.getPositionOfLineAndCharacter ?
9246             sourceFile.getPositionOfLineAndCharacter(line, character, allowEdits) :
9247             computePositionOfLineAndCharacter(getLineStarts(sourceFile), line, character, sourceFile.text, allowEdits);
9248     }
9249     ts.getPositionOfLineAndCharacter = getPositionOfLineAndCharacter;
9250     /* @internal */
9251     function computePositionOfLineAndCharacter(lineStarts, line, character, debugText, allowEdits) {
9252         if (line < 0 || line >= lineStarts.length) {
9253             if (allowEdits) {
9254                 // Clamp line to nearest allowable value
9255                 line = line < 0 ? 0 : line >= lineStarts.length ? lineStarts.length - 1 : line;
9256             }
9257             else {
9258                 ts.Debug.fail("Bad line number. Line: " + line + ", lineStarts.length: " + lineStarts.length + " , line map is correct? " + (debugText !== undefined ? ts.arraysEqual(lineStarts, computeLineStarts(debugText)) : "unknown"));
9259             }
9260         }
9261         var res = lineStarts[line] + character;
9262         if (allowEdits) {
9263             // Clamp to nearest allowable values to allow the underlying to be edited without crashing (accuracy is lost, instead)
9264             // TODO: Somehow track edits between file as it was during the creation of sourcemap we have and the current file and
9265             // apply them to the computed position to improve accuracy
9266             return res > lineStarts[line + 1] ? lineStarts[line + 1] : typeof debugText === "string" && res > debugText.length ? debugText.length : res;
9267         }
9268         if (line < lineStarts.length - 1) {
9269             ts.Debug.assert(res < lineStarts[line + 1]);
9270         }
9271         else if (debugText !== undefined) {
9272             ts.Debug.assert(res <= debugText.length); // Allow single character overflow for trailing newline
9273         }
9274         return res;
9275     }
9276     ts.computePositionOfLineAndCharacter = computePositionOfLineAndCharacter;
9277     /* @internal */
9278     function getLineStarts(sourceFile) {
9279         return sourceFile.lineMap || (sourceFile.lineMap = computeLineStarts(sourceFile.text));
9280     }
9281     ts.getLineStarts = getLineStarts;
9282     /* @internal */
9283     function computeLineAndCharacterOfPosition(lineStarts, position) {
9284         var lineNumber = computeLineOfPosition(lineStarts, position);
9285         return {
9286             line: lineNumber,
9287             character: position - lineStarts[lineNumber]
9288         };
9289     }
9290     ts.computeLineAndCharacterOfPosition = computeLineAndCharacterOfPosition;
9291     /**
9292      * @internal
9293      * We assume the first line starts at position 0 and 'position' is non-negative.
9294      */
9295     function computeLineOfPosition(lineStarts, position, lowerBound) {
9296         var lineNumber = ts.binarySearch(lineStarts, position, ts.identity, ts.compareValues, lowerBound);
9297         if (lineNumber < 0) {
9298             // If the actual position was not found,
9299             // the binary search returns the 2's-complement of the next line start
9300             // e.g. if the line starts at [5, 10, 23, 80] and the position requested was 20
9301             // then the search will return -2.
9302             //
9303             // We want the index of the previous line start, so we subtract 1.
9304             // Review 2's-complement if this is confusing.
9305             lineNumber = ~lineNumber - 1;
9306             ts.Debug.assert(lineNumber !== -1, "position cannot precede the beginning of the file");
9307         }
9308         return lineNumber;
9309     }
9310     ts.computeLineOfPosition = computeLineOfPosition;
9311     /** @internal */
9312     function getLinesBetweenPositions(sourceFile, pos1, pos2) {
9313         if (pos1 === pos2)
9314             return 0;
9315         var lineStarts = getLineStarts(sourceFile);
9316         var lower = Math.min(pos1, pos2);
9317         var isNegative = lower === pos2;
9318         var upper = isNegative ? pos1 : pos2;
9319         var lowerLine = computeLineOfPosition(lineStarts, lower);
9320         var upperLine = computeLineOfPosition(lineStarts, upper, lowerLine);
9321         return isNegative ? lowerLine - upperLine : upperLine - lowerLine;
9322     }
9323     ts.getLinesBetweenPositions = getLinesBetweenPositions;
9324     function getLineAndCharacterOfPosition(sourceFile, position) {
9325         return computeLineAndCharacterOfPosition(getLineStarts(sourceFile), position);
9326     }
9327     ts.getLineAndCharacterOfPosition = getLineAndCharacterOfPosition;
9328     function isWhiteSpaceLike(ch) {
9329         return isWhiteSpaceSingleLine(ch) || isLineBreak(ch);
9330     }
9331     ts.isWhiteSpaceLike = isWhiteSpaceLike;
9332     /** Does not include line breaks. For that, see isWhiteSpaceLike. */
9333     function isWhiteSpaceSingleLine(ch) {
9334         // Note: nextLine is in the Zs space, and should be considered to be a whitespace.
9335         // It is explicitly not a line-break as it isn't in the exact set specified by EcmaScript.
9336         return ch === 32 /* space */ ||
9337             ch === 9 /* tab */ ||
9338             ch === 11 /* verticalTab */ ||
9339             ch === 12 /* formFeed */ ||
9340             ch === 160 /* nonBreakingSpace */ ||
9341             ch === 133 /* nextLine */ ||
9342             ch === 5760 /* ogham */ ||
9343             ch >= 8192 /* enQuad */ && ch <= 8203 /* zeroWidthSpace */ ||
9344             ch === 8239 /* narrowNoBreakSpace */ ||
9345             ch === 8287 /* mathematicalSpace */ ||
9346             ch === 12288 /* ideographicSpace */ ||
9347             ch === 65279 /* byteOrderMark */;
9348     }
9349     ts.isWhiteSpaceSingleLine = isWhiteSpaceSingleLine;
9350     function isLineBreak(ch) {
9351         // ES5 7.3:
9352         // The ECMAScript line terminator characters are listed in Table 3.
9353         //     Table 3: Line Terminator Characters
9354         //     Code Unit Value     Name                    Formal Name
9355         //     \u000A              Line Feed               <LF>
9356         //     \u000D              Carriage Return         <CR>
9357         //     \u2028              Line separator          <LS>
9358         //     \u2029              Paragraph separator     <PS>
9359         // Only the characters in Table 3 are treated as line terminators. Other new line or line
9360         // breaking characters are treated as white space but not as line terminators.
9361         return ch === 10 /* lineFeed */ ||
9362             ch === 13 /* carriageReturn */ ||
9363             ch === 8232 /* lineSeparator */ ||
9364             ch === 8233 /* paragraphSeparator */;
9365     }
9366     ts.isLineBreak = isLineBreak;
9367     function isDigit(ch) {
9368         return ch >= 48 /* _0 */ && ch <= 57 /* _9 */;
9369     }
9370     function isHexDigit(ch) {
9371         return isDigit(ch) || ch >= 65 /* A */ && ch <= 70 /* F */ || ch >= 97 /* a */ && ch <= 102 /* f */;
9372     }
9373     function isCodePoint(code) {
9374         return code <= 0x10FFFF;
9375     }
9376     /* @internal */
9377     function isOctalDigit(ch) {
9378         return ch >= 48 /* _0 */ && ch <= 55 /* _7 */;
9379     }
9380     ts.isOctalDigit = isOctalDigit;
9381     function couldStartTrivia(text, pos) {
9382         // Keep in sync with skipTrivia
9383         var ch = text.charCodeAt(pos);
9384         switch (ch) {
9385             case 13 /* carriageReturn */:
9386             case 10 /* lineFeed */:
9387             case 9 /* tab */:
9388             case 11 /* verticalTab */:
9389             case 12 /* formFeed */:
9390             case 32 /* space */:
9391             case 47 /* slash */:
9392             // starts of normal trivia
9393             // falls through
9394             case 60 /* lessThan */:
9395             case 124 /* bar */:
9396             case 61 /* equals */:
9397             case 62 /* greaterThan */:
9398                 // Starts of conflict marker trivia
9399                 return true;
9400             case 35 /* hash */:
9401                 // Only if its the beginning can we have #! trivia
9402                 return pos === 0;
9403             default:
9404                 return ch > 127 /* maxAsciiCharacter */;
9405         }
9406     }
9407     ts.couldStartTrivia = couldStartTrivia;
9408     /* @internal */
9409     function skipTrivia(text, pos, stopAfterLineBreak, stopAtComments) {
9410         if (stopAtComments === void 0) { stopAtComments = false; }
9411         if (ts.positionIsSynthesized(pos)) {
9412             return pos;
9413         }
9414         // Keep in sync with couldStartTrivia
9415         while (true) {
9416             var ch = text.charCodeAt(pos);
9417             switch (ch) {
9418                 case 13 /* carriageReturn */:
9419                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9420                         pos++;
9421                     }
9422                 // falls through
9423                 case 10 /* lineFeed */:
9424                     pos++;
9425                     if (stopAfterLineBreak) {
9426                         return pos;
9427                     }
9428                     continue;
9429                 case 9 /* tab */:
9430                 case 11 /* verticalTab */:
9431                 case 12 /* formFeed */:
9432                 case 32 /* space */:
9433                     pos++;
9434                     continue;
9435                 case 47 /* slash */:
9436                     if (stopAtComments) {
9437                         break;
9438                     }
9439                     if (text.charCodeAt(pos + 1) === 47 /* slash */) {
9440                         pos += 2;
9441                         while (pos < text.length) {
9442                             if (isLineBreak(text.charCodeAt(pos))) {
9443                                 break;
9444                             }
9445                             pos++;
9446                         }
9447                         continue;
9448                     }
9449                     if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
9450                         pos += 2;
9451                         while (pos < text.length) {
9452                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9453                                 pos += 2;
9454                                 break;
9455                             }
9456                             pos++;
9457                         }
9458                         continue;
9459                     }
9460                     break;
9461                 case 60 /* lessThan */:
9462                 case 124 /* bar */:
9463                 case 61 /* equals */:
9464                 case 62 /* greaterThan */:
9465                     if (isConflictMarkerTrivia(text, pos)) {
9466                         pos = scanConflictMarkerTrivia(text, pos);
9467                         continue;
9468                     }
9469                     break;
9470                 case 35 /* hash */:
9471                     if (pos === 0 && isShebangTrivia(text, pos)) {
9472                         pos = scanShebangTrivia(text, pos);
9473                         continue;
9474                     }
9475                     break;
9476                 default:
9477                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
9478                         pos++;
9479                         continue;
9480                     }
9481                     break;
9482             }
9483             return pos;
9484         }
9485     }
9486     ts.skipTrivia = skipTrivia;
9487     // All conflict markers consist of the same character repeated seven times.  If it is
9488     // a <<<<<<< or >>>>>>> marker then it is also followed by a space.
9489     var mergeConflictMarkerLength = "<<<<<<<".length;
9490     function isConflictMarkerTrivia(text, pos) {
9491         ts.Debug.assert(pos >= 0);
9492         // Conflict markers must be at the start of a line.
9493         if (pos === 0 || isLineBreak(text.charCodeAt(pos - 1))) {
9494             var ch = text.charCodeAt(pos);
9495             if ((pos + mergeConflictMarkerLength) < text.length) {
9496                 for (var i = 0; i < mergeConflictMarkerLength; i++) {
9497                     if (text.charCodeAt(pos + i) !== ch) {
9498                         return false;
9499                     }
9500                 }
9501                 return ch === 61 /* equals */ ||
9502                     text.charCodeAt(pos + mergeConflictMarkerLength) === 32 /* space */;
9503             }
9504         }
9505         return false;
9506     }
9507     function scanConflictMarkerTrivia(text, pos, error) {
9508         if (error) {
9509             error(ts.Diagnostics.Merge_conflict_marker_encountered, pos, mergeConflictMarkerLength);
9510         }
9511         var ch = text.charCodeAt(pos);
9512         var len = text.length;
9513         if (ch === 60 /* lessThan */ || ch === 62 /* greaterThan */) {
9514             while (pos < len && !isLineBreak(text.charCodeAt(pos))) {
9515                 pos++;
9516             }
9517         }
9518         else {
9519             ts.Debug.assert(ch === 124 /* bar */ || ch === 61 /* equals */);
9520             // Consume everything from the start of a ||||||| or ======= marker to the start
9521             // of the next ======= or >>>>>>> marker.
9522             while (pos < len) {
9523                 var currentChar = text.charCodeAt(pos);
9524                 if ((currentChar === 61 /* equals */ || currentChar === 62 /* greaterThan */) && currentChar !== ch && isConflictMarkerTrivia(text, pos)) {
9525                     break;
9526                 }
9527                 pos++;
9528             }
9529         }
9530         return pos;
9531     }
9532     var shebangTriviaRegex = /^#!.*/;
9533     /*@internal*/
9534     function isShebangTrivia(text, pos) {
9535         // Shebangs check must only be done at the start of the file
9536         ts.Debug.assert(pos === 0);
9537         return shebangTriviaRegex.test(text);
9538     }
9539     ts.isShebangTrivia = isShebangTrivia;
9540     /*@internal*/
9541     function scanShebangTrivia(text, pos) {
9542         var shebang = shebangTriviaRegex.exec(text)[0];
9543         pos = pos + shebang.length;
9544         return pos;
9545     }
9546     ts.scanShebangTrivia = scanShebangTrivia;
9547     /**
9548      * Invokes a callback for each comment range following the provided position.
9549      *
9550      * Single-line comment ranges include the leading double-slash characters but not the ending
9551      * line break. Multi-line comment ranges include the leading slash-asterisk and trailing
9552      * asterisk-slash characters.
9553      *
9554      * @param reduce If true, accumulates the result of calling the callback in a fashion similar
9555      *      to reduceLeft. If false, iteration stops when the callback returns a truthy value.
9556      * @param text The source text to scan.
9557      * @param pos The position at which to start scanning.
9558      * @param trailing If false, whitespace is skipped until the first line break and comments
9559      *      between that location and the next token are returned. If true, comments occurring
9560      *      between the given position and the next line break are returned.
9561      * @param cb The callback to execute as each comment range is encountered.
9562      * @param state A state value to pass to each iteration of the callback.
9563      * @param initial An initial value to pass when accumulating results (when "reduce" is true).
9564      * @returns If "reduce" is true, the accumulated value. If "reduce" is false, the first truthy
9565      *      return value of the callback.
9566      */
9567     function iterateCommentRanges(reduce, text, pos, trailing, cb, state, initial) {
9568         var pendingPos;
9569         var pendingEnd;
9570         var pendingKind;
9571         var pendingHasTrailingNewLine;
9572         var hasPendingCommentRange = false;
9573         var collecting = trailing;
9574         var accumulator = initial;
9575         if (pos === 0) {
9576             collecting = true;
9577             var shebang = getShebang(text);
9578             if (shebang) {
9579                 pos = shebang.length;
9580             }
9581         }
9582         scan: while (pos >= 0 && pos < text.length) {
9583             var ch = text.charCodeAt(pos);
9584             switch (ch) {
9585                 case 13 /* carriageReturn */:
9586                     if (text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
9587                         pos++;
9588                     }
9589                 // falls through
9590                 case 10 /* lineFeed */:
9591                     pos++;
9592                     if (trailing) {
9593                         break scan;
9594                     }
9595                     collecting = true;
9596                     if (hasPendingCommentRange) {
9597                         pendingHasTrailingNewLine = true;
9598                     }
9599                     continue;
9600                 case 9 /* tab */:
9601                 case 11 /* verticalTab */:
9602                 case 12 /* formFeed */:
9603                 case 32 /* space */:
9604                     pos++;
9605                     continue;
9606                 case 47 /* slash */:
9607                     var nextChar = text.charCodeAt(pos + 1);
9608                     var hasTrailingNewLine = false;
9609                     if (nextChar === 47 /* slash */ || nextChar === 42 /* asterisk */) {
9610                         var kind = nextChar === 47 /* slash */ ? 2 /* SingleLineCommentTrivia */ : 3 /* MultiLineCommentTrivia */;
9611                         var startPos = pos;
9612                         pos += 2;
9613                         if (nextChar === 47 /* slash */) {
9614                             while (pos < text.length) {
9615                                 if (isLineBreak(text.charCodeAt(pos))) {
9616                                     hasTrailingNewLine = true;
9617                                     break;
9618                                 }
9619                                 pos++;
9620                             }
9621                         }
9622                         else {
9623                             while (pos < text.length) {
9624                                 if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
9625                                     pos += 2;
9626                                     break;
9627                                 }
9628                                 pos++;
9629                             }
9630                         }
9631                         if (collecting) {
9632                             if (hasPendingCommentRange) {
9633                                 accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
9634                                 if (!reduce && accumulator) {
9635                                     // If we are not reducing and we have a truthy result, return it.
9636                                     return accumulator;
9637                                 }
9638                             }
9639                             pendingPos = startPos;
9640                             pendingEnd = pos;
9641                             pendingKind = kind;
9642                             pendingHasTrailingNewLine = hasTrailingNewLine;
9643                             hasPendingCommentRange = true;
9644                         }
9645                         continue;
9646                     }
9647                     break scan;
9648                 default:
9649                     if (ch > 127 /* maxAsciiCharacter */ && (isWhiteSpaceLike(ch))) {
9650                         if (hasPendingCommentRange && isLineBreak(ch)) {
9651                             pendingHasTrailingNewLine = true;
9652                         }
9653                         pos++;
9654                         continue;
9655                     }
9656                     break scan;
9657             }
9658         }
9659         if (hasPendingCommentRange) {
9660             accumulator = cb(pendingPos, pendingEnd, pendingKind, pendingHasTrailingNewLine, state, accumulator);
9661         }
9662         return accumulator;
9663     }
9664     function forEachLeadingCommentRange(text, pos, cb, state) {
9665         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ false, cb, state);
9666     }
9667     ts.forEachLeadingCommentRange = forEachLeadingCommentRange;
9668     function forEachTrailingCommentRange(text, pos, cb, state) {
9669         return iterateCommentRanges(/*reduce*/ false, text, pos, /*trailing*/ true, cb, state);
9670     }
9671     ts.forEachTrailingCommentRange = forEachTrailingCommentRange;
9672     function reduceEachLeadingCommentRange(text, pos, cb, state, initial) {
9673         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ false, cb, state, initial);
9674     }
9675     ts.reduceEachLeadingCommentRange = reduceEachLeadingCommentRange;
9676     function reduceEachTrailingCommentRange(text, pos, cb, state, initial) {
9677         return iterateCommentRanges(/*reduce*/ true, text, pos, /*trailing*/ true, cb, state, initial);
9678     }
9679     ts.reduceEachTrailingCommentRange = reduceEachTrailingCommentRange;
9680     function appendCommentRange(pos, end, kind, hasTrailingNewLine, _state, comments) {
9681         if (!comments) {
9682             comments = [];
9683         }
9684         comments.push({ kind: kind, pos: pos, end: end, hasTrailingNewLine: hasTrailingNewLine });
9685         return comments;
9686     }
9687     function getLeadingCommentRanges(text, pos) {
9688         return reduceEachLeadingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
9689     }
9690     ts.getLeadingCommentRanges = getLeadingCommentRanges;
9691     function getTrailingCommentRanges(text, pos) {
9692         return reduceEachTrailingCommentRange(text, pos, appendCommentRange, /*state*/ undefined, /*initial*/ undefined);
9693     }
9694     ts.getTrailingCommentRanges = getTrailingCommentRanges;
9695     /** Optionally, get the shebang */
9696     function getShebang(text) {
9697         var match = shebangTriviaRegex.exec(text);
9698         if (match) {
9699             return match[0];
9700         }
9701     }
9702     ts.getShebang = getShebang;
9703     function isIdentifierStart(ch, languageVersion) {
9704         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
9705             ch === 36 /* $ */ || ch === 95 /* _ */ ||
9706             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierStart(ch, languageVersion);
9707     }
9708     ts.isIdentifierStart = isIdentifierStart;
9709     function isIdentifierPart(ch, languageVersion, identifierVariant) {
9710         return ch >= 65 /* A */ && ch <= 90 /* Z */ || ch >= 97 /* a */ && ch <= 122 /* z */ ||
9711             ch >= 48 /* _0 */ && ch <= 57 /* _9 */ || ch === 36 /* $ */ || ch === 95 /* _ */ ||
9712             // "-" and ":" are valid in JSX Identifiers
9713             (identifierVariant === 1 /* JSX */ ? (ch === 45 /* minus */ || ch === 58 /* colon */) : false) ||
9714             ch > 127 /* maxAsciiCharacter */ && isUnicodeIdentifierPart(ch, languageVersion);
9715     }
9716     ts.isIdentifierPart = isIdentifierPart;
9717     /* @internal */
9718     function isIdentifierText(name, languageVersion, identifierVariant) {
9719         var ch = codePointAt(name, 0);
9720         if (!isIdentifierStart(ch, languageVersion)) {
9721             return false;
9722         }
9723         for (var i = charSize(ch); i < name.length; i += charSize(ch)) {
9724             if (!isIdentifierPart(ch = codePointAt(name, i), languageVersion, identifierVariant)) {
9725                 return false;
9726             }
9727         }
9728         return true;
9729     }
9730     ts.isIdentifierText = isIdentifierText;
9731     // Creates a scanner over a (possibly unspecified) range of a piece of text.
9732     function createScanner(languageVersion, skipTrivia, languageVariant, textInitial, onError, start, length) {
9733         if (languageVariant === void 0) { languageVariant = 0 /* Standard */; }
9734         var text = textInitial;
9735         // Current position (end position of text of current token)
9736         var pos;
9737         // end of text
9738         var end;
9739         // Start position of whitespace before current token
9740         var startPos;
9741         // Start position of text of current token
9742         var tokenPos;
9743         var token;
9744         var tokenValue;
9745         var tokenFlags;
9746         var commentDirectives;
9747         var inJSDocType = 0;
9748         setText(text, start, length);
9749         var scanner = {
9750             getStartPos: function () { return startPos; },
9751             getTextPos: function () { return pos; },
9752             getToken: function () { return token; },
9753             getTokenPos: function () { return tokenPos; },
9754             getTokenText: function () { return text.substring(tokenPos, pos); },
9755             getTokenValue: function () { return tokenValue; },
9756             hasUnicodeEscape: function () { return (tokenFlags & 1024 /* UnicodeEscape */) !== 0; },
9757             hasExtendedUnicodeEscape: function () { return (tokenFlags & 8 /* ExtendedUnicodeEscape */) !== 0; },
9758             hasPrecedingLineBreak: function () { return (tokenFlags & 1 /* PrecedingLineBreak */) !== 0; },
9759             hasPrecedingJSDocComment: function () { return (tokenFlags & 2 /* PrecedingJSDocComment */) !== 0; },
9760             isIdentifier: function () { return token === 78 /* Identifier */ || token > 115 /* LastReservedWord */; },
9761             isReservedWord: function () { return token >= 80 /* FirstReservedWord */ && token <= 115 /* LastReservedWord */; },
9762             isUnterminated: function () { return (tokenFlags & 4 /* Unterminated */) !== 0; },
9763             getCommentDirectives: function () { return commentDirectives; },
9764             getNumericLiteralFlags: function () { return tokenFlags & 1008 /* NumericLiteralFlags */; },
9765             getTokenFlags: function () { return tokenFlags; },
9766             reScanGreaterToken: reScanGreaterToken,
9767             reScanAsteriskEqualsToken: reScanAsteriskEqualsToken,
9768             reScanSlashToken: reScanSlashToken,
9769             reScanTemplateToken: reScanTemplateToken,
9770             reScanTemplateHeadOrNoSubstitutionTemplate: reScanTemplateHeadOrNoSubstitutionTemplate,
9771             scanJsxIdentifier: scanJsxIdentifier,
9772             scanJsxAttributeValue: scanJsxAttributeValue,
9773             reScanJsxAttributeValue: reScanJsxAttributeValue,
9774             reScanJsxToken: reScanJsxToken,
9775             reScanLessThanToken: reScanLessThanToken,
9776             reScanQuestionToken: reScanQuestionToken,
9777             scanJsxToken: scanJsxToken,
9778             scanJsDocToken: scanJsDocToken,
9779             scan: scan,
9780             getText: getText,
9781             clearCommentDirectives: clearCommentDirectives,
9782             setText: setText,
9783             setScriptTarget: setScriptTarget,
9784             setLanguageVariant: setLanguageVariant,
9785             setOnError: setOnError,
9786             setTextPos: setTextPos,
9787             setInJSDocType: setInJSDocType,
9788             tryScan: tryScan,
9789             lookAhead: lookAhead,
9790             scanRange: scanRange,
9791         };
9792         if (ts.Debug.isDebugging) {
9793             Object.defineProperty(scanner, "__debugShowCurrentPositionInText", {
9794                 get: function () {
9795                     var text = scanner.getText();
9796                     return text.slice(0, scanner.getStartPos()) + "â•‘" + text.slice(scanner.getStartPos());
9797                 },
9798             });
9799         }
9800         return scanner;
9801         function error(message, errPos, length) {
9802             if (errPos === void 0) { errPos = pos; }
9803             if (onError) {
9804                 var oldPos = pos;
9805                 pos = errPos;
9806                 onError(message, length || 0);
9807                 pos = oldPos;
9808             }
9809         }
9810         function scanNumberFragment() {
9811             var start = pos;
9812             var allowSeparator = false;
9813             var isPreviousTokenSeparator = false;
9814             var result = "";
9815             while (true) {
9816                 var ch = text.charCodeAt(pos);
9817                 if (ch === 95 /* _ */) {
9818                     tokenFlags |= 512 /* ContainsSeparator */;
9819                     if (allowSeparator) {
9820                         allowSeparator = false;
9821                         isPreviousTokenSeparator = true;
9822                         result += text.substring(start, pos);
9823                     }
9824                     else if (isPreviousTokenSeparator) {
9825                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9826                     }
9827                     else {
9828                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9829                     }
9830                     pos++;
9831                     start = pos;
9832                     continue;
9833                 }
9834                 if (isDigit(ch)) {
9835                     allowSeparator = true;
9836                     isPreviousTokenSeparator = false;
9837                     pos++;
9838                     continue;
9839                 }
9840                 break;
9841             }
9842             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9843                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9844             }
9845             return result + text.substring(start, pos);
9846         }
9847         function scanNumber() {
9848             var start = pos;
9849             var mainFragment = scanNumberFragment();
9850             var decimalFragment;
9851             var scientificFragment;
9852             if (text.charCodeAt(pos) === 46 /* dot */) {
9853                 pos++;
9854                 decimalFragment = scanNumberFragment();
9855             }
9856             var end = pos;
9857             if (text.charCodeAt(pos) === 69 /* E */ || text.charCodeAt(pos) === 101 /* e */) {
9858                 pos++;
9859                 tokenFlags |= 16 /* Scientific */;
9860                 if (text.charCodeAt(pos) === 43 /* plus */ || text.charCodeAt(pos) === 45 /* minus */)
9861                     pos++;
9862                 var preNumericPart = pos;
9863                 var finalFragment = scanNumberFragment();
9864                 if (!finalFragment) {
9865                     error(ts.Diagnostics.Digit_expected);
9866                 }
9867                 else {
9868                     scientificFragment = text.substring(end, preNumericPart) + finalFragment;
9869                     end = pos;
9870                 }
9871             }
9872             var result;
9873             if (tokenFlags & 512 /* ContainsSeparator */) {
9874                 result = mainFragment;
9875                 if (decimalFragment) {
9876                     result += "." + decimalFragment;
9877                 }
9878                 if (scientificFragment) {
9879                     result += scientificFragment;
9880                 }
9881             }
9882             else {
9883                 result = text.substring(start, end); // No need to use all the fragments; no _ removal needed
9884             }
9885             if (decimalFragment !== undefined || tokenFlags & 16 /* Scientific */) {
9886                 checkForIdentifierStartAfterNumericLiteral(start, decimalFragment === undefined && !!(tokenFlags & 16 /* Scientific */));
9887                 return {
9888                     type: 8 /* NumericLiteral */,
9889                     value: "" + +result // if value is not an integer, it can be safely coerced to a number
9890                 };
9891             }
9892             else {
9893                 tokenValue = result;
9894                 var type = checkBigIntSuffix(); // if value is an integer, check whether it is a bigint
9895                 checkForIdentifierStartAfterNumericLiteral(start);
9896                 return { type: type, value: tokenValue };
9897             }
9898         }
9899         function checkForIdentifierStartAfterNumericLiteral(numericStart, isScientific) {
9900             if (!isIdentifierStart(codePointAt(text, pos), languageVersion)) {
9901                 return;
9902             }
9903             var identifierStart = pos;
9904             var length = scanIdentifierParts().length;
9905             if (length === 1 && text[identifierStart] === "n") {
9906                 if (isScientific) {
9907                     error(ts.Diagnostics.A_bigint_literal_cannot_use_exponential_notation, numericStart, identifierStart - numericStart + 1);
9908                 }
9909                 else {
9910                     error(ts.Diagnostics.A_bigint_literal_must_be_an_integer, numericStart, identifierStart - numericStart + 1);
9911                 }
9912             }
9913             else {
9914                 error(ts.Diagnostics.An_identifier_or_keyword_cannot_immediately_follow_a_numeric_literal, identifierStart, length);
9915                 pos = identifierStart;
9916             }
9917         }
9918         function scanOctalDigits() {
9919             var start = pos;
9920             while (isOctalDigit(text.charCodeAt(pos))) {
9921                 pos++;
9922             }
9923             return +(text.substring(start, pos));
9924         }
9925         /**
9926          * Scans the given number of hexadecimal digits in the text,
9927          * returning -1 if the given number is unavailable.
9928          */
9929         function scanExactNumberOfHexDigits(count, canHaveSeparators) {
9930             var valueString = scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ false, canHaveSeparators);
9931             return valueString ? parseInt(valueString, 16) : -1;
9932         }
9933         /**
9934          * Scans as many hexadecimal digits as are available in the text,
9935          * returning "" if the given number of digits was unavailable.
9936          */
9937         function scanMinimumNumberOfHexDigits(count, canHaveSeparators) {
9938             return scanHexDigits(/*minCount*/ count, /*scanAsManyAsPossible*/ true, canHaveSeparators);
9939         }
9940         function scanHexDigits(minCount, scanAsManyAsPossible, canHaveSeparators) {
9941             var valueChars = [];
9942             var allowSeparator = false;
9943             var isPreviousTokenSeparator = false;
9944             while (valueChars.length < minCount || scanAsManyAsPossible) {
9945                 var ch = text.charCodeAt(pos);
9946                 if (canHaveSeparators && ch === 95 /* _ */) {
9947                     tokenFlags |= 512 /* ContainsSeparator */;
9948                     if (allowSeparator) {
9949                         allowSeparator = false;
9950                         isPreviousTokenSeparator = true;
9951                     }
9952                     else if (isPreviousTokenSeparator) {
9953                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
9954                     }
9955                     else {
9956                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
9957                     }
9958                     pos++;
9959                     continue;
9960                 }
9961                 allowSeparator = canHaveSeparators;
9962                 if (ch >= 65 /* A */ && ch <= 70 /* F */) {
9963                     ch += 97 /* a */ - 65 /* A */; // standardize hex literals to lowercase
9964                 }
9965                 else if (!((ch >= 48 /* _0 */ && ch <= 57 /* _9 */) ||
9966                     (ch >= 97 /* a */ && ch <= 102 /* f */))) {
9967                     break;
9968                 }
9969                 valueChars.push(ch);
9970                 pos++;
9971                 isPreviousTokenSeparator = false;
9972             }
9973             if (valueChars.length < minCount) {
9974                 valueChars = [];
9975             }
9976             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
9977                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
9978             }
9979             return String.fromCharCode.apply(String, valueChars);
9980         }
9981         function scanString(jsxAttributeString) {
9982             if (jsxAttributeString === void 0) { jsxAttributeString = false; }
9983             var quote = text.charCodeAt(pos);
9984             pos++;
9985             var result = "";
9986             var start = pos;
9987             while (true) {
9988                 if (pos >= end) {
9989                     result += text.substring(start, pos);
9990                     tokenFlags |= 4 /* Unterminated */;
9991                     error(ts.Diagnostics.Unterminated_string_literal);
9992                     break;
9993                 }
9994                 var ch = text.charCodeAt(pos);
9995                 if (ch === quote) {
9996                     result += text.substring(start, pos);
9997                     pos++;
9998                     break;
9999                 }
10000                 if (ch === 92 /* backslash */ && !jsxAttributeString) {
10001                     result += text.substring(start, pos);
10002                     result += scanEscapeSequence();
10003                     start = pos;
10004                     continue;
10005                 }
10006                 if (isLineBreak(ch) && !jsxAttributeString) {
10007                     result += text.substring(start, pos);
10008                     tokenFlags |= 4 /* Unterminated */;
10009                     error(ts.Diagnostics.Unterminated_string_literal);
10010                     break;
10011                 }
10012                 pos++;
10013             }
10014             return result;
10015         }
10016         /**
10017          * Sets the current 'tokenValue' and returns a NoSubstitutionTemplateLiteral or
10018          * a literal component of a TemplateExpression.
10019          */
10020         function scanTemplateAndSetTokenValue(isTaggedTemplate) {
10021             var startedWithBacktick = text.charCodeAt(pos) === 96 /* backtick */;
10022             pos++;
10023             var start = pos;
10024             var contents = "";
10025             var resultingToken;
10026             while (true) {
10027                 if (pos >= end) {
10028                     contents += text.substring(start, pos);
10029                     tokenFlags |= 4 /* Unterminated */;
10030                     error(ts.Diagnostics.Unterminated_template_literal);
10031                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
10032                     break;
10033                 }
10034                 var currChar = text.charCodeAt(pos);
10035                 // '`'
10036                 if (currChar === 96 /* backtick */) {
10037                     contents += text.substring(start, pos);
10038                     pos++;
10039                     resultingToken = startedWithBacktick ? 14 /* NoSubstitutionTemplateLiteral */ : 17 /* TemplateTail */;
10040                     break;
10041                 }
10042                 // '${'
10043                 if (currChar === 36 /* $ */ && pos + 1 < end && text.charCodeAt(pos + 1) === 123 /* openBrace */) {
10044                     contents += text.substring(start, pos);
10045                     pos += 2;
10046                     resultingToken = startedWithBacktick ? 15 /* TemplateHead */ : 16 /* TemplateMiddle */;
10047                     break;
10048                 }
10049                 // Escape character
10050                 if (currChar === 92 /* backslash */) {
10051                     contents += text.substring(start, pos);
10052                     contents += scanEscapeSequence(isTaggedTemplate);
10053                     start = pos;
10054                     continue;
10055                 }
10056                 // Speculated ECMAScript 6 Spec 11.8.6.1:
10057                 // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for Template Values
10058                 if (currChar === 13 /* carriageReturn */) {
10059                     contents += text.substring(start, pos);
10060                     pos++;
10061                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
10062                         pos++;
10063                     }
10064                     contents += "\n";
10065                     start = pos;
10066                     continue;
10067                 }
10068                 pos++;
10069             }
10070             ts.Debug.assert(resultingToken !== undefined);
10071             tokenValue = contents;
10072             return resultingToken;
10073         }
10074         function scanEscapeSequence(isTaggedTemplate) {
10075             var start = pos;
10076             pos++;
10077             if (pos >= end) {
10078                 error(ts.Diagnostics.Unexpected_end_of_text);
10079                 return "";
10080             }
10081             var ch = text.charCodeAt(pos);
10082             pos++;
10083             switch (ch) {
10084                 case 48 /* _0 */:
10085                     // '\01'
10086                     if (isTaggedTemplate && pos < end && isDigit(text.charCodeAt(pos))) {
10087                         pos++;
10088                         tokenFlags |= 2048 /* ContainsInvalidEscape */;
10089                         return text.substring(start, pos);
10090                     }
10091                     return "\0";
10092                 case 98 /* b */:
10093                     return "\b";
10094                 case 116 /* t */:
10095                     return "\t";
10096                 case 110 /* n */:
10097                     return "\n";
10098                 case 118 /* v */:
10099                     return "\v";
10100                 case 102 /* f */:
10101                     return "\f";
10102                 case 114 /* r */:
10103                     return "\r";
10104                 case 39 /* singleQuote */:
10105                     return "\'";
10106                 case 34 /* doubleQuote */:
10107                     return "\"";
10108                 case 117 /* u */:
10109                     if (isTaggedTemplate) {
10110                         // '\u' or '\u0' or '\u00' or '\u000'
10111                         for (var escapePos = pos; escapePos < pos + 4; escapePos++) {
10112                             if (escapePos < end && !isHexDigit(text.charCodeAt(escapePos)) && text.charCodeAt(escapePos) !== 123 /* openBrace */) {
10113                                 pos = escapePos;
10114                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
10115                                 return text.substring(start, pos);
10116                             }
10117                         }
10118                     }
10119                     // '\u{DDDDDDDD}'
10120                     if (pos < end && text.charCodeAt(pos) === 123 /* openBrace */) {
10121                         pos++;
10122                         // '\u{'
10123                         if (isTaggedTemplate && !isHexDigit(text.charCodeAt(pos))) {
10124                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10125                             return text.substring(start, pos);
10126                         }
10127                         if (isTaggedTemplate) {
10128                             var savePos = pos;
10129                             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10130                             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10131                             // '\u{Not Code Point' or '\u{CodePoint'
10132                             if (!isCodePoint(escapedValue) || text.charCodeAt(pos) !== 125 /* closeBrace */) {
10133                                 tokenFlags |= 2048 /* ContainsInvalidEscape */;
10134                                 return text.substring(start, pos);
10135                             }
10136                             else {
10137                                 pos = savePos;
10138                             }
10139                         }
10140                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10141                         return scanExtendedUnicodeEscape();
10142                     }
10143                     tokenFlags |= 1024 /* UnicodeEscape */;
10144                     // '\uDDDD'
10145                     return scanHexadecimalEscape(/*numDigits*/ 4);
10146                 case 120 /* x */:
10147                     if (isTaggedTemplate) {
10148                         if (!isHexDigit(text.charCodeAt(pos))) {
10149                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10150                             return text.substring(start, pos);
10151                         }
10152                         else if (!isHexDigit(text.charCodeAt(pos + 1))) {
10153                             pos++;
10154                             tokenFlags |= 2048 /* ContainsInvalidEscape */;
10155                             return text.substring(start, pos);
10156                         }
10157                     }
10158                     // '\xDD'
10159                     return scanHexadecimalEscape(/*numDigits*/ 2);
10160                 // when encountering a LineContinuation (i.e. a backslash and a line terminator sequence),
10161                 // the line terminator is interpreted to be "the empty code unit sequence".
10162                 case 13 /* carriageReturn */:
10163                     if (pos < end && text.charCodeAt(pos) === 10 /* lineFeed */) {
10164                         pos++;
10165                     }
10166                 // falls through
10167                 case 10 /* lineFeed */:
10168                 case 8232 /* lineSeparator */:
10169                 case 8233 /* paragraphSeparator */:
10170                     return "";
10171                 default:
10172                     return String.fromCharCode(ch);
10173             }
10174         }
10175         function scanHexadecimalEscape(numDigits) {
10176             var escapedValue = scanExactNumberOfHexDigits(numDigits, /*canHaveSeparators*/ false);
10177             if (escapedValue >= 0) {
10178                 return String.fromCharCode(escapedValue);
10179             }
10180             else {
10181                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10182                 return "";
10183             }
10184         }
10185         function scanExtendedUnicodeEscape() {
10186             var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10187             var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10188             var isInvalidExtendedEscape = false;
10189             // Validate the value of the digit
10190             if (escapedValue < 0) {
10191                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10192                 isInvalidExtendedEscape = true;
10193             }
10194             else if (escapedValue > 0x10FFFF) {
10195                 error(ts.Diagnostics.An_extended_Unicode_escape_value_must_be_between_0x0_and_0x10FFFF_inclusive);
10196                 isInvalidExtendedEscape = true;
10197             }
10198             if (pos >= end) {
10199                 error(ts.Diagnostics.Unexpected_end_of_text);
10200                 isInvalidExtendedEscape = true;
10201             }
10202             else if (text.charCodeAt(pos) === 125 /* closeBrace */) {
10203                 // Only swallow the following character up if it's a '}'.
10204                 pos++;
10205             }
10206             else {
10207                 error(ts.Diagnostics.Unterminated_Unicode_escape_sequence);
10208                 isInvalidExtendedEscape = true;
10209             }
10210             if (isInvalidExtendedEscape) {
10211                 return "";
10212             }
10213             return utf16EncodeAsString(escapedValue);
10214         }
10215         // Current character is known to be a backslash. Check for Unicode escape of the form '\uXXXX'
10216         // and return code point value if valid Unicode escape is found. Otherwise return -1.
10217         function peekUnicodeEscape() {
10218             if (pos + 5 < end && text.charCodeAt(pos + 1) === 117 /* u */) {
10219                 var start_1 = pos;
10220                 pos += 2;
10221                 var value = scanExactNumberOfHexDigits(4, /*canHaveSeparators*/ false);
10222                 pos = start_1;
10223                 return value;
10224             }
10225             return -1;
10226         }
10227         function peekExtendedUnicodeEscape() {
10228             if (languageVersion >= 2 /* ES2015 */ && codePointAt(text, pos + 1) === 117 /* u */ && codePointAt(text, pos + 2) === 123 /* openBrace */) {
10229                 var start_2 = pos;
10230                 pos += 3;
10231                 var escapedValueString = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ false);
10232                 var escapedValue = escapedValueString ? parseInt(escapedValueString, 16) : -1;
10233                 pos = start_2;
10234                 return escapedValue;
10235             }
10236             return -1;
10237         }
10238         function scanIdentifierParts() {
10239             var result = "";
10240             var start = pos;
10241             while (pos < end) {
10242                 var ch = codePointAt(text, pos);
10243                 if (isIdentifierPart(ch, languageVersion)) {
10244                     pos += charSize(ch);
10245                 }
10246                 else if (ch === 92 /* backslash */) {
10247                     ch = peekExtendedUnicodeEscape();
10248                     if (ch >= 0 && isIdentifierPart(ch, languageVersion)) {
10249                         pos += 3;
10250                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10251                         result += scanExtendedUnicodeEscape();
10252                         start = pos;
10253                         continue;
10254                     }
10255                     ch = peekUnicodeEscape();
10256                     if (!(ch >= 0 && isIdentifierPart(ch, languageVersion))) {
10257                         break;
10258                     }
10259                     tokenFlags |= 1024 /* UnicodeEscape */;
10260                     result += text.substring(start, pos);
10261                     result += utf16EncodeAsString(ch);
10262                     // Valid Unicode escape is always six characters
10263                     pos += 6;
10264                     start = pos;
10265                 }
10266                 else {
10267                     break;
10268                 }
10269             }
10270             result += text.substring(start, pos);
10271             return result;
10272         }
10273         function getIdentifierToken() {
10274             // Reserved words are between 2 and 12 characters long and start with a lowercase letter
10275             var len = tokenValue.length;
10276             if (len >= 2 && len <= 12) {
10277                 var ch = tokenValue.charCodeAt(0);
10278                 if (ch >= 97 /* a */ && ch <= 122 /* z */) {
10279                     var keyword = textToKeyword.get(tokenValue);
10280                     if (keyword !== undefined) {
10281                         return token = keyword;
10282                     }
10283                 }
10284             }
10285             return token = 78 /* Identifier */;
10286         }
10287         function scanBinaryOrOctalDigits(base) {
10288             var value = "";
10289             // For counting number of digits; Valid binaryIntegerLiteral must have at least one binary digit following B or b.
10290             // Similarly valid octalIntegerLiteral must have at least one octal digit following o or O.
10291             var separatorAllowed = false;
10292             var isPreviousTokenSeparator = false;
10293             while (true) {
10294                 var ch = text.charCodeAt(pos);
10295                 // Numeric separators are allowed anywhere within a numeric literal, except not at the beginning, or following another separator
10296                 if (ch === 95 /* _ */) {
10297                     tokenFlags |= 512 /* ContainsSeparator */;
10298                     if (separatorAllowed) {
10299                         separatorAllowed = false;
10300                         isPreviousTokenSeparator = true;
10301                     }
10302                     else if (isPreviousTokenSeparator) {
10303                         error(ts.Diagnostics.Multiple_consecutive_numeric_separators_are_not_permitted, pos, 1);
10304                     }
10305                     else {
10306                         error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos, 1);
10307                     }
10308                     pos++;
10309                     continue;
10310                 }
10311                 separatorAllowed = true;
10312                 if (!isDigit(ch) || ch - 48 /* _0 */ >= base) {
10313                     break;
10314                 }
10315                 value += text[pos];
10316                 pos++;
10317                 isPreviousTokenSeparator = false;
10318             }
10319             if (text.charCodeAt(pos - 1) === 95 /* _ */) {
10320                 // Literal ends with underscore - not allowed
10321                 error(ts.Diagnostics.Numeric_separators_are_not_allowed_here, pos - 1, 1);
10322             }
10323             return value;
10324         }
10325         function checkBigIntSuffix() {
10326             if (text.charCodeAt(pos) === 110 /* n */) {
10327                 tokenValue += "n";
10328                 // Use base 10 instead of base 2 or base 8 for shorter literals
10329                 if (tokenFlags & 384 /* BinaryOrOctalSpecifier */) {
10330                     tokenValue = ts.parsePseudoBigInt(tokenValue) + "n";
10331                 }
10332                 pos++;
10333                 return 9 /* BigIntLiteral */;
10334             }
10335             else { // not a bigint, so can convert to number in simplified form
10336                 // Number() may not support 0b or 0o, so use parseInt() instead
10337                 var numericValue = tokenFlags & 128 /* BinarySpecifier */
10338                     ? parseInt(tokenValue.slice(2), 2) // skip "0b"
10339                     : tokenFlags & 256 /* OctalSpecifier */
10340                         ? parseInt(tokenValue.slice(2), 8) // skip "0o"
10341                         : +tokenValue;
10342                 tokenValue = "" + numericValue;
10343                 return 8 /* NumericLiteral */;
10344             }
10345         }
10346         function scan() {
10347             var _a;
10348             startPos = pos;
10349             tokenFlags = 0 /* None */;
10350             var asteriskSeen = false;
10351             while (true) {
10352                 tokenPos = pos;
10353                 if (pos >= end) {
10354                     return token = 1 /* EndOfFileToken */;
10355                 }
10356                 var ch = codePointAt(text, pos);
10357                 // Special handling for shebang
10358                 if (ch === 35 /* hash */ && pos === 0 && isShebangTrivia(text, pos)) {
10359                     pos = scanShebangTrivia(text, pos);
10360                     if (skipTrivia) {
10361                         continue;
10362                     }
10363                     else {
10364                         return token = 6 /* ShebangTrivia */;
10365                     }
10366                 }
10367                 switch (ch) {
10368                     case 10 /* lineFeed */:
10369                     case 13 /* carriageReturn */:
10370                         tokenFlags |= 1 /* PrecedingLineBreak */;
10371                         if (skipTrivia) {
10372                             pos++;
10373                             continue;
10374                         }
10375                         else {
10376                             if (ch === 13 /* carriageReturn */ && pos + 1 < end && text.charCodeAt(pos + 1) === 10 /* lineFeed */) {
10377                                 // consume both CR and LF
10378                                 pos += 2;
10379                             }
10380                             else {
10381                                 pos++;
10382                             }
10383                             return token = 4 /* NewLineTrivia */;
10384                         }
10385                     case 9 /* tab */:
10386                     case 11 /* verticalTab */:
10387                     case 12 /* formFeed */:
10388                     case 32 /* space */:
10389                     case 160 /* nonBreakingSpace */:
10390                     case 5760 /* ogham */:
10391                     case 8192 /* enQuad */:
10392                     case 8193 /* emQuad */:
10393                     case 8194 /* enSpace */:
10394                     case 8195 /* emSpace */:
10395                     case 8196 /* threePerEmSpace */:
10396                     case 8197 /* fourPerEmSpace */:
10397                     case 8198 /* sixPerEmSpace */:
10398                     case 8199 /* figureSpace */:
10399                     case 8200 /* punctuationSpace */:
10400                     case 8201 /* thinSpace */:
10401                     case 8202 /* hairSpace */:
10402                     case 8203 /* zeroWidthSpace */:
10403                     case 8239 /* narrowNoBreakSpace */:
10404                     case 8287 /* mathematicalSpace */:
10405                     case 12288 /* ideographicSpace */:
10406                     case 65279 /* byteOrderMark */:
10407                         if (skipTrivia) {
10408                             pos++;
10409                             continue;
10410                         }
10411                         else {
10412                             while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
10413                                 pos++;
10414                             }
10415                             return token = 5 /* WhitespaceTrivia */;
10416                         }
10417                     case 33 /* exclamation */:
10418                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10419                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10420                                 return pos += 3, token = 37 /* ExclamationEqualsEqualsToken */;
10421                             }
10422                             return pos += 2, token = 35 /* ExclamationEqualsToken */;
10423                         }
10424                         pos++;
10425                         return token = 53 /* ExclamationToken */;
10426                     case 34 /* doubleQuote */:
10427                     case 39 /* singleQuote */:
10428                         tokenValue = scanString();
10429                         return token = 10 /* StringLiteral */;
10430                     case 96 /* backtick */:
10431                         return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ false);
10432                     case 37 /* percent */:
10433                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10434                             return pos += 2, token = 68 /* PercentEqualsToken */;
10435                         }
10436                         pos++;
10437                         return token = 44 /* PercentToken */;
10438                     case 38 /* ampersand */:
10439                         if (text.charCodeAt(pos + 1) === 38 /* ampersand */) {
10440                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10441                                 return pos += 3, token = 75 /* AmpersandAmpersandEqualsToken */;
10442                             }
10443                             return pos += 2, token = 55 /* AmpersandAmpersandToken */;
10444                         }
10445                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10446                             return pos += 2, token = 72 /* AmpersandEqualsToken */;
10447                         }
10448                         pos++;
10449                         return token = 50 /* AmpersandToken */;
10450                     case 40 /* openParen */:
10451                         pos++;
10452                         return token = 20 /* OpenParenToken */;
10453                     case 41 /* closeParen */:
10454                         pos++;
10455                         return token = 21 /* CloseParenToken */;
10456                     case 42 /* asterisk */:
10457                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10458                             return pos += 2, token = 65 /* AsteriskEqualsToken */;
10459                         }
10460                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
10461                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10462                                 return pos += 3, token = 66 /* AsteriskAsteriskEqualsToken */;
10463                             }
10464                             return pos += 2, token = 42 /* AsteriskAsteriskToken */;
10465                         }
10466                         pos++;
10467                         if (inJSDocType && !asteriskSeen && (tokenFlags & 1 /* PrecedingLineBreak */)) {
10468                             // decoration at the start of a JSDoc comment line
10469                             asteriskSeen = true;
10470                             continue;
10471                         }
10472                         return token = 41 /* AsteriskToken */;
10473                     case 43 /* plus */:
10474                         if (text.charCodeAt(pos + 1) === 43 /* plus */) {
10475                             return pos += 2, token = 45 /* PlusPlusToken */;
10476                         }
10477                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10478                             return pos += 2, token = 63 /* PlusEqualsToken */;
10479                         }
10480                         pos++;
10481                         return token = 39 /* PlusToken */;
10482                     case 44 /* comma */:
10483                         pos++;
10484                         return token = 27 /* CommaToken */;
10485                     case 45 /* minus */:
10486                         if (text.charCodeAt(pos + 1) === 45 /* minus */) {
10487                             return pos += 2, token = 46 /* MinusMinusToken */;
10488                         }
10489                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10490                             return pos += 2, token = 64 /* MinusEqualsToken */;
10491                         }
10492                         pos++;
10493                         return token = 40 /* MinusToken */;
10494                     case 46 /* dot */:
10495                         if (isDigit(text.charCodeAt(pos + 1))) {
10496                             tokenValue = scanNumber().value;
10497                             return token = 8 /* NumericLiteral */;
10498                         }
10499                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && text.charCodeAt(pos + 2) === 46 /* dot */) {
10500                             return pos += 3, token = 25 /* DotDotDotToken */;
10501                         }
10502                         pos++;
10503                         return token = 24 /* DotToken */;
10504                     case 47 /* slash */:
10505                         // Single-line comment
10506                         if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10507                             pos += 2;
10508                             while (pos < end) {
10509                                 if (isLineBreak(text.charCodeAt(pos))) {
10510                                     break;
10511                                 }
10512                                 pos++;
10513                             }
10514                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(tokenPos, pos), commentDirectiveRegExSingleLine, tokenPos);
10515                             if (skipTrivia) {
10516                                 continue;
10517                             }
10518                             else {
10519                                 return token = 2 /* SingleLineCommentTrivia */;
10520                             }
10521                         }
10522                         // Multi-line comment
10523                         if (text.charCodeAt(pos + 1) === 42 /* asterisk */) {
10524                             pos += 2;
10525                             if (text.charCodeAt(pos) === 42 /* asterisk */ && text.charCodeAt(pos + 1) !== 47 /* slash */) {
10526                                 tokenFlags |= 2 /* PrecedingJSDocComment */;
10527                             }
10528                             var commentClosed = false;
10529                             var lastLineStart = tokenPos;
10530                             while (pos < end) {
10531                                 var ch_1 = text.charCodeAt(pos);
10532                                 if (ch_1 === 42 /* asterisk */ && text.charCodeAt(pos + 1) === 47 /* slash */) {
10533                                     pos += 2;
10534                                     commentClosed = true;
10535                                     break;
10536                                 }
10537                                 pos++;
10538                                 if (isLineBreak(ch_1)) {
10539                                     lastLineStart = pos;
10540                                     tokenFlags |= 1 /* PrecedingLineBreak */;
10541                                 }
10542                             }
10543                             commentDirectives = appendIfCommentDirective(commentDirectives, text.slice(lastLineStart, pos), commentDirectiveRegExMultiLine, lastLineStart);
10544                             if (!commentClosed) {
10545                                 error(ts.Diagnostics.Asterisk_Slash_expected);
10546                             }
10547                             if (skipTrivia) {
10548                                 continue;
10549                             }
10550                             else {
10551                                 if (!commentClosed) {
10552                                     tokenFlags |= 4 /* Unterminated */;
10553                                 }
10554                                 return token = 3 /* MultiLineCommentTrivia */;
10555                             }
10556                         }
10557                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10558                             return pos += 2, token = 67 /* SlashEqualsToken */;
10559                         }
10560                         pos++;
10561                         return token = 43 /* SlashToken */;
10562                     case 48 /* _0 */:
10563                         if (pos + 2 < end && (text.charCodeAt(pos + 1) === 88 /* X */ || text.charCodeAt(pos + 1) === 120 /* x */)) {
10564                             pos += 2;
10565                             tokenValue = scanMinimumNumberOfHexDigits(1, /*canHaveSeparators*/ true);
10566                             if (!tokenValue) {
10567                                 error(ts.Diagnostics.Hexadecimal_digit_expected);
10568                                 tokenValue = "0";
10569                             }
10570                             tokenValue = "0x" + tokenValue;
10571                             tokenFlags |= 64 /* HexSpecifier */;
10572                             return token = checkBigIntSuffix();
10573                         }
10574                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 66 /* B */ || text.charCodeAt(pos + 1) === 98 /* b */)) {
10575                             pos += 2;
10576                             tokenValue = scanBinaryOrOctalDigits(/* base */ 2);
10577                             if (!tokenValue) {
10578                                 error(ts.Diagnostics.Binary_digit_expected);
10579                                 tokenValue = "0";
10580                             }
10581                             tokenValue = "0b" + tokenValue;
10582                             tokenFlags |= 128 /* BinarySpecifier */;
10583                             return token = checkBigIntSuffix();
10584                         }
10585                         else if (pos + 2 < end && (text.charCodeAt(pos + 1) === 79 /* O */ || text.charCodeAt(pos + 1) === 111 /* o */)) {
10586                             pos += 2;
10587                             tokenValue = scanBinaryOrOctalDigits(/* base */ 8);
10588                             if (!tokenValue) {
10589                                 error(ts.Diagnostics.Octal_digit_expected);
10590                                 tokenValue = "0";
10591                             }
10592                             tokenValue = "0o" + tokenValue;
10593                             tokenFlags |= 256 /* OctalSpecifier */;
10594                             return token = checkBigIntSuffix();
10595                         }
10596                         // Try to parse as an octal
10597                         if (pos + 1 < end && isOctalDigit(text.charCodeAt(pos + 1))) {
10598                             tokenValue = "" + scanOctalDigits();
10599                             tokenFlags |= 32 /* Octal */;
10600                             return token = 8 /* NumericLiteral */;
10601                         }
10602                     // This fall-through is a deviation from the EcmaScript grammar. The grammar says that a leading zero
10603                     // can only be followed by an octal digit, a dot, or the end of the number literal. However, we are being
10604                     // permissive and allowing decimal digits of the form 08* and 09* (which many browsers also do).
10605                     // falls through
10606                     case 49 /* _1 */:
10607                     case 50 /* _2 */:
10608                     case 51 /* _3 */:
10609                     case 52 /* _4 */:
10610                     case 53 /* _5 */:
10611                     case 54 /* _6 */:
10612                     case 55 /* _7 */:
10613                     case 56 /* _8 */:
10614                     case 57 /* _9 */:
10615                         (_a = scanNumber(), token = _a.type, tokenValue = _a.value);
10616                         return token;
10617                     case 58 /* colon */:
10618                         pos++;
10619                         return token = 58 /* ColonToken */;
10620                     case 59 /* semicolon */:
10621                         pos++;
10622                         return token = 26 /* SemicolonToken */;
10623                     case 60 /* lessThan */:
10624                         if (isConflictMarkerTrivia(text, pos)) {
10625                             pos = scanConflictMarkerTrivia(text, pos, error);
10626                             if (skipTrivia) {
10627                                 continue;
10628                             }
10629                             else {
10630                                 return token = 7 /* ConflictMarkerTrivia */;
10631                             }
10632                         }
10633                         if (text.charCodeAt(pos + 1) === 60 /* lessThan */) {
10634                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10635                                 return pos += 3, token = 69 /* LessThanLessThanEqualsToken */;
10636                             }
10637                             return pos += 2, token = 47 /* LessThanLessThanToken */;
10638                         }
10639                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10640                             return pos += 2, token = 32 /* LessThanEqualsToken */;
10641                         }
10642                         if (languageVariant === 1 /* JSX */ &&
10643                             text.charCodeAt(pos + 1) === 47 /* slash */ &&
10644                             text.charCodeAt(pos + 2) !== 42 /* asterisk */) {
10645                             return pos += 2, token = 30 /* LessThanSlashToken */;
10646                         }
10647                         pos++;
10648                         return token = 29 /* LessThanToken */;
10649                     case 61 /* equals */:
10650                         if (isConflictMarkerTrivia(text, pos)) {
10651                             pos = scanConflictMarkerTrivia(text, pos, error);
10652                             if (skipTrivia) {
10653                                 continue;
10654                             }
10655                             else {
10656                                 return token = 7 /* ConflictMarkerTrivia */;
10657                             }
10658                         }
10659                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10660                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10661                                 return pos += 3, token = 36 /* EqualsEqualsEqualsToken */;
10662                             }
10663                             return pos += 2, token = 34 /* EqualsEqualsToken */;
10664                         }
10665                         if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
10666                             return pos += 2, token = 38 /* EqualsGreaterThanToken */;
10667                         }
10668                         pos++;
10669                         return token = 62 /* EqualsToken */;
10670                     case 62 /* greaterThan */:
10671                         if (isConflictMarkerTrivia(text, pos)) {
10672                             pos = scanConflictMarkerTrivia(text, pos, error);
10673                             if (skipTrivia) {
10674                                 continue;
10675                             }
10676                             else {
10677                                 return token = 7 /* ConflictMarkerTrivia */;
10678                             }
10679                         }
10680                         pos++;
10681                         return token = 31 /* GreaterThanToken */;
10682                     case 63 /* question */:
10683                         if (text.charCodeAt(pos + 1) === 46 /* dot */ && !isDigit(text.charCodeAt(pos + 2))) {
10684                             return pos += 2, token = 28 /* QuestionDotToken */;
10685                         }
10686                         if (text.charCodeAt(pos + 1) === 63 /* question */) {
10687                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10688                                 return pos += 3, token = 76 /* QuestionQuestionEqualsToken */;
10689                             }
10690                             return pos += 2, token = 60 /* QuestionQuestionToken */;
10691                         }
10692                         pos++;
10693                         return token = 57 /* QuestionToken */;
10694                     case 91 /* openBracket */:
10695                         pos++;
10696                         return token = 22 /* OpenBracketToken */;
10697                     case 93 /* closeBracket */:
10698                         pos++;
10699                         return token = 23 /* CloseBracketToken */;
10700                     case 94 /* caret */:
10701                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10702                             return pos += 2, token = 77 /* CaretEqualsToken */;
10703                         }
10704                         pos++;
10705                         return token = 52 /* CaretToken */;
10706                     case 123 /* openBrace */:
10707                         pos++;
10708                         return token = 18 /* OpenBraceToken */;
10709                     case 124 /* bar */:
10710                         if (isConflictMarkerTrivia(text, pos)) {
10711                             pos = scanConflictMarkerTrivia(text, pos, error);
10712                             if (skipTrivia) {
10713                                 continue;
10714                             }
10715                             else {
10716                                 return token = 7 /* ConflictMarkerTrivia */;
10717                             }
10718                         }
10719                         if (text.charCodeAt(pos + 1) === 124 /* bar */) {
10720                             if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10721                                 return pos += 3, token = 74 /* BarBarEqualsToken */;
10722                             }
10723                             return pos += 2, token = 56 /* BarBarToken */;
10724                         }
10725                         if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10726                             return pos += 2, token = 73 /* BarEqualsToken */;
10727                         }
10728                         pos++;
10729                         return token = 51 /* BarToken */;
10730                     case 125 /* closeBrace */:
10731                         pos++;
10732                         return token = 19 /* CloseBraceToken */;
10733                     case 126 /* tilde */:
10734                         pos++;
10735                         return token = 54 /* TildeToken */;
10736                     case 64 /* at */:
10737                         pos++;
10738                         return token = 59 /* AtToken */;
10739                     case 92 /* backslash */:
10740                         var extendedCookedChar = peekExtendedUnicodeEscape();
10741                         if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
10742                             pos += 3;
10743                             tokenFlags |= 8 /* ExtendedUnicodeEscape */;
10744                             tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
10745                             return token = getIdentifierToken();
10746                         }
10747                         var cookedChar = peekUnicodeEscape();
10748                         if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
10749                             pos += 6;
10750                             tokenFlags |= 1024 /* UnicodeEscape */;
10751                             tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
10752                             return token = getIdentifierToken();
10753                         }
10754                         error(ts.Diagnostics.Invalid_character);
10755                         pos++;
10756                         return token = 0 /* Unknown */;
10757                     case 35 /* hash */:
10758                         if (pos !== 0 && text[pos + 1] === "!") {
10759                             error(ts.Diagnostics.can_only_be_used_at_the_start_of_a_file);
10760                             pos++;
10761                             return token = 0 /* Unknown */;
10762                         }
10763                         pos++;
10764                         if (isIdentifierStart(ch = text.charCodeAt(pos), languageVersion)) {
10765                             pos++;
10766                             while (pos < end && isIdentifierPart(ch = text.charCodeAt(pos), languageVersion))
10767                                 pos++;
10768                             tokenValue = text.substring(tokenPos, pos);
10769                             if (ch === 92 /* backslash */) {
10770                                 tokenValue += scanIdentifierParts();
10771                             }
10772                         }
10773                         else {
10774                             tokenValue = "#";
10775                             error(ts.Diagnostics.Invalid_character);
10776                         }
10777                         return token = 79 /* PrivateIdentifier */;
10778                     default:
10779                         if (isIdentifierStart(ch, languageVersion)) {
10780                             pos += charSize(ch);
10781                             while (pos < end && isIdentifierPart(ch = codePointAt(text, pos), languageVersion))
10782                                 pos += charSize(ch);
10783                             tokenValue = text.substring(tokenPos, pos);
10784                             if (ch === 92 /* backslash */) {
10785                                 tokenValue += scanIdentifierParts();
10786                             }
10787                             return token = getIdentifierToken();
10788                         }
10789                         else if (isWhiteSpaceSingleLine(ch)) {
10790                             pos += charSize(ch);
10791                             continue;
10792                         }
10793                         else if (isLineBreak(ch)) {
10794                             tokenFlags |= 1 /* PrecedingLineBreak */;
10795                             pos += charSize(ch);
10796                             continue;
10797                         }
10798                         error(ts.Diagnostics.Invalid_character);
10799                         pos += charSize(ch);
10800                         return token = 0 /* Unknown */;
10801                 }
10802             }
10803         }
10804         function reScanGreaterToken() {
10805             if (token === 31 /* GreaterThanToken */) {
10806                 if (text.charCodeAt(pos) === 62 /* greaterThan */) {
10807                     if (text.charCodeAt(pos + 1) === 62 /* greaterThan */) {
10808                         if (text.charCodeAt(pos + 2) === 61 /* equals */) {
10809                             return pos += 3, token = 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */;
10810                         }
10811                         return pos += 2, token = 49 /* GreaterThanGreaterThanGreaterThanToken */;
10812                     }
10813                     if (text.charCodeAt(pos + 1) === 61 /* equals */) {
10814                         return pos += 2, token = 70 /* GreaterThanGreaterThanEqualsToken */;
10815                     }
10816                     pos++;
10817                     return token = 48 /* GreaterThanGreaterThanToken */;
10818                 }
10819                 if (text.charCodeAt(pos) === 61 /* equals */) {
10820                     pos++;
10821                     return token = 33 /* GreaterThanEqualsToken */;
10822                 }
10823             }
10824             return token;
10825         }
10826         function reScanAsteriskEqualsToken() {
10827             ts.Debug.assert(token === 65 /* AsteriskEqualsToken */, "'reScanAsteriskEqualsToken' should only be called on a '*='");
10828             pos = tokenPos + 1;
10829             return token = 62 /* EqualsToken */;
10830         }
10831         function reScanSlashToken() {
10832             if (token === 43 /* SlashToken */ || token === 67 /* SlashEqualsToken */) {
10833                 var p = tokenPos + 1;
10834                 var inEscape = false;
10835                 var inCharacterClass = false;
10836                 while (true) {
10837                     // If we reach the end of a file, or hit a newline, then this is an unterminated
10838                     // regex.  Report error and return what we have so far.
10839                     if (p >= end) {
10840                         tokenFlags |= 4 /* Unterminated */;
10841                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
10842                         break;
10843                     }
10844                     var ch = text.charCodeAt(p);
10845                     if (isLineBreak(ch)) {
10846                         tokenFlags |= 4 /* Unterminated */;
10847                         error(ts.Diagnostics.Unterminated_regular_expression_literal);
10848                         break;
10849                     }
10850                     if (inEscape) {
10851                         // Parsing an escape character;
10852                         // reset the flag and just advance to the next char.
10853                         inEscape = false;
10854                     }
10855                     else if (ch === 47 /* slash */ && !inCharacterClass) {
10856                         // A slash within a character class is permissible,
10857                         // but in general it signals the end of the regexp literal.
10858                         p++;
10859                         break;
10860                     }
10861                     else if (ch === 91 /* openBracket */) {
10862                         inCharacterClass = true;
10863                     }
10864                     else if (ch === 92 /* backslash */) {
10865                         inEscape = true;
10866                     }
10867                     else if (ch === 93 /* closeBracket */) {
10868                         inCharacterClass = false;
10869                     }
10870                     p++;
10871                 }
10872                 while (p < end && isIdentifierPart(text.charCodeAt(p), languageVersion)) {
10873                     p++;
10874                 }
10875                 pos = p;
10876                 tokenValue = text.substring(tokenPos, pos);
10877                 token = 13 /* RegularExpressionLiteral */;
10878             }
10879             return token;
10880         }
10881         function appendIfCommentDirective(commentDirectives, text, commentDirectiveRegEx, lineStart) {
10882             var type = getDirectiveFromComment(text, commentDirectiveRegEx);
10883             if (type === undefined) {
10884                 return commentDirectives;
10885             }
10886             return ts.append(commentDirectives, {
10887                 range: { pos: lineStart, end: pos },
10888                 type: type,
10889             });
10890         }
10891         function getDirectiveFromComment(text, commentDirectiveRegEx) {
10892             var match = commentDirectiveRegEx.exec(text);
10893             if (!match) {
10894                 return undefined;
10895             }
10896             switch (match[1]) {
10897                 case "ts-expect-error":
10898                     return 0 /* ExpectError */;
10899                 case "ts-ignore":
10900                     return 1 /* Ignore */;
10901             }
10902             return undefined;
10903         }
10904         /**
10905          * Unconditionally back up and scan a template expression portion.
10906          */
10907         function reScanTemplateToken(isTaggedTemplate) {
10908             ts.Debug.assert(token === 19 /* CloseBraceToken */, "'reScanTemplateToken' should only be called on a '}'");
10909             pos = tokenPos;
10910             return token = scanTemplateAndSetTokenValue(isTaggedTemplate);
10911         }
10912         function reScanTemplateHeadOrNoSubstitutionTemplate() {
10913             pos = tokenPos;
10914             return token = scanTemplateAndSetTokenValue(/* isTaggedTemplate */ true);
10915         }
10916         function reScanJsxToken() {
10917             pos = tokenPos = startPos;
10918             return token = scanJsxToken();
10919         }
10920         function reScanLessThanToken() {
10921             if (token === 47 /* LessThanLessThanToken */) {
10922                 pos = tokenPos + 1;
10923                 return token = 29 /* LessThanToken */;
10924             }
10925             return token;
10926         }
10927         function reScanQuestionToken() {
10928             ts.Debug.assert(token === 60 /* QuestionQuestionToken */, "'reScanQuestionToken' should only be called on a '??'");
10929             pos = tokenPos + 1;
10930             return token = 57 /* QuestionToken */;
10931         }
10932         function scanJsxToken() {
10933             startPos = tokenPos = pos;
10934             if (pos >= end) {
10935                 return token = 1 /* EndOfFileToken */;
10936             }
10937             var char = text.charCodeAt(pos);
10938             if (char === 60 /* lessThan */) {
10939                 if (text.charCodeAt(pos + 1) === 47 /* slash */) {
10940                     pos += 2;
10941                     return token = 30 /* LessThanSlashToken */;
10942                 }
10943                 pos++;
10944                 return token = 29 /* LessThanToken */;
10945             }
10946             if (char === 123 /* openBrace */) {
10947                 pos++;
10948                 return token = 18 /* OpenBraceToken */;
10949             }
10950             // First non-whitespace character on this line.
10951             var firstNonWhitespace = 0;
10952             var lastNonWhitespace = -1;
10953             // These initial values are special because the first line is:
10954             // firstNonWhitespace = 0 to indicate that we want leading whitespace,
10955             while (pos < end) {
10956                 // We want to keep track of the last non-whitespace (but including
10957                 // newlines character for hitting the end of the JSX Text region)
10958                 if (!isWhiteSpaceSingleLine(char)) {
10959                     lastNonWhitespace = pos;
10960                 }
10961                 char = text.charCodeAt(pos);
10962                 if (char === 123 /* openBrace */) {
10963                     break;
10964                 }
10965                 if (char === 60 /* lessThan */) {
10966                     if (isConflictMarkerTrivia(text, pos)) {
10967                         pos = scanConflictMarkerTrivia(text, pos, error);
10968                         return token = 7 /* ConflictMarkerTrivia */;
10969                     }
10970                     break;
10971                 }
10972                 if (char === 62 /* greaterThan */) {
10973                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_gt, pos, 1);
10974                 }
10975                 if (char === 125 /* closeBrace */) {
10976                     error(ts.Diagnostics.Unexpected_token_Did_you_mean_or_rbrace, pos, 1);
10977                 }
10978                 if (lastNonWhitespace > 0)
10979                     lastNonWhitespace++;
10980                 // FirstNonWhitespace is 0, then we only see whitespaces so far. If we see a linebreak, we want to ignore that whitespaces.
10981                 // i.e (- : whitespace)
10982                 //      <div>----
10983                 //      </div> becomes <div></div>
10984                 //
10985                 //      <div>----</div> becomes <div>----</div>
10986                 if (isLineBreak(char) && firstNonWhitespace === 0) {
10987                     firstNonWhitespace = -1;
10988                 }
10989                 else if (!isWhiteSpaceLike(char)) {
10990                     firstNonWhitespace = pos;
10991                 }
10992                 pos++;
10993             }
10994             var endPosition = lastNonWhitespace === -1 ? pos : lastNonWhitespace;
10995             tokenValue = text.substring(startPos, endPosition);
10996             return firstNonWhitespace === -1 ? 12 /* JsxTextAllWhiteSpaces */ : 11 /* JsxText */;
10997         }
10998         // Scans a JSX identifier; these differ from normal identifiers in that
10999         // they allow dashes
11000         function scanJsxIdentifier() {
11001             if (tokenIsIdentifierOrKeyword(token)) {
11002                 // An identifier or keyword has already been parsed - check for a `-` and then append it and everything after it to the token
11003                 // Do note that this means that `scanJsxIdentifier` effectively _mutates_ the visible token without advancing to a new token
11004                 // Any caller should be expecting this behavior and should only read the pos or token value after calling it.
11005                 while (pos < end) {
11006                     var ch = text.charCodeAt(pos);
11007                     if (ch === 45 /* minus */) {
11008                         tokenValue += "-";
11009                         pos++;
11010                         continue;
11011                     }
11012                     var oldPos = pos;
11013                     tokenValue += scanIdentifierParts(); // reuse `scanIdentifierParts` so unicode escapes are handled
11014                     if (pos === oldPos) {
11015                         break;
11016                     }
11017                 }
11018             }
11019             return token;
11020         }
11021         function scanJsxAttributeValue() {
11022             startPos = pos;
11023             switch (text.charCodeAt(pos)) {
11024                 case 34 /* doubleQuote */:
11025                 case 39 /* singleQuote */:
11026                     tokenValue = scanString(/*jsxAttributeString*/ true);
11027                     return token = 10 /* StringLiteral */;
11028                 default:
11029                     // If this scans anything other than `{`, it's a parse error.
11030                     return scan();
11031             }
11032         }
11033         function reScanJsxAttributeValue() {
11034             pos = tokenPos = startPos;
11035             return scanJsxAttributeValue();
11036         }
11037         function scanJsDocToken() {
11038             startPos = tokenPos = pos;
11039             tokenFlags = 0 /* None */;
11040             if (pos >= end) {
11041                 return token = 1 /* EndOfFileToken */;
11042             }
11043             var ch = codePointAt(text, pos);
11044             pos += charSize(ch);
11045             switch (ch) {
11046                 case 9 /* tab */:
11047                 case 11 /* verticalTab */:
11048                 case 12 /* formFeed */:
11049                 case 32 /* space */:
11050                     while (pos < end && isWhiteSpaceSingleLine(text.charCodeAt(pos))) {
11051                         pos++;
11052                     }
11053                     return token = 5 /* WhitespaceTrivia */;
11054                 case 64 /* at */:
11055                     return token = 59 /* AtToken */;
11056                 case 13 /* carriageReturn */:
11057                     if (text.charCodeAt(pos) === 10 /* lineFeed */) {
11058                         pos++;
11059                     }
11060                 // falls through
11061                 case 10 /* lineFeed */:
11062                     tokenFlags |= 1 /* PrecedingLineBreak */;
11063                     return token = 4 /* NewLineTrivia */;
11064                 case 42 /* asterisk */:
11065                     return token = 41 /* AsteriskToken */;
11066                 case 123 /* openBrace */:
11067                     return token = 18 /* OpenBraceToken */;
11068                 case 125 /* closeBrace */:
11069                     return token = 19 /* CloseBraceToken */;
11070                 case 91 /* openBracket */:
11071                     return token = 22 /* OpenBracketToken */;
11072                 case 93 /* closeBracket */:
11073                     return token = 23 /* CloseBracketToken */;
11074                 case 60 /* lessThan */:
11075                     return token = 29 /* LessThanToken */;
11076                 case 62 /* greaterThan */:
11077                     return token = 31 /* GreaterThanToken */;
11078                 case 61 /* equals */:
11079                     return token = 62 /* EqualsToken */;
11080                 case 44 /* comma */:
11081                     return token = 27 /* CommaToken */;
11082                 case 46 /* dot */:
11083                     return token = 24 /* DotToken */;
11084                 case 96 /* backtick */:
11085                     return token = 61 /* BacktickToken */;
11086                 case 92 /* backslash */:
11087                     pos--;
11088                     var extendedCookedChar = peekExtendedUnicodeEscape();
11089                     if (extendedCookedChar >= 0 && isIdentifierStart(extendedCookedChar, languageVersion)) {
11090                         pos += 3;
11091                         tokenFlags |= 8 /* ExtendedUnicodeEscape */;
11092                         tokenValue = scanExtendedUnicodeEscape() + scanIdentifierParts();
11093                         return token = getIdentifierToken();
11094                     }
11095                     var cookedChar = peekUnicodeEscape();
11096                     if (cookedChar >= 0 && isIdentifierStart(cookedChar, languageVersion)) {
11097                         pos += 6;
11098                         tokenFlags |= 1024 /* UnicodeEscape */;
11099                         tokenValue = String.fromCharCode(cookedChar) + scanIdentifierParts();
11100                         return token = getIdentifierToken();
11101                     }
11102                     pos++;
11103                     return token = 0 /* Unknown */;
11104             }
11105             if (isIdentifierStart(ch, languageVersion)) {
11106                 var char = ch;
11107                 while (pos < end && isIdentifierPart(char = codePointAt(text, pos), languageVersion) || text.charCodeAt(pos) === 45 /* minus */)
11108                     pos += charSize(char);
11109                 tokenValue = text.substring(tokenPos, pos);
11110                 if (char === 92 /* backslash */) {
11111                     tokenValue += scanIdentifierParts();
11112                 }
11113                 return token = getIdentifierToken();
11114             }
11115             else {
11116                 return token = 0 /* Unknown */;
11117             }
11118         }
11119         function speculationHelper(callback, isLookahead) {
11120             var savePos = pos;
11121             var saveStartPos = startPos;
11122             var saveTokenPos = tokenPos;
11123             var saveToken = token;
11124             var saveTokenValue = tokenValue;
11125             var saveTokenFlags = tokenFlags;
11126             var result = callback();
11127             // If our callback returned something 'falsy' or we're just looking ahead,
11128             // then unconditionally restore us to where we were.
11129             if (!result || isLookahead) {
11130                 pos = savePos;
11131                 startPos = saveStartPos;
11132                 tokenPos = saveTokenPos;
11133                 token = saveToken;
11134                 tokenValue = saveTokenValue;
11135                 tokenFlags = saveTokenFlags;
11136             }
11137             return result;
11138         }
11139         function scanRange(start, length, callback) {
11140             var saveEnd = end;
11141             var savePos = pos;
11142             var saveStartPos = startPos;
11143             var saveTokenPos = tokenPos;
11144             var saveToken = token;
11145             var saveTokenValue = tokenValue;
11146             var saveTokenFlags = tokenFlags;
11147             var saveErrorExpectations = commentDirectives;
11148             setText(text, start, length);
11149             var result = callback();
11150             end = saveEnd;
11151             pos = savePos;
11152             startPos = saveStartPos;
11153             tokenPos = saveTokenPos;
11154             token = saveToken;
11155             tokenValue = saveTokenValue;
11156             tokenFlags = saveTokenFlags;
11157             commentDirectives = saveErrorExpectations;
11158             return result;
11159         }
11160         function lookAhead(callback) {
11161             return speculationHelper(callback, /*isLookahead*/ true);
11162         }
11163         function tryScan(callback) {
11164             return speculationHelper(callback, /*isLookahead*/ false);
11165         }
11166         function getText() {
11167             return text;
11168         }
11169         function clearCommentDirectives() {
11170             commentDirectives = undefined;
11171         }
11172         function setText(newText, start, length) {
11173             text = newText || "";
11174             end = length === undefined ? text.length : start + length;
11175             setTextPos(start || 0);
11176         }
11177         function setOnError(errorCallback) {
11178             onError = errorCallback;
11179         }
11180         function setScriptTarget(scriptTarget) {
11181             languageVersion = scriptTarget;
11182         }
11183         function setLanguageVariant(variant) {
11184             languageVariant = variant;
11185         }
11186         function setTextPos(textPos) {
11187             ts.Debug.assert(textPos >= 0);
11188             pos = textPos;
11189             startPos = textPos;
11190             tokenPos = textPos;
11191             token = 0 /* Unknown */;
11192             tokenValue = undefined;
11193             tokenFlags = 0 /* None */;
11194         }
11195         function setInJSDocType(inType) {
11196             inJSDocType += inType ? 1 : -1;
11197         }
11198     }
11199     ts.createScanner = createScanner;
11200     /* @internal */
11201     var codePointAt = String.prototype.codePointAt ? function (s, i) { return s.codePointAt(i); } : function codePointAt(str, i) {
11202         // from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/codePointAt
11203         var size = str.length;
11204         // Account for out-of-bounds indices:
11205         if (i < 0 || i >= size) {
11206             return undefined; // String.codePointAt returns `undefined` for OOB indexes
11207         }
11208         // Get the first code unit
11209         var first = str.charCodeAt(i);
11210         // check if it’s the start of a surrogate pair
11211         if (first >= 0xD800 && first <= 0xDBFF && size > i + 1) { // high surrogate and there is a next code unit
11212             var second = str.charCodeAt(i + 1);
11213             if (second >= 0xDC00 && second <= 0xDFFF) { // low surrogate
11214                 // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae
11215                 return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000;
11216             }
11217         }
11218         return first;
11219     };
11220     /* @internal */
11221     function charSize(ch) {
11222         if (ch >= 0x10000) {
11223             return 2;
11224         }
11225         return 1;
11226     }
11227     // Derived from the 10.1.1 UTF16Encoding of the ES6 Spec.
11228     function utf16EncodeAsStringFallback(codePoint) {
11229         ts.Debug.assert(0x0 <= codePoint && codePoint <= 0x10FFFF);
11230         if (codePoint <= 65535) {
11231             return String.fromCharCode(codePoint);
11232         }
11233         var codeUnit1 = Math.floor((codePoint - 65536) / 1024) + 0xD800;
11234         var codeUnit2 = ((codePoint - 65536) % 1024) + 0xDC00;
11235         return String.fromCharCode(codeUnit1, codeUnit2);
11236     }
11237     var utf16EncodeAsStringWorker = String.fromCodePoint ? function (codePoint) { return String.fromCodePoint(codePoint); } : utf16EncodeAsStringFallback;
11238     /* @internal */
11239     function utf16EncodeAsString(codePoint) {
11240         return utf16EncodeAsStringWorker(codePoint);
11241     }
11242     ts.utf16EncodeAsString = utf16EncodeAsString;
11243 })(ts || (ts = {}));
11244 var ts;
11245 (function (ts) {
11246     function isExternalModuleNameRelative(moduleName) {
11247         // TypeScript 1.0 spec (April 2014): 11.2.1
11248         // An external module name is "relative" if the first term is "." or "..".
11249         // 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.
11250         return ts.pathIsRelative(moduleName) || ts.isRootedDiskPath(moduleName);
11251     }
11252     ts.isExternalModuleNameRelative = isExternalModuleNameRelative;
11253     function sortAndDeduplicateDiagnostics(diagnostics) {
11254         return ts.sortAndDeduplicate(diagnostics, ts.compareDiagnostics);
11255     }
11256     ts.sortAndDeduplicateDiagnostics = sortAndDeduplicateDiagnostics;
11257     function getDefaultLibFileName(options) {
11258         switch (options.target) {
11259             case 99 /* ESNext */:
11260                 return "lib.esnext.full.d.ts";
11261             case 7 /* ES2020 */:
11262                 return "lib.es2020.full.d.ts";
11263             case 6 /* ES2019 */:
11264                 return "lib.es2019.full.d.ts";
11265             case 5 /* ES2018 */:
11266                 return "lib.es2018.full.d.ts";
11267             case 4 /* ES2017 */:
11268                 return "lib.es2017.full.d.ts";
11269             case 3 /* ES2016 */:
11270                 return "lib.es2016.full.d.ts";
11271             case 2 /* ES2015 */:
11272                 return "lib.es6.d.ts"; // We don't use lib.es2015.full.d.ts due to breaking change.
11273             default:
11274                 return "lib.d.ts";
11275         }
11276     }
11277     ts.getDefaultLibFileName = getDefaultLibFileName;
11278     function textSpanEnd(span) {
11279         return span.start + span.length;
11280     }
11281     ts.textSpanEnd = textSpanEnd;
11282     function textSpanIsEmpty(span) {
11283         return span.length === 0;
11284     }
11285     ts.textSpanIsEmpty = textSpanIsEmpty;
11286     function textSpanContainsPosition(span, position) {
11287         return position >= span.start && position < textSpanEnd(span);
11288     }
11289     ts.textSpanContainsPosition = textSpanContainsPosition;
11290     /* @internal */
11291     function textRangeContainsPositionInclusive(span, position) {
11292         return position >= span.pos && position <= span.end;
11293     }
11294     ts.textRangeContainsPositionInclusive = textRangeContainsPositionInclusive;
11295     // Returns true if 'span' contains 'other'.
11296     function textSpanContainsTextSpan(span, other) {
11297         return other.start >= span.start && textSpanEnd(other) <= textSpanEnd(span);
11298     }
11299     ts.textSpanContainsTextSpan = textSpanContainsTextSpan;
11300     function textSpanOverlapsWith(span, other) {
11301         return textSpanOverlap(span, other) !== undefined;
11302     }
11303     ts.textSpanOverlapsWith = textSpanOverlapsWith;
11304     function textSpanOverlap(span1, span2) {
11305         var overlap = textSpanIntersection(span1, span2);
11306         return overlap && overlap.length === 0 ? undefined : overlap;
11307     }
11308     ts.textSpanOverlap = textSpanOverlap;
11309     function textSpanIntersectsWithTextSpan(span, other) {
11310         return decodedTextSpanIntersectsWith(span.start, span.length, other.start, other.length);
11311     }
11312     ts.textSpanIntersectsWithTextSpan = textSpanIntersectsWithTextSpan;
11313     function textSpanIntersectsWith(span, start, length) {
11314         return decodedTextSpanIntersectsWith(span.start, span.length, start, length);
11315     }
11316     ts.textSpanIntersectsWith = textSpanIntersectsWith;
11317     function decodedTextSpanIntersectsWith(start1, length1, start2, length2) {
11318         var end1 = start1 + length1;
11319         var end2 = start2 + length2;
11320         return start2 <= end1 && end2 >= start1;
11321     }
11322     ts.decodedTextSpanIntersectsWith = decodedTextSpanIntersectsWith;
11323     function textSpanIntersectsWithPosition(span, position) {
11324         return position <= textSpanEnd(span) && position >= span.start;
11325     }
11326     ts.textSpanIntersectsWithPosition = textSpanIntersectsWithPosition;
11327     function textSpanIntersection(span1, span2) {
11328         var start = Math.max(span1.start, span2.start);
11329         var end = Math.min(textSpanEnd(span1), textSpanEnd(span2));
11330         return start <= end ? createTextSpanFromBounds(start, end) : undefined;
11331     }
11332     ts.textSpanIntersection = textSpanIntersection;
11333     function createTextSpan(start, length) {
11334         if (start < 0) {
11335             throw new Error("start < 0");
11336         }
11337         if (length < 0) {
11338             throw new Error("length < 0");
11339         }
11340         return { start: start, length: length };
11341     }
11342     ts.createTextSpan = createTextSpan;
11343     function createTextSpanFromBounds(start, end) {
11344         return createTextSpan(start, end - start);
11345     }
11346     ts.createTextSpanFromBounds = createTextSpanFromBounds;
11347     function textChangeRangeNewSpan(range) {
11348         return createTextSpan(range.span.start, range.newLength);
11349     }
11350     ts.textChangeRangeNewSpan = textChangeRangeNewSpan;
11351     function textChangeRangeIsUnchanged(range) {
11352         return textSpanIsEmpty(range.span) && range.newLength === 0;
11353     }
11354     ts.textChangeRangeIsUnchanged = textChangeRangeIsUnchanged;
11355     function createTextChangeRange(span, newLength) {
11356         if (newLength < 0) {
11357             throw new Error("newLength < 0");
11358         }
11359         return { span: span, newLength: newLength };
11360     }
11361     ts.createTextChangeRange = createTextChangeRange;
11362     ts.unchangedTextChangeRange = createTextChangeRange(createTextSpan(0, 0), 0); // eslint-disable-line prefer-const
11363     /**
11364      * Called to merge all the changes that occurred across several versions of a script snapshot
11365      * into a single change.  i.e. if a user keeps making successive edits to a script we will
11366      * have a text change from V1 to V2, V2 to V3, ..., Vn.
11367      *
11368      * This function will then merge those changes into a single change range valid between V1 and
11369      * Vn.
11370      */
11371     function collapseTextChangeRangesAcrossMultipleVersions(changes) {
11372         if (changes.length === 0) {
11373             return ts.unchangedTextChangeRange;
11374         }
11375         if (changes.length === 1) {
11376             return changes[0];
11377         }
11378         // We change from talking about { { oldStart, oldLength }, newLength } to { oldStart, oldEnd, newEnd }
11379         // as it makes things much easier to reason about.
11380         var change0 = changes[0];
11381         var oldStartN = change0.span.start;
11382         var oldEndN = textSpanEnd(change0.span);
11383         var newEndN = oldStartN + change0.newLength;
11384         for (var i = 1; i < changes.length; i++) {
11385             var nextChange = changes[i];
11386             // Consider the following case:
11387             // i.e. two edits.  The first represents the text change range { { 10, 50 }, 30 }.  i.e. The span starting
11388             // at 10, with length 50 is reduced to length 30.  The second represents the text change range { { 30, 30 }, 40 }.
11389             // i.e. the span starting at 30 with length 30 is increased to length 40.
11390             //
11391             //      0         10        20        30        40        50        60        70        80        90        100
11392             //      -------------------------------------------------------------------------------------------------------
11393             //                |                                                 /
11394             //                |                                            /----
11395             //  T1            |                                       /----
11396             //                |                                  /----
11397             //                |                             /----
11398             //      -------------------------------------------------------------------------------------------------------
11399             //                                     |                            \
11400             //                                     |                               \
11401             //   T2                                |                                 \
11402             //                                     |                                   \
11403             //                                     |                                      \
11404             //      -------------------------------------------------------------------------------------------------------
11405             //
11406             // Merging these turns out to not be too difficult.  First, determining the new start of the change is trivial
11407             // it's just the min of the old and new starts.  i.e.:
11408             //
11409             //      0         10        20        30        40        50        60        70        80        90        100
11410             //      ------------------------------------------------------------*------------------------------------------
11411             //                |                                                 /
11412             //                |                                            /----
11413             //  T1            |                                       /----
11414             //                |                                  /----
11415             //                |                             /----
11416             //      ----------------------------------------$-------------------$------------------------------------------
11417             //                .                    |                            \
11418             //                .                    |                               \
11419             //   T2           .                    |                                 \
11420             //                .                    |                                   \
11421             //                .                    |                                      \
11422             //      ----------------------------------------------------------------------*--------------------------------
11423             //
11424             // (Note the dots represent the newly inferred start.
11425             // Determining the new and old end is also pretty simple.  Basically it boils down to paying attention to the
11426             // absolute positions at the asterisks, and the relative change between the dollar signs. Basically, we see
11427             // which if the two $'s precedes the other, and we move that one forward until they line up.  in this case that
11428             // means:
11429             //
11430             //      0         10        20        30        40        50        60        70        80        90        100
11431             //      --------------------------------------------------------------------------------*----------------------
11432             //                |                                                                     /
11433             //                |                                                                /----
11434             //  T1            |                                                           /----
11435             //                |                                                      /----
11436             //                |                                                 /----
11437             //      ------------------------------------------------------------$------------------------------------------
11438             //                .                    |                            \
11439             //                .                    |                               \
11440             //   T2           .                    |                                 \
11441             //                .                    |                                   \
11442             //                .                    |                                      \
11443             //      ----------------------------------------------------------------------*--------------------------------
11444             //
11445             // In other words (in this case), we're recognizing that the second edit happened after where the first edit
11446             // ended with a delta of 20 characters (60 - 40).  Thus, if we go back in time to where the first edit started
11447             // that's the same as if we started at char 80 instead of 60.
11448             //
11449             // As it so happens, the same logic applies if the second edit precedes the first edit.  In that case rather
11450             // than pushing the first edit forward to match the second, we'll push the second edit forward to match the
11451             // first.
11452             //
11453             // In this case that means we have { oldStart: 10, oldEnd: 80, newEnd: 70 } or, in TextChangeRange
11454             // semantics: { { start: 10, length: 70 }, newLength: 60 }
11455             //
11456             // The math then works out as follows.
11457             // If we have { oldStart1, oldEnd1, newEnd1 } and { oldStart2, oldEnd2, newEnd2 } then we can compute the
11458             // final result like so:
11459             //
11460             // {
11461             //      oldStart3: Min(oldStart1, oldStart2),
11462             //      oldEnd3: Max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1)),
11463             //      newEnd3: Max(newEnd2, newEnd2 + (newEnd1 - oldEnd2))
11464             // }
11465             var oldStart1 = oldStartN;
11466             var oldEnd1 = oldEndN;
11467             var newEnd1 = newEndN;
11468             var oldStart2 = nextChange.span.start;
11469             var oldEnd2 = textSpanEnd(nextChange.span);
11470             var newEnd2 = oldStart2 + nextChange.newLength;
11471             oldStartN = Math.min(oldStart1, oldStart2);
11472             oldEndN = Math.max(oldEnd1, oldEnd1 + (oldEnd2 - newEnd1));
11473             newEndN = Math.max(newEnd2, newEnd2 + (newEnd1 - oldEnd2));
11474         }
11475         return createTextChangeRange(createTextSpanFromBounds(oldStartN, oldEndN), /*newLength*/ newEndN - oldStartN);
11476     }
11477     ts.collapseTextChangeRangesAcrossMultipleVersions = collapseTextChangeRangesAcrossMultipleVersions;
11478     function getTypeParameterOwner(d) {
11479         if (d && d.kind === 159 /* TypeParameter */) {
11480             for (var current = d; current; current = current.parent) {
11481                 if (isFunctionLike(current) || isClassLike(current) || current.kind === 253 /* InterfaceDeclaration */) {
11482                     return current;
11483                 }
11484             }
11485         }
11486     }
11487     ts.getTypeParameterOwner = getTypeParameterOwner;
11488     function isParameterPropertyDeclaration(node, parent) {
11489         return ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */) && parent.kind === 166 /* Constructor */;
11490     }
11491     ts.isParameterPropertyDeclaration = isParameterPropertyDeclaration;
11492     function isEmptyBindingPattern(node) {
11493         if (isBindingPattern(node)) {
11494             return ts.every(node.elements, isEmptyBindingElement);
11495         }
11496         return false;
11497     }
11498     ts.isEmptyBindingPattern = isEmptyBindingPattern;
11499     function isEmptyBindingElement(node) {
11500         if (ts.isOmittedExpression(node)) {
11501             return true;
11502         }
11503         return isEmptyBindingPattern(node.name);
11504     }
11505     ts.isEmptyBindingElement = isEmptyBindingElement;
11506     function walkUpBindingElementsAndPatterns(binding) {
11507         var node = binding.parent;
11508         while (ts.isBindingElement(node.parent)) {
11509             node = node.parent.parent;
11510         }
11511         return node.parent;
11512     }
11513     ts.walkUpBindingElementsAndPatterns = walkUpBindingElementsAndPatterns;
11514     function getCombinedFlags(node, getFlags) {
11515         if (ts.isBindingElement(node)) {
11516             node = walkUpBindingElementsAndPatterns(node);
11517         }
11518         var flags = getFlags(node);
11519         if (node.kind === 249 /* VariableDeclaration */) {
11520             node = node.parent;
11521         }
11522         if (node && node.kind === 250 /* VariableDeclarationList */) {
11523             flags |= getFlags(node);
11524             node = node.parent;
11525         }
11526         if (node && node.kind === 232 /* VariableStatement */) {
11527             flags |= getFlags(node);
11528         }
11529         return flags;
11530     }
11531     function getCombinedModifierFlags(node) {
11532         return getCombinedFlags(node, ts.getEffectiveModifierFlags);
11533     }
11534     ts.getCombinedModifierFlags = getCombinedModifierFlags;
11535     /* @internal */
11536     function getCombinedNodeFlagsAlwaysIncludeJSDoc(node) {
11537         return getCombinedFlags(node, ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc);
11538     }
11539     ts.getCombinedNodeFlagsAlwaysIncludeJSDoc = getCombinedNodeFlagsAlwaysIncludeJSDoc;
11540     // Returns the node flags for this node and all relevant parent nodes.  This is done so that
11541     // nodes like variable declarations and binding elements can returned a view of their flags
11542     // that includes the modifiers from their container.  i.e. flags like export/declare aren't
11543     // stored on the variable declaration directly, but on the containing variable statement
11544     // (if it has one).  Similarly, flags for let/const are store on the variable declaration
11545     // list.  By calling this function, all those flags are combined so that the client can treat
11546     // the node as if it actually had those flags.
11547     function getCombinedNodeFlags(node) {
11548         return getCombinedFlags(node, function (n) { return n.flags; });
11549     }
11550     ts.getCombinedNodeFlags = getCombinedNodeFlags;
11551     /**
11552      * Checks to see if the locale is in the appropriate format,
11553      * and if it is, attempts to set the appropriate language.
11554      */
11555     function validateLocaleAndSetLanguage(locale, sys, errors) {
11556         var matchResult = /^([a-z]+)([_\-]([a-z]+))?$/.exec(locale.toLowerCase());
11557         if (!matchResult) {
11558             if (errors) {
11559                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Locale_must_be_of_the_form_language_or_language_territory_For_example_0_or_1, "en", "ja-jp"));
11560             }
11561             return;
11562         }
11563         var language = matchResult[1];
11564         var territory = matchResult[3];
11565         // First try the entire locale, then fall back to just language if that's all we have.
11566         // Either ways do not fail, and fallback to the English diagnostic strings.
11567         if (!trySetLanguageAndTerritory(language, territory, errors)) {
11568             trySetLanguageAndTerritory(language, /*territory*/ undefined, errors);
11569         }
11570         // Set the UI locale for string collation
11571         ts.setUILocale(locale);
11572         function trySetLanguageAndTerritory(language, territory, errors) {
11573             var compilerFilePath = ts.normalizePath(sys.getExecutingFilePath());
11574             var containingDirectoryPath = ts.getDirectoryPath(compilerFilePath);
11575             var filePath = ts.combinePaths(containingDirectoryPath, language);
11576             if (territory) {
11577                 filePath = filePath + "-" + territory;
11578             }
11579             filePath = sys.resolvePath(ts.combinePaths(filePath, "diagnosticMessages.generated.json"));
11580             if (!sys.fileExists(filePath)) {
11581                 return false;
11582             }
11583             // TODO: Add codePage support for readFile?
11584             var fileContents = "";
11585             try {
11586                 fileContents = sys.readFile(filePath);
11587             }
11588             catch (e) {
11589                 if (errors) {
11590                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unable_to_open_file_0, filePath));
11591                 }
11592                 return false;
11593             }
11594             try {
11595                 // this is a global mutation (or live binding update)!
11596                 ts.setLocalizedDiagnosticMessages(JSON.parse(fileContents));
11597             }
11598             catch (_a) {
11599                 if (errors) {
11600                     errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Corrupted_locale_file_0, filePath));
11601                 }
11602                 return false;
11603             }
11604             return true;
11605         }
11606     }
11607     ts.validateLocaleAndSetLanguage = validateLocaleAndSetLanguage;
11608     function getOriginalNode(node, nodeTest) {
11609         if (node) {
11610             while (node.original !== undefined) {
11611                 node = node.original;
11612             }
11613         }
11614         return !nodeTest || nodeTest(node) ? node : undefined;
11615     }
11616     ts.getOriginalNode = getOriginalNode;
11617     function findAncestor(node, callback) {
11618         while (node) {
11619             var result = callback(node);
11620             if (result === "quit") {
11621                 return undefined;
11622             }
11623             else if (result) {
11624                 return node;
11625             }
11626             node = node.parent;
11627         }
11628         return undefined;
11629     }
11630     ts.findAncestor = findAncestor;
11631     /**
11632      * Gets a value indicating whether a node originated in the parse tree.
11633      *
11634      * @param node The node to test.
11635      */
11636     function isParseTreeNode(node) {
11637         return (node.flags & 8 /* Synthesized */) === 0;
11638     }
11639     ts.isParseTreeNode = isParseTreeNode;
11640     function getParseTreeNode(node, nodeTest) {
11641         if (node === undefined || isParseTreeNode(node)) {
11642             return node;
11643         }
11644         node = node.original;
11645         while (node) {
11646             if (isParseTreeNode(node)) {
11647                 return !nodeTest || nodeTest(node) ? node : undefined;
11648             }
11649             node = node.original;
11650         }
11651     }
11652     ts.getParseTreeNode = getParseTreeNode;
11653     /** Add an extra underscore to identifiers that start with two underscores to avoid issues with magic names like '__proto__' */
11654     function escapeLeadingUnderscores(identifier) {
11655         return (identifier.length >= 2 && identifier.charCodeAt(0) === 95 /* _ */ && identifier.charCodeAt(1) === 95 /* _ */ ? "_" + identifier : identifier);
11656     }
11657     ts.escapeLeadingUnderscores = escapeLeadingUnderscores;
11658     /**
11659      * Remove extra underscore from escaped identifier text content.
11660      *
11661      * @param identifier The escaped identifier text.
11662      * @returns The unescaped identifier text.
11663      */
11664     function unescapeLeadingUnderscores(identifier) {
11665         var id = identifier;
11666         return id.length >= 3 && id.charCodeAt(0) === 95 /* _ */ && id.charCodeAt(1) === 95 /* _ */ && id.charCodeAt(2) === 95 /* _ */ ? id.substr(1) : id;
11667     }
11668     ts.unescapeLeadingUnderscores = unescapeLeadingUnderscores;
11669     function idText(identifierOrPrivateName) {
11670         return unescapeLeadingUnderscores(identifierOrPrivateName.escapedText);
11671     }
11672     ts.idText = idText;
11673     function symbolName(symbol) {
11674         if (symbol.valueDeclaration && isPrivateIdentifierPropertyDeclaration(symbol.valueDeclaration)) {
11675             return idText(symbol.valueDeclaration.name);
11676         }
11677         return unescapeLeadingUnderscores(symbol.escapedName);
11678     }
11679     ts.symbolName = symbolName;
11680     /**
11681      * A JSDocTypedef tag has an _optional_ name field - if a name is not directly present, we should
11682      * attempt to draw the name from the node the declaration is on (as that declaration is what its' symbol
11683      * will be merged with)
11684      */
11685     function nameForNamelessJSDocTypedef(declaration) {
11686         var hostNode = declaration.parent.parent;
11687         if (!hostNode) {
11688             return undefined;
11689         }
11690         // Covers classes, functions - any named declaration host node
11691         if (isDeclaration(hostNode)) {
11692             return getDeclarationIdentifier(hostNode);
11693         }
11694         // Covers remaining cases (returning undefined if none match).
11695         switch (hostNode.kind) {
11696             case 232 /* VariableStatement */:
11697                 if (hostNode.declarationList && hostNode.declarationList.declarations[0]) {
11698                     return getDeclarationIdentifier(hostNode.declarationList.declarations[0]);
11699                 }
11700                 break;
11701             case 233 /* ExpressionStatement */:
11702                 var expr = hostNode.expression;
11703                 if (expr.kind === 216 /* BinaryExpression */ && expr.operatorToken.kind === 62 /* EqualsToken */) {
11704                     expr = expr.left;
11705                 }
11706                 switch (expr.kind) {
11707                     case 201 /* PropertyAccessExpression */:
11708                         return expr.name;
11709                     case 202 /* ElementAccessExpression */:
11710                         var arg = expr.argumentExpression;
11711                         if (ts.isIdentifier(arg)) {
11712                             return arg;
11713                         }
11714                 }
11715                 break;
11716             case 207 /* ParenthesizedExpression */: {
11717                 return getDeclarationIdentifier(hostNode.expression);
11718             }
11719             case 245 /* LabeledStatement */: {
11720                 if (isDeclaration(hostNode.statement) || isExpression(hostNode.statement)) {
11721                     return getDeclarationIdentifier(hostNode.statement);
11722                 }
11723                 break;
11724             }
11725         }
11726     }
11727     function getDeclarationIdentifier(node) {
11728         var name = getNameOfDeclaration(node);
11729         return name && ts.isIdentifier(name) ? name : undefined;
11730     }
11731     /** @internal */
11732     function nodeHasName(statement, name) {
11733         if (isNamedDeclaration(statement) && ts.isIdentifier(statement.name) && idText(statement.name) === idText(name)) {
11734             return true;
11735         }
11736         if (ts.isVariableStatement(statement) && ts.some(statement.declarationList.declarations, function (d) { return nodeHasName(d, name); })) {
11737             return true;
11738         }
11739         return false;
11740     }
11741     ts.nodeHasName = nodeHasName;
11742     function getNameOfJSDocTypedef(declaration) {
11743         return declaration.name || nameForNamelessJSDocTypedef(declaration);
11744     }
11745     ts.getNameOfJSDocTypedef = getNameOfJSDocTypedef;
11746     /** @internal */
11747     function isNamedDeclaration(node) {
11748         return !!node.name; // A 'name' property should always be a DeclarationName.
11749     }
11750     ts.isNamedDeclaration = isNamedDeclaration;
11751     /** @internal */
11752     function getNonAssignedNameOfDeclaration(declaration) {
11753         switch (declaration.kind) {
11754             case 78 /* Identifier */:
11755                 return declaration;
11756             case 333 /* JSDocPropertyTag */:
11757             case 326 /* JSDocParameterTag */: {
11758                 var name = declaration.name;
11759                 if (name.kind === 157 /* QualifiedName */) {
11760                     return name.right;
11761                 }
11762                 break;
11763             }
11764             case 203 /* CallExpression */:
11765             case 216 /* BinaryExpression */: {
11766                 var expr_1 = declaration;
11767                 switch (ts.getAssignmentDeclarationKind(expr_1)) {
11768                     case 1 /* ExportsProperty */:
11769                     case 4 /* ThisProperty */:
11770                     case 5 /* Property */:
11771                     case 3 /* PrototypeProperty */:
11772                         return ts.getElementOrPropertyAccessArgumentExpressionOrName(expr_1.left);
11773                     case 7 /* ObjectDefinePropertyValue */:
11774                     case 8 /* ObjectDefinePropertyExports */:
11775                     case 9 /* ObjectDefinePrototypeProperty */:
11776                         return expr_1.arguments[1];
11777                     default:
11778                         return undefined;
11779                 }
11780             }
11781             case 331 /* JSDocTypedefTag */:
11782                 return getNameOfJSDocTypedef(declaration);
11783             case 325 /* JSDocEnumTag */:
11784                 return nameForNamelessJSDocTypedef(declaration);
11785             case 266 /* ExportAssignment */: {
11786                 var expression = declaration.expression;
11787                 return ts.isIdentifier(expression) ? expression : undefined;
11788             }
11789             case 202 /* ElementAccessExpression */:
11790                 var expr = declaration;
11791                 if (ts.isBindableStaticElementAccessExpression(expr)) {
11792                     return expr.argumentExpression;
11793                 }
11794         }
11795         return declaration.name;
11796     }
11797     ts.getNonAssignedNameOfDeclaration = getNonAssignedNameOfDeclaration;
11798     function getNameOfDeclaration(declaration) {
11799         if (declaration === undefined)
11800             return undefined;
11801         return getNonAssignedNameOfDeclaration(declaration) ||
11802             (ts.isFunctionExpression(declaration) || ts.isClassExpression(declaration) ? getAssignedName(declaration) : undefined);
11803     }
11804     ts.getNameOfDeclaration = getNameOfDeclaration;
11805     /*@internal*/
11806     function getAssignedName(node) {
11807         if (!node.parent) {
11808             return undefined;
11809         }
11810         else if (ts.isPropertyAssignment(node.parent) || ts.isBindingElement(node.parent)) {
11811             return node.parent.name;
11812         }
11813         else if (ts.isBinaryExpression(node.parent) && node === node.parent.right) {
11814             if (ts.isIdentifier(node.parent.left)) {
11815                 return node.parent.left;
11816             }
11817             else if (ts.isAccessExpression(node.parent.left)) {
11818                 return ts.getElementOrPropertyAccessArgumentExpressionOrName(node.parent.left);
11819             }
11820         }
11821         else if (ts.isVariableDeclaration(node.parent) && ts.isIdentifier(node.parent.name)) {
11822             return node.parent.name;
11823         }
11824     }
11825     ts.getAssignedName = getAssignedName;
11826     function getJSDocParameterTagsWorker(param, noCache) {
11827         if (param.name) {
11828             if (ts.isIdentifier(param.name)) {
11829                 var name_1 = param.name.escapedText;
11830                 return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) { return ts.isJSDocParameterTag(tag) && ts.isIdentifier(tag.name) && tag.name.escapedText === name_1; });
11831             }
11832             else {
11833                 var i = param.parent.parameters.indexOf(param);
11834                 ts.Debug.assert(i > -1, "Parameters should always be in their parents' parameter list");
11835                 var paramTags = getJSDocTagsWorker(param.parent, noCache).filter(ts.isJSDocParameterTag);
11836                 if (i < paramTags.length) {
11837                     return [paramTags[i]];
11838                 }
11839             }
11840         }
11841         // return empty array for: out-of-order binding patterns and JSDoc function syntax, which has un-named parameters
11842         return ts.emptyArray;
11843     }
11844     /**
11845      * Gets the JSDoc parameter tags for the node if present.
11846      *
11847      * @remarks Returns any JSDoc param tag whose name matches the provided
11848      * parameter, whether a param tag on a containing function
11849      * expression, or a param tag on a variable declaration whose
11850      * initializer is the containing function. The tags closest to the
11851      * node are returned first, so in the previous example, the param
11852      * tag on the containing function expression would be first.
11853      *
11854      * For binding patterns, parameter tags are matched by position.
11855      */
11856     function getJSDocParameterTags(param) {
11857         return getJSDocParameterTagsWorker(param, /*noCache*/ false);
11858     }
11859     ts.getJSDocParameterTags = getJSDocParameterTags;
11860     /* @internal */
11861     function getJSDocParameterTagsNoCache(param) {
11862         return getJSDocParameterTagsWorker(param, /*noCache*/ true);
11863     }
11864     ts.getJSDocParameterTagsNoCache = getJSDocParameterTagsNoCache;
11865     function getJSDocTypeParameterTagsWorker(param, noCache) {
11866         var name = param.name.escapedText;
11867         return getJSDocTagsWorker(param.parent, noCache).filter(function (tag) {
11868             return ts.isJSDocTemplateTag(tag) && tag.typeParameters.some(function (tp) { return tp.name.escapedText === name; });
11869         });
11870     }
11871     /**
11872      * Gets the JSDoc type parameter tags for the node if present.
11873      *
11874      * @remarks Returns any JSDoc template tag whose names match the provided
11875      * parameter, whether a template tag on a containing function
11876      * expression, or a template tag on a variable declaration whose
11877      * initializer is the containing function. The tags closest to the
11878      * node are returned first, so in the previous example, the template
11879      * tag on the containing function expression would be first.
11880      */
11881     function getJSDocTypeParameterTags(param) {
11882         return getJSDocTypeParameterTagsWorker(param, /*noCache*/ false);
11883     }
11884     ts.getJSDocTypeParameterTags = getJSDocTypeParameterTags;
11885     /* @internal */
11886     function getJSDocTypeParameterTagsNoCache(param) {
11887         return getJSDocTypeParameterTagsWorker(param, /*noCache*/ true);
11888     }
11889     ts.getJSDocTypeParameterTagsNoCache = getJSDocTypeParameterTagsNoCache;
11890     /**
11891      * Return true if the node has JSDoc parameter tags.
11892      *
11893      * @remarks Includes parameter tags that are not directly on the node,
11894      * for example on a variable declaration whose initializer is a function expression.
11895      */
11896     function hasJSDocParameterTags(node) {
11897         return !!getFirstJSDocTag(node, ts.isJSDocParameterTag);
11898     }
11899     ts.hasJSDocParameterTags = hasJSDocParameterTags;
11900     /** Gets the JSDoc augments tag for the node if present */
11901     function getJSDocAugmentsTag(node) {
11902         return getFirstJSDocTag(node, ts.isJSDocAugmentsTag);
11903     }
11904     ts.getJSDocAugmentsTag = getJSDocAugmentsTag;
11905     /** Gets the JSDoc implements tags for the node if present */
11906     function getJSDocImplementsTags(node) {
11907         return getAllJSDocTags(node, ts.isJSDocImplementsTag);
11908     }
11909     ts.getJSDocImplementsTags = getJSDocImplementsTags;
11910     /** Gets the JSDoc class tag for the node if present */
11911     function getJSDocClassTag(node) {
11912         return getFirstJSDocTag(node, ts.isJSDocClassTag);
11913     }
11914     ts.getJSDocClassTag = getJSDocClassTag;
11915     /** Gets the JSDoc public tag for the node if present */
11916     function getJSDocPublicTag(node) {
11917         return getFirstJSDocTag(node, ts.isJSDocPublicTag);
11918     }
11919     ts.getJSDocPublicTag = getJSDocPublicTag;
11920     /*@internal*/
11921     function getJSDocPublicTagNoCache(node) {
11922         return getFirstJSDocTag(node, ts.isJSDocPublicTag, /*noCache*/ true);
11923     }
11924     ts.getJSDocPublicTagNoCache = getJSDocPublicTagNoCache;
11925     /** Gets the JSDoc private tag for the node if present */
11926     function getJSDocPrivateTag(node) {
11927         return getFirstJSDocTag(node, ts.isJSDocPrivateTag);
11928     }
11929     ts.getJSDocPrivateTag = getJSDocPrivateTag;
11930     /*@internal*/
11931     function getJSDocPrivateTagNoCache(node) {
11932         return getFirstJSDocTag(node, ts.isJSDocPrivateTag, /*noCache*/ true);
11933     }
11934     ts.getJSDocPrivateTagNoCache = getJSDocPrivateTagNoCache;
11935     /** Gets the JSDoc protected tag for the node if present */
11936     function getJSDocProtectedTag(node) {
11937         return getFirstJSDocTag(node, ts.isJSDocProtectedTag);
11938     }
11939     ts.getJSDocProtectedTag = getJSDocProtectedTag;
11940     /*@internal*/
11941     function getJSDocProtectedTagNoCache(node) {
11942         return getFirstJSDocTag(node, ts.isJSDocProtectedTag, /*noCache*/ true);
11943     }
11944     ts.getJSDocProtectedTagNoCache = getJSDocProtectedTagNoCache;
11945     /** Gets the JSDoc protected tag for the node if present */
11946     function getJSDocReadonlyTag(node) {
11947         return getFirstJSDocTag(node, ts.isJSDocReadonlyTag);
11948     }
11949     ts.getJSDocReadonlyTag = getJSDocReadonlyTag;
11950     /*@internal*/
11951     function getJSDocReadonlyTagNoCache(node) {
11952         return getFirstJSDocTag(node, ts.isJSDocReadonlyTag, /*noCache*/ true);
11953     }
11954     ts.getJSDocReadonlyTagNoCache = getJSDocReadonlyTagNoCache;
11955     /** Gets the JSDoc deprecated tag for the node if present */
11956     function getJSDocDeprecatedTag(node) {
11957         return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag);
11958     }
11959     ts.getJSDocDeprecatedTag = getJSDocDeprecatedTag;
11960     /*@internal */
11961     function getJSDocDeprecatedTagNoCache(node) {
11962         return getFirstJSDocTag(node, ts.isJSDocDeprecatedTag, /*noCache*/ true);
11963     }
11964     ts.getJSDocDeprecatedTagNoCache = getJSDocDeprecatedTagNoCache;
11965     /** Gets the JSDoc enum tag for the node if present */
11966     function getJSDocEnumTag(node) {
11967         return getFirstJSDocTag(node, ts.isJSDocEnumTag);
11968     }
11969     ts.getJSDocEnumTag = getJSDocEnumTag;
11970     /** Gets the JSDoc this tag for the node if present */
11971     function getJSDocThisTag(node) {
11972         return getFirstJSDocTag(node, ts.isJSDocThisTag);
11973     }
11974     ts.getJSDocThisTag = getJSDocThisTag;
11975     /** Gets the JSDoc return tag for the node if present */
11976     function getJSDocReturnTag(node) {
11977         return getFirstJSDocTag(node, ts.isJSDocReturnTag);
11978     }
11979     ts.getJSDocReturnTag = getJSDocReturnTag;
11980     /** Gets the JSDoc template tag for the node if present */
11981     function getJSDocTemplateTag(node) {
11982         return getFirstJSDocTag(node, ts.isJSDocTemplateTag);
11983     }
11984     ts.getJSDocTemplateTag = getJSDocTemplateTag;
11985     /** Gets the JSDoc type tag for the node if present and valid */
11986     function getJSDocTypeTag(node) {
11987         // We should have already issued an error if there were multiple type jsdocs, so just use the first one.
11988         var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
11989         if (tag && tag.typeExpression && tag.typeExpression.type) {
11990             return tag;
11991         }
11992         return undefined;
11993     }
11994     ts.getJSDocTypeTag = getJSDocTypeTag;
11995     /**
11996      * Gets the type node for the node if provided via JSDoc.
11997      *
11998      * @remarks The search includes any JSDoc param tag that relates
11999      * to the provided parameter, for example a type tag on the
12000      * parameter itself, or a param tag on a containing function
12001      * expression, or a param tag on a variable declaration whose
12002      * initializer is the containing function. The tags closest to the
12003      * node are examined first, so in the previous example, the type
12004      * tag directly on the node would be returned.
12005      */
12006     function getJSDocType(node) {
12007         var tag = getFirstJSDocTag(node, ts.isJSDocTypeTag);
12008         if (!tag && ts.isParameter(node)) {
12009             tag = ts.find(getJSDocParameterTags(node), function (tag) { return !!tag.typeExpression; });
12010         }
12011         return tag && tag.typeExpression && tag.typeExpression.type;
12012     }
12013     ts.getJSDocType = getJSDocType;
12014     /**
12015      * Gets the return type node for the node if provided via JSDoc return tag or type tag.
12016      *
12017      * @remarks `getJSDocReturnTag` just gets the whole JSDoc tag. This function
12018      * gets the type from inside the braces, after the fat arrow, etc.
12019      */
12020     function getJSDocReturnType(node) {
12021         var returnTag = getJSDocReturnTag(node);
12022         if (returnTag && returnTag.typeExpression) {
12023             return returnTag.typeExpression.type;
12024         }
12025         var typeTag = getJSDocTypeTag(node);
12026         if (typeTag && typeTag.typeExpression) {
12027             var type = typeTag.typeExpression.type;
12028             if (ts.isTypeLiteralNode(type)) {
12029                 var sig = ts.find(type.members, ts.isCallSignatureDeclaration);
12030                 return sig && sig.type;
12031             }
12032             if (ts.isFunctionTypeNode(type) || ts.isJSDocFunctionType(type)) {
12033                 return type.type;
12034             }
12035         }
12036     }
12037     ts.getJSDocReturnType = getJSDocReturnType;
12038     function getJSDocTagsWorker(node, noCache) {
12039         var tags = node.jsDocCache;
12040         // If cache is 'null', that means we did the work of searching for JSDoc tags and came up with nothing.
12041         if (tags === undefined || noCache) {
12042             var comments = ts.getJSDocCommentsAndTags(node, noCache);
12043             ts.Debug.assert(comments.length < 2 || comments[0] !== comments[1]);
12044             tags = ts.flatMap(comments, function (j) { return ts.isJSDoc(j) ? j.tags : j; });
12045             if (!noCache) {
12046                 node.jsDocCache = tags;
12047             }
12048         }
12049         return tags;
12050     }
12051     /** Get all JSDoc tags related to a node, including those on parent nodes. */
12052     function getJSDocTags(node) {
12053         return getJSDocTagsWorker(node, /*noCache*/ false);
12054     }
12055     ts.getJSDocTags = getJSDocTags;
12056     /* @internal */
12057     function getJSDocTagsNoCache(node) {
12058         return getJSDocTagsWorker(node, /*noCache*/ true);
12059     }
12060     ts.getJSDocTagsNoCache = getJSDocTagsNoCache;
12061     /** Get the first JSDoc tag of a specified kind, or undefined if not present. */
12062     function getFirstJSDocTag(node, predicate, noCache) {
12063         return ts.find(getJSDocTagsWorker(node, noCache), predicate);
12064     }
12065     /** Gets all JSDoc tags that match a specified predicate */
12066     function getAllJSDocTags(node, predicate) {
12067         return getJSDocTags(node).filter(predicate);
12068     }
12069     ts.getAllJSDocTags = getAllJSDocTags;
12070     /** Gets all JSDoc tags of a specified kind */
12071     function getAllJSDocTagsOfKind(node, kind) {
12072         return getJSDocTags(node).filter(function (doc) { return doc.kind === kind; });
12073     }
12074     ts.getAllJSDocTagsOfKind = getAllJSDocTagsOfKind;
12075     /**
12076      * Gets the effective type parameters. If the node was parsed in a
12077      * JavaScript file, gets the type parameters from the `@template` tag from JSDoc.
12078      */
12079     function getEffectiveTypeParameterDeclarations(node) {
12080         if (ts.isJSDocSignature(node)) {
12081             return ts.emptyArray;
12082         }
12083         if (ts.isJSDocTypeAlias(node)) {
12084             ts.Debug.assert(node.parent.kind === 311 /* JSDocComment */);
12085             return ts.flatMap(node.parent.tags, function (tag) { return ts.isJSDocTemplateTag(tag) ? tag.typeParameters : undefined; });
12086         }
12087         if (node.typeParameters) {
12088             return node.typeParameters;
12089         }
12090         if (ts.isInJSFile(node)) {
12091             var decls = ts.getJSDocTypeParameterDeclarations(node);
12092             if (decls.length) {
12093                 return decls;
12094             }
12095             var typeTag = getJSDocType(node);
12096             if (typeTag && ts.isFunctionTypeNode(typeTag) && typeTag.typeParameters) {
12097                 return typeTag.typeParameters;
12098             }
12099         }
12100         return ts.emptyArray;
12101     }
12102     ts.getEffectiveTypeParameterDeclarations = getEffectiveTypeParameterDeclarations;
12103     function getEffectiveConstraintOfTypeParameter(node) {
12104         return node.constraint ? node.constraint :
12105             ts.isJSDocTemplateTag(node.parent) && node === node.parent.typeParameters[0] ? node.parent.constraint :
12106                 undefined;
12107     }
12108     ts.getEffectiveConstraintOfTypeParameter = getEffectiveConstraintOfTypeParameter;
12109     // #region
12110     function isIdentifierOrPrivateIdentifier(node) {
12111         return node.kind === 78 /* Identifier */ || node.kind === 79 /* PrivateIdentifier */;
12112     }
12113     ts.isIdentifierOrPrivateIdentifier = isIdentifierOrPrivateIdentifier;
12114     /* @internal */
12115     function isGetOrSetAccessorDeclaration(node) {
12116         return node.kind === 168 /* SetAccessor */ || node.kind === 167 /* GetAccessor */;
12117     }
12118     ts.isGetOrSetAccessorDeclaration = isGetOrSetAccessorDeclaration;
12119     function isPropertyAccessChain(node) {
12120         return ts.isPropertyAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12121     }
12122     ts.isPropertyAccessChain = isPropertyAccessChain;
12123     function isElementAccessChain(node) {
12124         return ts.isElementAccessExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12125     }
12126     ts.isElementAccessChain = isElementAccessChain;
12127     function isCallChain(node) {
12128         return ts.isCallExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12129     }
12130     ts.isCallChain = isCallChain;
12131     function isOptionalChain(node) {
12132         var kind = node.kind;
12133         return !!(node.flags & 32 /* OptionalChain */) &&
12134             (kind === 201 /* PropertyAccessExpression */
12135                 || kind === 202 /* ElementAccessExpression */
12136                 || kind === 203 /* CallExpression */
12137                 || kind === 225 /* NonNullExpression */);
12138     }
12139     ts.isOptionalChain = isOptionalChain;
12140     /* @internal */
12141     function isOptionalChainRoot(node) {
12142         return isOptionalChain(node) && !ts.isNonNullExpression(node) && !!node.questionDotToken;
12143     }
12144     ts.isOptionalChainRoot = isOptionalChainRoot;
12145     /**
12146      * Determines whether a node is the expression preceding an optional chain (i.e. `a` in `a?.b`).
12147      */
12148     /* @internal */
12149     function isExpressionOfOptionalChainRoot(node) {
12150         return isOptionalChainRoot(node.parent) && node.parent.expression === node;
12151     }
12152     ts.isExpressionOfOptionalChainRoot = isExpressionOfOptionalChainRoot;
12153     /**
12154      * Determines whether a node is the outermost `OptionalChain` in an ECMAScript `OptionalExpression`:
12155      *
12156      * 1. For `a?.b.c`, the outermost chain is `a?.b.c` (`c` is the end of the chain starting at `a?.`)
12157      * 2. For `a?.b!`, the outermost chain is `a?.b` (`b` is the end of the chain starting at `a?.`)
12158      * 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)
12159      * 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
12160      *   the end of the chain starting at `c?.`)
12161      * 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
12162      *   the end of the chain starting at `a?.`)
12163      */
12164     /* @internal */
12165     function isOutermostOptionalChain(node) {
12166         return !isOptionalChain(node.parent) // cases 1, 2, and 3
12167             || isOptionalChainRoot(node.parent) // case 4
12168             || node !== node.parent.expression; // case 5
12169     }
12170     ts.isOutermostOptionalChain = isOutermostOptionalChain;
12171     function isNullishCoalesce(node) {
12172         return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 60 /* QuestionQuestionToken */;
12173     }
12174     ts.isNullishCoalesce = isNullishCoalesce;
12175     function isConstTypeReference(node) {
12176         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) &&
12177             node.typeName.escapedText === "const" && !node.typeArguments;
12178     }
12179     ts.isConstTypeReference = isConstTypeReference;
12180     function skipPartiallyEmittedExpressions(node) {
12181         return ts.skipOuterExpressions(node, 8 /* PartiallyEmittedExpressions */);
12182     }
12183     ts.skipPartiallyEmittedExpressions = skipPartiallyEmittedExpressions;
12184     function isNonNullChain(node) {
12185         return ts.isNonNullExpression(node) && !!(node.flags & 32 /* OptionalChain */);
12186     }
12187     ts.isNonNullChain = isNonNullChain;
12188     function isBreakOrContinueStatement(node) {
12189         return node.kind === 241 /* BreakStatement */ || node.kind === 240 /* ContinueStatement */;
12190     }
12191     ts.isBreakOrContinueStatement = isBreakOrContinueStatement;
12192     function isNamedExportBindings(node) {
12193         return node.kind === 269 /* NamespaceExport */ || node.kind === 268 /* NamedExports */;
12194     }
12195     ts.isNamedExportBindings = isNamedExportBindings;
12196     function isUnparsedTextLike(node) {
12197         switch (node.kind) {
12198             case 294 /* UnparsedText */:
12199             case 295 /* UnparsedInternalText */:
12200                 return true;
12201             default:
12202                 return false;
12203         }
12204     }
12205     ts.isUnparsedTextLike = isUnparsedTextLike;
12206     function isUnparsedNode(node) {
12207         return isUnparsedTextLike(node) ||
12208             node.kind === 292 /* UnparsedPrologue */ ||
12209             node.kind === 296 /* UnparsedSyntheticReference */;
12210     }
12211     ts.isUnparsedNode = isUnparsedNode;
12212     function isJSDocPropertyLikeTag(node) {
12213         return node.kind === 333 /* JSDocPropertyTag */ || node.kind === 326 /* JSDocParameterTag */;
12214     }
12215     ts.isJSDocPropertyLikeTag = isJSDocPropertyLikeTag;
12216     // #endregion
12217     // #region
12218     // Node tests
12219     //
12220     // All node tests in the following list should *not* reference parent pointers so that
12221     // they may be used with transformations.
12222     /* @internal */
12223     function isNode(node) {
12224         return isNodeKind(node.kind);
12225     }
12226     ts.isNode = isNode;
12227     /* @internal */
12228     function isNodeKind(kind) {
12229         return kind >= 157 /* FirstNode */;
12230     }
12231     ts.isNodeKind = isNodeKind;
12232     /**
12233      * True if node is of some token syntax kind.
12234      * For example, this is true for an IfKeyword but not for an IfStatement.
12235      * Literals are considered tokens, except TemplateLiteral, but does include TemplateHead/Middle/Tail.
12236      */
12237     function isToken(n) {
12238         return n.kind >= 0 /* FirstToken */ && n.kind <= 156 /* LastToken */;
12239     }
12240     ts.isToken = isToken;
12241     // Node Arrays
12242     /* @internal */
12243     function isNodeArray(array) {
12244         return array.hasOwnProperty("pos") && array.hasOwnProperty("end");
12245     }
12246     ts.isNodeArray = isNodeArray;
12247     // Literals
12248     /* @internal */
12249     function isLiteralKind(kind) {
12250         return 8 /* FirstLiteralToken */ <= kind && kind <= 14 /* LastLiteralToken */;
12251     }
12252     ts.isLiteralKind = isLiteralKind;
12253     function isLiteralExpression(node) {
12254         return isLiteralKind(node.kind);
12255     }
12256     ts.isLiteralExpression = isLiteralExpression;
12257     // Pseudo-literals
12258     /* @internal */
12259     function isTemplateLiteralKind(kind) {
12260         return 14 /* FirstTemplateToken */ <= kind && kind <= 17 /* LastTemplateToken */;
12261     }
12262     ts.isTemplateLiteralKind = isTemplateLiteralKind;
12263     function isTemplateLiteralToken(node) {
12264         return isTemplateLiteralKind(node.kind);
12265     }
12266     ts.isTemplateLiteralToken = isTemplateLiteralToken;
12267     function isTemplateMiddleOrTemplateTail(node) {
12268         var kind = node.kind;
12269         return kind === 16 /* TemplateMiddle */
12270             || kind === 17 /* TemplateTail */;
12271     }
12272     ts.isTemplateMiddleOrTemplateTail = isTemplateMiddleOrTemplateTail;
12273     function isImportOrExportSpecifier(node) {
12274         return ts.isImportSpecifier(node) || ts.isExportSpecifier(node);
12275     }
12276     ts.isImportOrExportSpecifier = isImportOrExportSpecifier;
12277     function isTypeOnlyImportOrExportDeclaration(node) {
12278         switch (node.kind) {
12279             case 265 /* ImportSpecifier */:
12280             case 270 /* ExportSpecifier */:
12281                 return node.parent.parent.isTypeOnly;
12282             case 263 /* NamespaceImport */:
12283                 return node.parent.isTypeOnly;
12284             case 262 /* ImportClause */:
12285                 return node.isTypeOnly;
12286             default:
12287                 return false;
12288         }
12289     }
12290     ts.isTypeOnlyImportOrExportDeclaration = isTypeOnlyImportOrExportDeclaration;
12291     function isStringTextContainingNode(node) {
12292         return node.kind === 10 /* StringLiteral */ || isTemplateLiteralKind(node.kind);
12293     }
12294     ts.isStringTextContainingNode = isStringTextContainingNode;
12295     // Identifiers
12296     /* @internal */
12297     function isGeneratedIdentifier(node) {
12298         return ts.isIdentifier(node) && (node.autoGenerateFlags & 7 /* KindMask */) > 0 /* None */;
12299     }
12300     ts.isGeneratedIdentifier = isGeneratedIdentifier;
12301     // Private Identifiers
12302     /*@internal*/
12303     function isPrivateIdentifierPropertyDeclaration(node) {
12304         return ts.isPropertyDeclaration(node) && ts.isPrivateIdentifier(node.name);
12305     }
12306     ts.isPrivateIdentifierPropertyDeclaration = isPrivateIdentifierPropertyDeclaration;
12307     /*@internal*/
12308     function isPrivateIdentifierPropertyAccessExpression(node) {
12309         return ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name);
12310     }
12311     ts.isPrivateIdentifierPropertyAccessExpression = isPrivateIdentifierPropertyAccessExpression;
12312     // Keywords
12313     /* @internal */
12314     function isModifierKind(token) {
12315         switch (token) {
12316             case 125 /* AbstractKeyword */:
12317             case 129 /* AsyncKeyword */:
12318             case 84 /* ConstKeyword */:
12319             case 133 /* DeclareKeyword */:
12320             case 87 /* DefaultKeyword */:
12321             case 92 /* ExportKeyword */:
12322             case 122 /* PublicKeyword */:
12323             case 120 /* PrivateKeyword */:
12324             case 121 /* ProtectedKeyword */:
12325             case 142 /* ReadonlyKeyword */:
12326             case 123 /* StaticKeyword */:
12327                 return true;
12328         }
12329         return false;
12330     }
12331     ts.isModifierKind = isModifierKind;
12332     /* @internal */
12333     function isParameterPropertyModifier(kind) {
12334         return !!(ts.modifierToFlag(kind) & 92 /* ParameterPropertyModifier */);
12335     }
12336     ts.isParameterPropertyModifier = isParameterPropertyModifier;
12337     /* @internal */
12338     function isClassMemberModifier(idToken) {
12339         return isParameterPropertyModifier(idToken) || idToken === 123 /* StaticKeyword */;
12340     }
12341     ts.isClassMemberModifier = isClassMemberModifier;
12342     function isModifier(node) {
12343         return isModifierKind(node.kind);
12344     }
12345     ts.isModifier = isModifier;
12346     function isEntityName(node) {
12347         var kind = node.kind;
12348         return kind === 157 /* QualifiedName */
12349             || kind === 78 /* Identifier */;
12350     }
12351     ts.isEntityName = isEntityName;
12352     function isPropertyName(node) {
12353         var kind = node.kind;
12354         return kind === 78 /* Identifier */
12355             || kind === 79 /* PrivateIdentifier */
12356             || kind === 10 /* StringLiteral */
12357             || kind === 8 /* NumericLiteral */
12358             || kind === 158 /* ComputedPropertyName */;
12359     }
12360     ts.isPropertyName = isPropertyName;
12361     function isBindingName(node) {
12362         var kind = node.kind;
12363         return kind === 78 /* Identifier */
12364             || kind === 196 /* ObjectBindingPattern */
12365             || kind === 197 /* ArrayBindingPattern */;
12366     }
12367     ts.isBindingName = isBindingName;
12368     // Functions
12369     function isFunctionLike(node) {
12370         return node && isFunctionLikeKind(node.kind);
12371     }
12372     ts.isFunctionLike = isFunctionLike;
12373     /* @internal */
12374     function isFunctionLikeDeclaration(node) {
12375         return node && isFunctionLikeDeclarationKind(node.kind);
12376     }
12377     ts.isFunctionLikeDeclaration = isFunctionLikeDeclaration;
12378     function isFunctionLikeDeclarationKind(kind) {
12379         switch (kind) {
12380             case 251 /* FunctionDeclaration */:
12381             case 165 /* MethodDeclaration */:
12382             case 166 /* Constructor */:
12383             case 167 /* GetAccessor */:
12384             case 168 /* SetAccessor */:
12385             case 208 /* FunctionExpression */:
12386             case 209 /* ArrowFunction */:
12387                 return true;
12388             default:
12389                 return false;
12390         }
12391     }
12392     /* @internal */
12393     function isFunctionLikeKind(kind) {
12394         switch (kind) {
12395             case 164 /* MethodSignature */:
12396             case 169 /* CallSignature */:
12397             case 313 /* JSDocSignature */:
12398             case 170 /* ConstructSignature */:
12399             case 171 /* IndexSignature */:
12400             case 174 /* FunctionType */:
12401             case 308 /* JSDocFunctionType */:
12402             case 175 /* ConstructorType */:
12403                 return true;
12404             default:
12405                 return isFunctionLikeDeclarationKind(kind);
12406         }
12407     }
12408     ts.isFunctionLikeKind = isFunctionLikeKind;
12409     /* @internal */
12410     function isFunctionOrModuleBlock(node) {
12411         return ts.isSourceFile(node) || ts.isModuleBlock(node) || ts.isBlock(node) && isFunctionLike(node.parent);
12412     }
12413     ts.isFunctionOrModuleBlock = isFunctionOrModuleBlock;
12414     // Classes
12415     function isClassElement(node) {
12416         var kind = node.kind;
12417         return kind === 166 /* Constructor */
12418             || kind === 163 /* PropertyDeclaration */
12419             || kind === 165 /* MethodDeclaration */
12420             || kind === 167 /* GetAccessor */
12421             || kind === 168 /* SetAccessor */
12422             || kind === 171 /* IndexSignature */
12423             || kind === 229 /* SemicolonClassElement */;
12424     }
12425     ts.isClassElement = isClassElement;
12426     function isClassLike(node) {
12427         return node && (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */);
12428     }
12429     ts.isClassLike = isClassLike;
12430     function isAccessor(node) {
12431         return node && (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */);
12432     }
12433     ts.isAccessor = isAccessor;
12434     /* @internal */
12435     function isMethodOrAccessor(node) {
12436         switch (node.kind) {
12437             case 165 /* MethodDeclaration */:
12438             case 167 /* GetAccessor */:
12439             case 168 /* SetAccessor */:
12440                 return true;
12441             default:
12442                 return false;
12443         }
12444     }
12445     ts.isMethodOrAccessor = isMethodOrAccessor;
12446     // Type members
12447     function isTypeElement(node) {
12448         var kind = node.kind;
12449         return kind === 170 /* ConstructSignature */
12450             || kind === 169 /* CallSignature */
12451             || kind === 162 /* PropertySignature */
12452             || kind === 164 /* MethodSignature */
12453             || kind === 171 /* IndexSignature */;
12454     }
12455     ts.isTypeElement = isTypeElement;
12456     function isClassOrTypeElement(node) {
12457         return isTypeElement(node) || isClassElement(node);
12458     }
12459     ts.isClassOrTypeElement = isClassOrTypeElement;
12460     function isObjectLiteralElementLike(node) {
12461         var kind = node.kind;
12462         return kind === 288 /* PropertyAssignment */
12463             || kind === 289 /* ShorthandPropertyAssignment */
12464             || kind === 290 /* SpreadAssignment */
12465             || kind === 165 /* MethodDeclaration */
12466             || kind === 167 /* GetAccessor */
12467             || kind === 168 /* SetAccessor */;
12468     }
12469     ts.isObjectLiteralElementLike = isObjectLiteralElementLike;
12470     // Type
12471     /**
12472      * Node test that determines whether a node is a valid type node.
12473      * This differs from the `isPartOfTypeNode` function which determines whether a node is *part*
12474      * of a TypeNode.
12475      */
12476     function isTypeNode(node) {
12477         return ts.isTypeNodeKind(node.kind);
12478     }
12479     ts.isTypeNode = isTypeNode;
12480     function isFunctionOrConstructorTypeNode(node) {
12481         switch (node.kind) {
12482             case 174 /* FunctionType */:
12483             case 175 /* ConstructorType */:
12484                 return true;
12485         }
12486         return false;
12487     }
12488     ts.isFunctionOrConstructorTypeNode = isFunctionOrConstructorTypeNode;
12489     // Binding patterns
12490     /* @internal */
12491     function isBindingPattern(node) {
12492         if (node) {
12493             var kind = node.kind;
12494             return kind === 197 /* ArrayBindingPattern */
12495                 || kind === 196 /* ObjectBindingPattern */;
12496         }
12497         return false;
12498     }
12499     ts.isBindingPattern = isBindingPattern;
12500     /* @internal */
12501     function isAssignmentPattern(node) {
12502         var kind = node.kind;
12503         return kind === 199 /* ArrayLiteralExpression */
12504             || kind === 200 /* ObjectLiteralExpression */;
12505     }
12506     ts.isAssignmentPattern = isAssignmentPattern;
12507     /* @internal */
12508     function isArrayBindingElement(node) {
12509         var kind = node.kind;
12510         return kind === 198 /* BindingElement */
12511             || kind === 222 /* OmittedExpression */;
12512     }
12513     ts.isArrayBindingElement = isArrayBindingElement;
12514     /**
12515      * Determines whether the BindingOrAssignmentElement is a BindingElement-like declaration
12516      */
12517     /* @internal */
12518     function isDeclarationBindingElement(bindingElement) {
12519         switch (bindingElement.kind) {
12520             case 249 /* VariableDeclaration */:
12521             case 160 /* Parameter */:
12522             case 198 /* BindingElement */:
12523                 return true;
12524         }
12525         return false;
12526     }
12527     ts.isDeclarationBindingElement = isDeclarationBindingElement;
12528     /**
12529      * Determines whether a node is a BindingOrAssignmentPattern
12530      */
12531     /* @internal */
12532     function isBindingOrAssignmentPattern(node) {
12533         return isObjectBindingOrAssignmentPattern(node)
12534             || isArrayBindingOrAssignmentPattern(node);
12535     }
12536     ts.isBindingOrAssignmentPattern = isBindingOrAssignmentPattern;
12537     /**
12538      * Determines whether a node is an ObjectBindingOrAssignmentPattern
12539      */
12540     /* @internal */
12541     function isObjectBindingOrAssignmentPattern(node) {
12542         switch (node.kind) {
12543             case 196 /* ObjectBindingPattern */:
12544             case 200 /* ObjectLiteralExpression */:
12545                 return true;
12546         }
12547         return false;
12548     }
12549     ts.isObjectBindingOrAssignmentPattern = isObjectBindingOrAssignmentPattern;
12550     /**
12551      * Determines whether a node is an ArrayBindingOrAssignmentPattern
12552      */
12553     /* @internal */
12554     function isArrayBindingOrAssignmentPattern(node) {
12555         switch (node.kind) {
12556             case 197 /* ArrayBindingPattern */:
12557             case 199 /* ArrayLiteralExpression */:
12558                 return true;
12559         }
12560         return false;
12561     }
12562     ts.isArrayBindingOrAssignmentPattern = isArrayBindingOrAssignmentPattern;
12563     /* @internal */
12564     function isPropertyAccessOrQualifiedNameOrImportTypeNode(node) {
12565         var kind = node.kind;
12566         return kind === 201 /* PropertyAccessExpression */
12567             || kind === 157 /* QualifiedName */
12568             || kind === 195 /* ImportType */;
12569     }
12570     ts.isPropertyAccessOrQualifiedNameOrImportTypeNode = isPropertyAccessOrQualifiedNameOrImportTypeNode;
12571     // Expression
12572     function isPropertyAccessOrQualifiedName(node) {
12573         var kind = node.kind;
12574         return kind === 201 /* PropertyAccessExpression */
12575             || kind === 157 /* QualifiedName */;
12576     }
12577     ts.isPropertyAccessOrQualifiedName = isPropertyAccessOrQualifiedName;
12578     function isCallLikeExpression(node) {
12579         switch (node.kind) {
12580             case 275 /* JsxOpeningElement */:
12581             case 274 /* JsxSelfClosingElement */:
12582             case 203 /* CallExpression */:
12583             case 204 /* NewExpression */:
12584             case 205 /* TaggedTemplateExpression */:
12585             case 161 /* Decorator */:
12586                 return true;
12587             default:
12588                 return false;
12589         }
12590     }
12591     ts.isCallLikeExpression = isCallLikeExpression;
12592     function isCallOrNewExpression(node) {
12593         return node.kind === 203 /* CallExpression */ || node.kind === 204 /* NewExpression */;
12594     }
12595     ts.isCallOrNewExpression = isCallOrNewExpression;
12596     function isTemplateLiteral(node) {
12597         var kind = node.kind;
12598         return kind === 218 /* TemplateExpression */
12599             || kind === 14 /* NoSubstitutionTemplateLiteral */;
12600     }
12601     ts.isTemplateLiteral = isTemplateLiteral;
12602     /* @internal */
12603     function isLeftHandSideExpression(node) {
12604         return isLeftHandSideExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12605     }
12606     ts.isLeftHandSideExpression = isLeftHandSideExpression;
12607     function isLeftHandSideExpressionKind(kind) {
12608         switch (kind) {
12609             case 201 /* PropertyAccessExpression */:
12610             case 202 /* ElementAccessExpression */:
12611             case 204 /* NewExpression */:
12612             case 203 /* CallExpression */:
12613             case 273 /* JsxElement */:
12614             case 274 /* JsxSelfClosingElement */:
12615             case 277 /* JsxFragment */:
12616             case 205 /* TaggedTemplateExpression */:
12617             case 199 /* ArrayLiteralExpression */:
12618             case 207 /* ParenthesizedExpression */:
12619             case 200 /* ObjectLiteralExpression */:
12620             case 221 /* ClassExpression */:
12621             case 208 /* FunctionExpression */:
12622             case 78 /* Identifier */:
12623             case 13 /* RegularExpressionLiteral */:
12624             case 8 /* NumericLiteral */:
12625             case 9 /* BigIntLiteral */:
12626             case 10 /* StringLiteral */:
12627             case 14 /* NoSubstitutionTemplateLiteral */:
12628             case 218 /* TemplateExpression */:
12629             case 94 /* FalseKeyword */:
12630             case 103 /* NullKeyword */:
12631             case 107 /* ThisKeyword */:
12632             case 109 /* TrueKeyword */:
12633             case 105 /* SuperKeyword */:
12634             case 225 /* NonNullExpression */:
12635             case 226 /* MetaProperty */:
12636             case 99 /* ImportKeyword */: // technically this is only an Expression if it's in a CallExpression
12637                 return true;
12638             default:
12639                 return false;
12640         }
12641     }
12642     /* @internal */
12643     function isUnaryExpression(node) {
12644         return isUnaryExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12645     }
12646     ts.isUnaryExpression = isUnaryExpression;
12647     function isUnaryExpressionKind(kind) {
12648         switch (kind) {
12649             case 214 /* PrefixUnaryExpression */:
12650             case 215 /* PostfixUnaryExpression */:
12651             case 210 /* DeleteExpression */:
12652             case 211 /* TypeOfExpression */:
12653             case 212 /* VoidExpression */:
12654             case 213 /* AwaitExpression */:
12655             case 206 /* TypeAssertionExpression */:
12656                 return true;
12657             default:
12658                 return isLeftHandSideExpressionKind(kind);
12659         }
12660     }
12661     /* @internal */
12662     function isUnaryExpressionWithWrite(expr) {
12663         switch (expr.kind) {
12664             case 215 /* PostfixUnaryExpression */:
12665                 return true;
12666             case 214 /* PrefixUnaryExpression */:
12667                 return expr.operator === 45 /* PlusPlusToken */ ||
12668                     expr.operator === 46 /* MinusMinusToken */;
12669             default:
12670                 return false;
12671         }
12672     }
12673     ts.isUnaryExpressionWithWrite = isUnaryExpressionWithWrite;
12674     /* @internal */
12675     /**
12676      * Determines whether a node is an expression based only on its kind.
12677      * Use `isExpressionNode` if not in transforms.
12678      */
12679     function isExpression(node) {
12680         return isExpressionKind(skipPartiallyEmittedExpressions(node).kind);
12681     }
12682     ts.isExpression = isExpression;
12683     function isExpressionKind(kind) {
12684         switch (kind) {
12685             case 217 /* ConditionalExpression */:
12686             case 219 /* YieldExpression */:
12687             case 209 /* ArrowFunction */:
12688             case 216 /* BinaryExpression */:
12689             case 220 /* SpreadElement */:
12690             case 224 /* AsExpression */:
12691             case 222 /* OmittedExpression */:
12692             case 337 /* CommaListExpression */:
12693             case 336 /* PartiallyEmittedExpression */:
12694                 return true;
12695             default:
12696                 return isUnaryExpressionKind(kind);
12697         }
12698     }
12699     function isAssertionExpression(node) {
12700         var kind = node.kind;
12701         return kind === 206 /* TypeAssertionExpression */
12702             || kind === 224 /* AsExpression */;
12703     }
12704     ts.isAssertionExpression = isAssertionExpression;
12705     /* @internal */
12706     function isNotEmittedOrPartiallyEmittedNode(node) {
12707         return ts.isNotEmittedStatement(node)
12708             || ts.isPartiallyEmittedExpression(node);
12709     }
12710     ts.isNotEmittedOrPartiallyEmittedNode = isNotEmittedOrPartiallyEmittedNode;
12711     function isIterationStatement(node, lookInLabeledStatements) {
12712         switch (node.kind) {
12713             case 237 /* ForStatement */:
12714             case 238 /* ForInStatement */:
12715             case 239 /* ForOfStatement */:
12716             case 235 /* DoStatement */:
12717             case 236 /* WhileStatement */:
12718                 return true;
12719             case 245 /* LabeledStatement */:
12720                 return lookInLabeledStatements && isIterationStatement(node.statement, lookInLabeledStatements);
12721         }
12722         return false;
12723     }
12724     ts.isIterationStatement = isIterationStatement;
12725     /* @internal */
12726     function isScopeMarker(node) {
12727         return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
12728     }
12729     ts.isScopeMarker = isScopeMarker;
12730     /* @internal */
12731     function hasScopeMarker(statements) {
12732         return ts.some(statements, isScopeMarker);
12733     }
12734     ts.hasScopeMarker = hasScopeMarker;
12735     /* @internal */
12736     function needsScopeMarker(result) {
12737         return !ts.isAnyImportOrReExport(result) && !ts.isExportAssignment(result) && !ts.hasSyntacticModifier(result, 1 /* Export */) && !ts.isAmbientModule(result);
12738     }
12739     ts.needsScopeMarker = needsScopeMarker;
12740     /* @internal */
12741     function isExternalModuleIndicator(result) {
12742         // Exported top-level member indicates moduleness
12743         return ts.isAnyImportOrReExport(result) || ts.isExportAssignment(result) || ts.hasSyntacticModifier(result, 1 /* Export */);
12744     }
12745     ts.isExternalModuleIndicator = isExternalModuleIndicator;
12746     /* @internal */
12747     function isForInOrOfStatement(node) {
12748         return node.kind === 238 /* ForInStatement */ || node.kind === 239 /* ForOfStatement */;
12749     }
12750     ts.isForInOrOfStatement = isForInOrOfStatement;
12751     // Element
12752     /* @internal */
12753     function isConciseBody(node) {
12754         return ts.isBlock(node)
12755             || isExpression(node);
12756     }
12757     ts.isConciseBody = isConciseBody;
12758     /* @internal */
12759     function isFunctionBody(node) {
12760         return ts.isBlock(node);
12761     }
12762     ts.isFunctionBody = isFunctionBody;
12763     /* @internal */
12764     function isForInitializer(node) {
12765         return ts.isVariableDeclarationList(node)
12766             || isExpression(node);
12767     }
12768     ts.isForInitializer = isForInitializer;
12769     /* @internal */
12770     function isModuleBody(node) {
12771         var kind = node.kind;
12772         return kind === 257 /* ModuleBlock */
12773             || kind === 256 /* ModuleDeclaration */
12774             || kind === 78 /* Identifier */;
12775     }
12776     ts.isModuleBody = isModuleBody;
12777     /* @internal */
12778     function isNamespaceBody(node) {
12779         var kind = node.kind;
12780         return kind === 257 /* ModuleBlock */
12781             || kind === 256 /* ModuleDeclaration */;
12782     }
12783     ts.isNamespaceBody = isNamespaceBody;
12784     /* @internal */
12785     function isJSDocNamespaceBody(node) {
12786         var kind = node.kind;
12787         return kind === 78 /* Identifier */
12788             || kind === 256 /* ModuleDeclaration */;
12789     }
12790     ts.isJSDocNamespaceBody = isJSDocNamespaceBody;
12791     /* @internal */
12792     function isNamedImportBindings(node) {
12793         var kind = node.kind;
12794         return kind === 264 /* NamedImports */
12795             || kind === 263 /* NamespaceImport */;
12796     }
12797     ts.isNamedImportBindings = isNamedImportBindings;
12798     /* @internal */
12799     function isModuleOrEnumDeclaration(node) {
12800         return node.kind === 256 /* ModuleDeclaration */ || node.kind === 255 /* EnumDeclaration */;
12801     }
12802     ts.isModuleOrEnumDeclaration = isModuleOrEnumDeclaration;
12803     function isDeclarationKind(kind) {
12804         return kind === 209 /* ArrowFunction */
12805             || kind === 198 /* BindingElement */
12806             || kind === 252 /* ClassDeclaration */
12807             || kind === 221 /* ClassExpression */
12808             || kind === 166 /* Constructor */
12809             || kind === 255 /* EnumDeclaration */
12810             || kind === 291 /* EnumMember */
12811             || kind === 270 /* ExportSpecifier */
12812             || kind === 251 /* FunctionDeclaration */
12813             || kind === 208 /* FunctionExpression */
12814             || kind === 167 /* GetAccessor */
12815             || kind === 262 /* ImportClause */
12816             || kind === 260 /* ImportEqualsDeclaration */
12817             || kind === 265 /* ImportSpecifier */
12818             || kind === 253 /* InterfaceDeclaration */
12819             || kind === 280 /* JsxAttribute */
12820             || kind === 165 /* MethodDeclaration */
12821             || kind === 164 /* MethodSignature */
12822             || kind === 256 /* ModuleDeclaration */
12823             || kind === 259 /* NamespaceExportDeclaration */
12824             || kind === 263 /* NamespaceImport */
12825             || kind === 269 /* NamespaceExport */
12826             || kind === 160 /* Parameter */
12827             || kind === 288 /* PropertyAssignment */
12828             || kind === 163 /* PropertyDeclaration */
12829             || kind === 162 /* PropertySignature */
12830             || kind === 168 /* SetAccessor */
12831             || kind === 289 /* ShorthandPropertyAssignment */
12832             || kind === 254 /* TypeAliasDeclaration */
12833             || kind === 159 /* TypeParameter */
12834             || kind === 249 /* VariableDeclaration */
12835             || kind === 331 /* JSDocTypedefTag */
12836             || kind === 324 /* JSDocCallbackTag */
12837             || kind === 333 /* JSDocPropertyTag */;
12838     }
12839     function isDeclarationStatementKind(kind) {
12840         return kind === 251 /* FunctionDeclaration */
12841             || kind === 271 /* MissingDeclaration */
12842             || kind === 252 /* ClassDeclaration */
12843             || kind === 253 /* InterfaceDeclaration */
12844             || kind === 254 /* TypeAliasDeclaration */
12845             || kind === 255 /* EnumDeclaration */
12846             || kind === 256 /* ModuleDeclaration */
12847             || kind === 261 /* ImportDeclaration */
12848             || kind === 260 /* ImportEqualsDeclaration */
12849             || kind === 267 /* ExportDeclaration */
12850             || kind === 266 /* ExportAssignment */
12851             || kind === 259 /* NamespaceExportDeclaration */;
12852     }
12853     function isStatementKindButNotDeclarationKind(kind) {
12854         return kind === 241 /* BreakStatement */
12855             || kind === 240 /* ContinueStatement */
12856             || kind === 248 /* DebuggerStatement */
12857             || kind === 235 /* DoStatement */
12858             || kind === 233 /* ExpressionStatement */
12859             || kind === 231 /* EmptyStatement */
12860             || kind === 238 /* ForInStatement */
12861             || kind === 239 /* ForOfStatement */
12862             || kind === 237 /* ForStatement */
12863             || kind === 234 /* IfStatement */
12864             || kind === 245 /* LabeledStatement */
12865             || kind === 242 /* ReturnStatement */
12866             || kind === 244 /* SwitchStatement */
12867             || kind === 246 /* ThrowStatement */
12868             || kind === 247 /* TryStatement */
12869             || kind === 232 /* VariableStatement */
12870             || kind === 236 /* WhileStatement */
12871             || kind === 243 /* WithStatement */
12872             || kind === 335 /* NotEmittedStatement */
12873             || kind === 339 /* EndOfDeclarationMarker */
12874             || kind === 338 /* MergeDeclarationMarker */;
12875     }
12876     /* @internal */
12877     function isDeclaration(node) {
12878         if (node.kind === 159 /* TypeParameter */) {
12879             return (node.parent && node.parent.kind !== 330 /* JSDocTemplateTag */) || ts.isInJSFile(node);
12880         }
12881         return isDeclarationKind(node.kind);
12882     }
12883     ts.isDeclaration = isDeclaration;
12884     /* @internal */
12885     function isDeclarationStatement(node) {
12886         return isDeclarationStatementKind(node.kind);
12887     }
12888     ts.isDeclarationStatement = isDeclarationStatement;
12889     /**
12890      * Determines whether the node is a statement that is not also a declaration
12891      */
12892     /* @internal */
12893     function isStatementButNotDeclaration(node) {
12894         return isStatementKindButNotDeclarationKind(node.kind);
12895     }
12896     ts.isStatementButNotDeclaration = isStatementButNotDeclaration;
12897     /* @internal */
12898     function isStatement(node) {
12899         var kind = node.kind;
12900         return isStatementKindButNotDeclarationKind(kind)
12901             || isDeclarationStatementKind(kind)
12902             || isBlockStatement(node);
12903     }
12904     ts.isStatement = isStatement;
12905     function isBlockStatement(node) {
12906         if (node.kind !== 230 /* Block */)
12907             return false;
12908         if (node.parent !== undefined) {
12909             if (node.parent.kind === 247 /* TryStatement */ || node.parent.kind === 287 /* CatchClause */) {
12910                 return false;
12911             }
12912         }
12913         return !ts.isFunctionBlock(node);
12914     }
12915     /**
12916      * NOTE: This is similar to `isStatement` but does not access parent pointers.
12917      */
12918     /* @internal */
12919     function isStatementOrBlock(node) {
12920         var kind = node.kind;
12921         return isStatementKindButNotDeclarationKind(kind)
12922             || isDeclarationStatementKind(kind)
12923             || kind === 230 /* Block */;
12924     }
12925     ts.isStatementOrBlock = isStatementOrBlock;
12926     // Module references
12927     /* @internal */
12928     function isModuleReference(node) {
12929         var kind = node.kind;
12930         return kind === 272 /* ExternalModuleReference */
12931             || kind === 157 /* QualifiedName */
12932             || kind === 78 /* Identifier */;
12933     }
12934     ts.isModuleReference = isModuleReference;
12935     // JSX
12936     /* @internal */
12937     function isJsxTagNameExpression(node) {
12938         var kind = node.kind;
12939         return kind === 107 /* ThisKeyword */
12940             || kind === 78 /* Identifier */
12941             || kind === 201 /* PropertyAccessExpression */;
12942     }
12943     ts.isJsxTagNameExpression = isJsxTagNameExpression;
12944     /* @internal */
12945     function isJsxChild(node) {
12946         var kind = node.kind;
12947         return kind === 273 /* JsxElement */
12948             || kind === 283 /* JsxExpression */
12949             || kind === 274 /* JsxSelfClosingElement */
12950             || kind === 11 /* JsxText */
12951             || kind === 277 /* JsxFragment */;
12952     }
12953     ts.isJsxChild = isJsxChild;
12954     /* @internal */
12955     function isJsxAttributeLike(node) {
12956         var kind = node.kind;
12957         return kind === 280 /* JsxAttribute */
12958             || kind === 282 /* JsxSpreadAttribute */;
12959     }
12960     ts.isJsxAttributeLike = isJsxAttributeLike;
12961     /* @internal */
12962     function isStringLiteralOrJsxExpression(node) {
12963         var kind = node.kind;
12964         return kind === 10 /* StringLiteral */
12965             || kind === 283 /* JsxExpression */;
12966     }
12967     ts.isStringLiteralOrJsxExpression = isStringLiteralOrJsxExpression;
12968     function isJsxOpeningLikeElement(node) {
12969         var kind = node.kind;
12970         return kind === 275 /* JsxOpeningElement */
12971             || kind === 274 /* JsxSelfClosingElement */;
12972     }
12973     ts.isJsxOpeningLikeElement = isJsxOpeningLikeElement;
12974     // Clauses
12975     function isCaseOrDefaultClause(node) {
12976         var kind = node.kind;
12977         return kind === 284 /* CaseClause */
12978             || kind === 285 /* DefaultClause */;
12979     }
12980     ts.isCaseOrDefaultClause = isCaseOrDefaultClause;
12981     // JSDoc
12982     /** True if node is of some JSDoc syntax kind. */
12983     /* @internal */
12984     function isJSDocNode(node) {
12985         return node.kind >= 301 /* FirstJSDocNode */ && node.kind <= 333 /* LastJSDocNode */;
12986     }
12987     ts.isJSDocNode = isJSDocNode;
12988     /** True if node is of a kind that may contain comment text. */
12989     function isJSDocCommentContainingNode(node) {
12990         return node.kind === 311 /* JSDocComment */ || node.kind === 310 /* JSDocNamepathType */ || isJSDocTag(node) || ts.isJSDocTypeLiteral(node) || ts.isJSDocSignature(node);
12991     }
12992     ts.isJSDocCommentContainingNode = isJSDocCommentContainingNode;
12993     // TODO: determine what this does before making it public.
12994     /* @internal */
12995     function isJSDocTag(node) {
12996         return node.kind >= 314 /* FirstJSDocTagNode */ && node.kind <= 333 /* LastJSDocTagNode */;
12997     }
12998     ts.isJSDocTag = isJSDocTag;
12999     function isSetAccessor(node) {
13000         return node.kind === 168 /* SetAccessor */;
13001     }
13002     ts.isSetAccessor = isSetAccessor;
13003     function isGetAccessor(node) {
13004         return node.kind === 167 /* GetAccessor */;
13005     }
13006     ts.isGetAccessor = isGetAccessor;
13007     /** True if has jsdoc nodes attached to it. */
13008     /* @internal */
13009     // TODO: GH#19856 Would like to return `node is Node & { jsDoc: JSDoc[] }` but it causes long compile times
13010     function hasJSDocNodes(node) {
13011         var jsDoc = node.jsDoc;
13012         return !!jsDoc && jsDoc.length > 0;
13013     }
13014     ts.hasJSDocNodes = hasJSDocNodes;
13015     /** True if has type node attached to it. */
13016     /* @internal */
13017     function hasType(node) {
13018         return !!node.type;
13019     }
13020     ts.hasType = hasType;
13021     /** True if has initializer node attached to it. */
13022     /* @internal */
13023     function hasInitializer(node) {
13024         return !!node.initializer;
13025     }
13026     ts.hasInitializer = hasInitializer;
13027     /** True if has initializer node attached to it. */
13028     function hasOnlyExpressionInitializer(node) {
13029         switch (node.kind) {
13030             case 249 /* VariableDeclaration */:
13031             case 160 /* Parameter */:
13032             case 198 /* BindingElement */:
13033             case 162 /* PropertySignature */:
13034             case 163 /* PropertyDeclaration */:
13035             case 288 /* PropertyAssignment */:
13036             case 291 /* EnumMember */:
13037                 return true;
13038             default:
13039                 return false;
13040         }
13041     }
13042     ts.hasOnlyExpressionInitializer = hasOnlyExpressionInitializer;
13043     function isObjectLiteralElement(node) {
13044         return node.kind === 280 /* JsxAttribute */ || node.kind === 282 /* JsxSpreadAttribute */ || isObjectLiteralElementLike(node);
13045     }
13046     ts.isObjectLiteralElement = isObjectLiteralElement;
13047     /* @internal */
13048     function isTypeReferenceType(node) {
13049         return node.kind === 173 /* TypeReference */ || node.kind === 223 /* ExpressionWithTypeArguments */;
13050     }
13051     ts.isTypeReferenceType = isTypeReferenceType;
13052     var MAX_SMI_X86 = 1073741823;
13053     /* @internal */
13054     function guessIndentation(lines) {
13055         var indentation = MAX_SMI_X86;
13056         for (var _i = 0, lines_1 = lines; _i < lines_1.length; _i++) {
13057             var line = lines_1[_i];
13058             if (!line.length) {
13059                 continue;
13060             }
13061             var i = 0;
13062             for (; i < line.length && i < indentation; i++) {
13063                 if (!ts.isWhiteSpaceLike(line.charCodeAt(i))) {
13064                     break;
13065                 }
13066             }
13067             if (i < indentation) {
13068                 indentation = i;
13069             }
13070             if (indentation === 0) {
13071                 return 0;
13072             }
13073         }
13074         return indentation === MAX_SMI_X86 ? undefined : indentation;
13075     }
13076     ts.guessIndentation = guessIndentation;
13077     function isStringLiteralLike(node) {
13078         return node.kind === 10 /* StringLiteral */ || node.kind === 14 /* NoSubstitutionTemplateLiteral */;
13079     }
13080     ts.isStringLiteralLike = isStringLiteralLike;
13081     // #endregion
13082 })(ts || (ts = {}));
13083 /* @internal */
13084 var ts;
13085 (function (ts) {
13086     ts.resolvingEmptyArray = [];
13087     ts.externalHelpersModuleNameText = "tslib";
13088     ts.defaultMaximumTruncationLength = 160;
13089     ts.noTruncationMaximumTruncationLength = 1000000;
13090     function getDeclarationOfKind(symbol, kind) {
13091         var declarations = symbol.declarations;
13092         if (declarations) {
13093             for (var _i = 0, declarations_1 = declarations; _i < declarations_1.length; _i++) {
13094                 var declaration = declarations_1[_i];
13095                 if (declaration.kind === kind) {
13096                     return declaration;
13097                 }
13098             }
13099         }
13100         return undefined;
13101     }
13102     ts.getDeclarationOfKind = getDeclarationOfKind;
13103     /**
13104      * Create a new escaped identifier map.
13105      * @deprecated Use `new Map<__String, T>()` instead.
13106      */
13107     function createUnderscoreEscapedMap() {
13108         return new ts.Map();
13109     }
13110     ts.createUnderscoreEscapedMap = createUnderscoreEscapedMap;
13111     /**
13112      * @deprecated Use `!!map?.size` instead
13113      */
13114     function hasEntries(map) {
13115         return !!map && !!map.size;
13116     }
13117     ts.hasEntries = hasEntries;
13118     function createSymbolTable(symbols) {
13119         var result = new ts.Map();
13120         if (symbols) {
13121             for (var _i = 0, symbols_1 = symbols; _i < symbols_1.length; _i++) {
13122                 var symbol = symbols_1[_i];
13123                 result.set(symbol.escapedName, symbol);
13124             }
13125         }
13126         return result;
13127     }
13128     ts.createSymbolTable = createSymbolTable;
13129     function isTransientSymbol(symbol) {
13130         return (symbol.flags & 33554432 /* Transient */) !== 0;
13131     }
13132     ts.isTransientSymbol = isTransientSymbol;
13133     var stringWriter = createSingleLineStringWriter();
13134     function createSingleLineStringWriter() {
13135         var str = "";
13136         var writeText = function (text) { return str += text; };
13137         return {
13138             getText: function () { return str; },
13139             write: writeText,
13140             rawWrite: writeText,
13141             writeKeyword: writeText,
13142             writeOperator: writeText,
13143             writePunctuation: writeText,
13144             writeSpace: writeText,
13145             writeStringLiteral: writeText,
13146             writeLiteral: writeText,
13147             writeParameter: writeText,
13148             writeProperty: writeText,
13149             writeSymbol: function (s, _) { return writeText(s); },
13150             writeTrailingSemicolon: writeText,
13151             writeComment: writeText,
13152             getTextPos: function () { return str.length; },
13153             getLine: function () { return 0; },
13154             getColumn: function () { return 0; },
13155             getIndent: function () { return 0; },
13156             isAtStartOfLine: function () { return false; },
13157             hasTrailingComment: function () { return false; },
13158             hasTrailingWhitespace: function () { return !!str.length && ts.isWhiteSpaceLike(str.charCodeAt(str.length - 1)); },
13159             // Completely ignore indentation for string writers.  And map newlines to
13160             // a single space.
13161             writeLine: function () { return str += " "; },
13162             increaseIndent: ts.noop,
13163             decreaseIndent: ts.noop,
13164             clear: function () { return str = ""; },
13165             trackSymbol: ts.noop,
13166             reportInaccessibleThisError: ts.noop,
13167             reportInaccessibleUniqueSymbolError: ts.noop,
13168             reportPrivateInBaseOfClassExpression: ts.noop,
13169         };
13170     }
13171     function changesAffectModuleResolution(oldOptions, newOptions) {
13172         return oldOptions.configFilePath !== newOptions.configFilePath ||
13173             optionsHaveModuleResolutionChanges(oldOptions, newOptions);
13174     }
13175     ts.changesAffectModuleResolution = changesAffectModuleResolution;
13176     function optionsHaveModuleResolutionChanges(oldOptions, newOptions) {
13177         return ts.moduleResolutionOptionDeclarations.some(function (o) {
13178             return !isJsonEqual(getCompilerOptionValue(oldOptions, o), getCompilerOptionValue(newOptions, o));
13179         });
13180     }
13181     ts.optionsHaveModuleResolutionChanges = optionsHaveModuleResolutionChanges;
13182     function forEachAncestor(node, callback) {
13183         while (true) {
13184             var res = callback(node);
13185             if (res === "quit")
13186                 return undefined;
13187             if (res !== undefined)
13188                 return res;
13189             if (ts.isSourceFile(node))
13190                 return undefined;
13191             node = node.parent;
13192         }
13193     }
13194     ts.forEachAncestor = forEachAncestor;
13195     /**
13196      * Calls `callback` for each entry in the map, returning the first truthy result.
13197      * Use `map.forEach` instead for normal iteration.
13198      */
13199     function forEachEntry(map, callback) {
13200         var iterator = map.entries();
13201         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
13202             var _a = iterResult.value, key = _a[0], value = _a[1];
13203             var result = callback(value, key);
13204             if (result) {
13205                 return result;
13206             }
13207         }
13208         return undefined;
13209     }
13210     ts.forEachEntry = forEachEntry;
13211     /** `forEachEntry` for just keys. */
13212     function forEachKey(map, callback) {
13213         var iterator = map.keys();
13214         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
13215             var result = callback(iterResult.value);
13216             if (result) {
13217                 return result;
13218             }
13219         }
13220         return undefined;
13221     }
13222     ts.forEachKey = forEachKey;
13223     /** Copy entries from `source` to `target`. */
13224     function copyEntries(source, target) {
13225         source.forEach(function (value, key) {
13226             target.set(key, value);
13227         });
13228     }
13229     ts.copyEntries = copyEntries;
13230     function usingSingleLineStringWriter(action) {
13231         var oldString = stringWriter.getText();
13232         try {
13233             action(stringWriter);
13234             return stringWriter.getText();
13235         }
13236         finally {
13237             stringWriter.clear();
13238             stringWriter.writeKeyword(oldString);
13239         }
13240     }
13241     ts.usingSingleLineStringWriter = usingSingleLineStringWriter;
13242     function getFullWidth(node) {
13243         return node.end - node.pos;
13244     }
13245     ts.getFullWidth = getFullWidth;
13246     function getResolvedModule(sourceFile, moduleNameText) {
13247         return sourceFile && sourceFile.resolvedModules && sourceFile.resolvedModules.get(moduleNameText);
13248     }
13249     ts.getResolvedModule = getResolvedModule;
13250     function setResolvedModule(sourceFile, moduleNameText, resolvedModule) {
13251         if (!sourceFile.resolvedModules) {
13252             sourceFile.resolvedModules = new ts.Map();
13253         }
13254         sourceFile.resolvedModules.set(moduleNameText, resolvedModule);
13255     }
13256     ts.setResolvedModule = setResolvedModule;
13257     function setResolvedTypeReferenceDirective(sourceFile, typeReferenceDirectiveName, resolvedTypeReferenceDirective) {
13258         if (!sourceFile.resolvedTypeReferenceDirectiveNames) {
13259             sourceFile.resolvedTypeReferenceDirectiveNames = new ts.Map();
13260         }
13261         sourceFile.resolvedTypeReferenceDirectiveNames.set(typeReferenceDirectiveName, resolvedTypeReferenceDirective);
13262     }
13263     ts.setResolvedTypeReferenceDirective = setResolvedTypeReferenceDirective;
13264     function projectReferenceIsEqualTo(oldRef, newRef) {
13265         return oldRef.path === newRef.path &&
13266             !oldRef.prepend === !newRef.prepend &&
13267             !oldRef.circular === !newRef.circular;
13268     }
13269     ts.projectReferenceIsEqualTo = projectReferenceIsEqualTo;
13270     function moduleResolutionIsEqualTo(oldResolution, newResolution) {
13271         return oldResolution.isExternalLibraryImport === newResolution.isExternalLibraryImport &&
13272             oldResolution.extension === newResolution.extension &&
13273             oldResolution.resolvedFileName === newResolution.resolvedFileName &&
13274             oldResolution.originalPath === newResolution.originalPath &&
13275             packageIdIsEqual(oldResolution.packageId, newResolution.packageId);
13276     }
13277     ts.moduleResolutionIsEqualTo = moduleResolutionIsEqualTo;
13278     function packageIdIsEqual(a, b) {
13279         return a === b || !!a && !!b && a.name === b.name && a.subModuleName === b.subModuleName && a.version === b.version;
13280     }
13281     function packageIdToString(_a) {
13282         var name = _a.name, subModuleName = _a.subModuleName, version = _a.version;
13283         var fullName = subModuleName ? name + "/" + subModuleName : name;
13284         return fullName + "@" + version;
13285     }
13286     ts.packageIdToString = packageIdToString;
13287     function typeDirectiveIsEqualTo(oldResolution, newResolution) {
13288         return oldResolution.resolvedFileName === newResolution.resolvedFileName && oldResolution.primary === newResolution.primary;
13289     }
13290     ts.typeDirectiveIsEqualTo = typeDirectiveIsEqualTo;
13291     function hasChangesInResolutions(names, newResolutions, oldResolutions, comparer) {
13292         ts.Debug.assert(names.length === newResolutions.length);
13293         for (var i = 0; i < names.length; i++) {
13294             var newResolution = newResolutions[i];
13295             var oldResolution = oldResolutions && oldResolutions.get(names[i]);
13296             var changed = oldResolution
13297                 ? !newResolution || !comparer(oldResolution, newResolution)
13298                 : newResolution;
13299             if (changed) {
13300                 return true;
13301             }
13302         }
13303         return false;
13304     }
13305     ts.hasChangesInResolutions = hasChangesInResolutions;
13306     // Returns true if this node contains a parse error anywhere underneath it.
13307     function containsParseError(node) {
13308         aggregateChildData(node);
13309         return (node.flags & 262144 /* ThisNodeOrAnySubNodesHasError */) !== 0;
13310     }
13311     ts.containsParseError = containsParseError;
13312     function aggregateChildData(node) {
13313         if (!(node.flags & 524288 /* HasAggregatedChildData */)) {
13314             // A node is considered to contain a parse error if:
13315             //  a) the parser explicitly marked that it had an error
13316             //  b) any of it's children reported that it had an error.
13317             var thisNodeOrAnySubNodesHasError = ((node.flags & 65536 /* ThisNodeHasError */) !== 0) ||
13318                 ts.forEachChild(node, containsParseError);
13319             // If so, mark ourselves accordingly.
13320             if (thisNodeOrAnySubNodesHasError) {
13321                 node.flags |= 262144 /* ThisNodeOrAnySubNodesHasError */;
13322             }
13323             // Also mark that we've propagated the child information to this node.  This way we can
13324             // always consult the bit directly on this node without needing to check its children
13325             // again.
13326             node.flags |= 524288 /* HasAggregatedChildData */;
13327         }
13328     }
13329     function getSourceFileOfNode(node) {
13330         while (node && node.kind !== 297 /* SourceFile */) {
13331             node = node.parent;
13332         }
13333         return node;
13334     }
13335     ts.getSourceFileOfNode = getSourceFileOfNode;
13336     function isStatementWithLocals(node) {
13337         switch (node.kind) {
13338             case 230 /* Block */:
13339             case 258 /* CaseBlock */:
13340             case 237 /* ForStatement */:
13341             case 238 /* ForInStatement */:
13342             case 239 /* ForOfStatement */:
13343                 return true;
13344         }
13345         return false;
13346     }
13347     ts.isStatementWithLocals = isStatementWithLocals;
13348     function getStartPositionOfLine(line, sourceFile) {
13349         ts.Debug.assert(line >= 0);
13350         return ts.getLineStarts(sourceFile)[line];
13351     }
13352     ts.getStartPositionOfLine = getStartPositionOfLine;
13353     // This is a useful function for debugging purposes.
13354     function nodePosToString(node) {
13355         var file = getSourceFileOfNode(node);
13356         var loc = ts.getLineAndCharacterOfPosition(file, node.pos);
13357         return file.fileName + "(" + (loc.line + 1) + "," + (loc.character + 1) + ")";
13358     }
13359     ts.nodePosToString = nodePosToString;
13360     function getEndLinePosition(line, sourceFile) {
13361         ts.Debug.assert(line >= 0);
13362         var lineStarts = ts.getLineStarts(sourceFile);
13363         var lineIndex = line;
13364         var sourceText = sourceFile.text;
13365         if (lineIndex + 1 === lineStarts.length) {
13366             // last line - return EOF
13367             return sourceText.length - 1;
13368         }
13369         else {
13370             // current line start
13371             var start = lineStarts[lineIndex];
13372             // take the start position of the next line - 1 = it should be some line break
13373             var pos = lineStarts[lineIndex + 1] - 1;
13374             ts.Debug.assert(ts.isLineBreak(sourceText.charCodeAt(pos)));
13375             // walk backwards skipping line breaks, stop the the beginning of current line.
13376             // i.e:
13377             // <some text>
13378             // $ <- end of line for this position should match the start position
13379             while (start <= pos && ts.isLineBreak(sourceText.charCodeAt(pos))) {
13380                 pos--;
13381             }
13382             return pos;
13383         }
13384     }
13385     ts.getEndLinePosition = getEndLinePosition;
13386     /**
13387      * Returns a value indicating whether a name is unique globally or within the current file.
13388      * 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`.
13389      */
13390     function isFileLevelUniqueName(sourceFile, name, hasGlobalName) {
13391         return !(hasGlobalName && hasGlobalName(name)) && !sourceFile.identifiers.has(name);
13392     }
13393     ts.isFileLevelUniqueName = isFileLevelUniqueName;
13394     // Returns true if this node is missing from the actual source code. A 'missing' node is different
13395     // from 'undefined/defined'. When a node is undefined (which can happen for optional nodes
13396     // in the tree), it is definitely missing. However, a node may be defined, but still be
13397     // missing.  This happens whenever the parser knows it needs to parse something, but can't
13398     // get anything in the source code that it expects at that location. For example:
13399     //
13400     //          let a: ;
13401     //
13402     // Here, the Type in the Type-Annotation is not-optional (as there is a colon in the source
13403     // code). So the parser will attempt to parse out a type, and will create an actual node.
13404     // However, this node will be 'missing' in the sense that no actual source-code/tokens are
13405     // contained within it.
13406     function nodeIsMissing(node) {
13407         if (node === undefined) {
13408             return true;
13409         }
13410         return node.pos === node.end && node.pos >= 0 && node.kind !== 1 /* EndOfFileToken */;
13411     }
13412     ts.nodeIsMissing = nodeIsMissing;
13413     function nodeIsPresent(node) {
13414         return !nodeIsMissing(node);
13415     }
13416     ts.nodeIsPresent = nodeIsPresent;
13417     function insertStatementsAfterPrologue(to, from, isPrologueDirective) {
13418         if (from === undefined || from.length === 0)
13419             return to;
13420         var statementIndex = 0;
13421         // skip all prologue directives to insert at the correct position
13422         for (; statementIndex < to.length; ++statementIndex) {
13423             if (!isPrologueDirective(to[statementIndex])) {
13424                 break;
13425             }
13426         }
13427         to.splice.apply(to, __spreadArrays([statementIndex, 0], from));
13428         return to;
13429     }
13430     function insertStatementAfterPrologue(to, statement, isPrologueDirective) {
13431         if (statement === undefined)
13432             return to;
13433         var statementIndex = 0;
13434         // skip all prologue directives to insert at the correct position
13435         for (; statementIndex < to.length; ++statementIndex) {
13436             if (!isPrologueDirective(to[statementIndex])) {
13437                 break;
13438             }
13439         }
13440         to.splice(statementIndex, 0, statement);
13441         return to;
13442     }
13443     function isAnyPrologueDirective(node) {
13444         return isPrologueDirective(node) || !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
13445     }
13446     /**
13447      * Prepends statements to an array while taking care of prologue directives.
13448      */
13449     function insertStatementsAfterStandardPrologue(to, from) {
13450         return insertStatementsAfterPrologue(to, from, isPrologueDirective);
13451     }
13452     ts.insertStatementsAfterStandardPrologue = insertStatementsAfterStandardPrologue;
13453     function insertStatementsAfterCustomPrologue(to, from) {
13454         return insertStatementsAfterPrologue(to, from, isAnyPrologueDirective);
13455     }
13456     ts.insertStatementsAfterCustomPrologue = insertStatementsAfterCustomPrologue;
13457     /**
13458      * Prepends statements to an array while taking care of prologue directives.
13459      */
13460     function insertStatementAfterStandardPrologue(to, statement) {
13461         return insertStatementAfterPrologue(to, statement, isPrologueDirective);
13462     }
13463     ts.insertStatementAfterStandardPrologue = insertStatementAfterStandardPrologue;
13464     function insertStatementAfterCustomPrologue(to, statement) {
13465         return insertStatementAfterPrologue(to, statement, isAnyPrologueDirective);
13466     }
13467     ts.insertStatementAfterCustomPrologue = insertStatementAfterCustomPrologue;
13468     /**
13469      * Determine if the given comment is a triple-slash
13470      *
13471      * @return true if the comment is a triple-slash comment else false
13472      */
13473     function isRecognizedTripleSlashComment(text, commentPos, commentEnd) {
13474         // Verify this is /// comment, but do the regexp match only when we first can find /// in the comment text
13475         // so that we don't end up computing comment string and doing match for all // comments
13476         if (text.charCodeAt(commentPos + 1) === 47 /* slash */ &&
13477             commentPos + 2 < commentEnd &&
13478             text.charCodeAt(commentPos + 2) === 47 /* slash */) {
13479             var textSubStr = text.substring(commentPos, commentEnd);
13480             return textSubStr.match(ts.fullTripleSlashReferencePathRegEx) ||
13481                 textSubStr.match(ts.fullTripleSlashAMDReferencePathRegEx) ||
13482                 textSubStr.match(fullTripleSlashReferenceTypeReferenceDirectiveRegEx) ||
13483                 textSubStr.match(defaultLibReferenceRegEx) ?
13484                 true : false;
13485         }
13486         return false;
13487     }
13488     ts.isRecognizedTripleSlashComment = isRecognizedTripleSlashComment;
13489     function isPinnedComment(text, start) {
13490         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
13491             text.charCodeAt(start + 2) === 33 /* exclamation */;
13492     }
13493     ts.isPinnedComment = isPinnedComment;
13494     function createCommentDirectivesMap(sourceFile, commentDirectives) {
13495         var directivesByLine = new ts.Map(commentDirectives.map(function (commentDirective) { return ([
13496             "" + ts.getLineAndCharacterOfPosition(sourceFile, commentDirective.range.end).line,
13497             commentDirective,
13498         ]); }));
13499         var usedLines = new ts.Map();
13500         return { getUnusedExpectations: getUnusedExpectations, markUsed: markUsed };
13501         function getUnusedExpectations() {
13502             return ts.arrayFrom(directivesByLine.entries())
13503                 .filter(function (_a) {
13504                 var line = _a[0], directive = _a[1];
13505                 return directive.type === 0 /* ExpectError */ && !usedLines.get(line);
13506             })
13507                 .map(function (_a) {
13508                 var _ = _a[0], directive = _a[1];
13509                 return directive;
13510             });
13511         }
13512         function markUsed(line) {
13513             if (!directivesByLine.has("" + line)) {
13514                 return false;
13515             }
13516             usedLines.set("" + line, true);
13517             return true;
13518         }
13519     }
13520     ts.createCommentDirectivesMap = createCommentDirectivesMap;
13521     function getTokenPosOfNode(node, sourceFile, includeJsDoc) {
13522         // With nodes that have no width (i.e. 'Missing' nodes), we actually *don't*
13523         // want to skip trivia because this will launch us forward to the next token.
13524         if (nodeIsMissing(node)) {
13525             return node.pos;
13526         }
13527         if (ts.isJSDocNode(node) || node.kind === 11 /* JsxText */) {
13528             // JsxText cannot actually contain comments, even though the scanner will think it sees comments
13529             return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos, /*stopAfterLineBreak*/ false, /*stopAtComments*/ true);
13530         }
13531         if (includeJsDoc && ts.hasJSDocNodes(node)) {
13532             return getTokenPosOfNode(node.jsDoc[0], sourceFile);
13533         }
13534         // For a syntax list, it is possible that one of its children has JSDocComment nodes, while
13535         // the syntax list itself considers them as normal trivia. Therefore if we simply skip
13536         // trivia for the list, we may have skipped the JSDocComment as well. So we should process its
13537         // first child to determine the actual position of its first token.
13538         if (node.kind === 334 /* SyntaxList */ && node._children.length > 0) {
13539             return getTokenPosOfNode(node._children[0], sourceFile, includeJsDoc);
13540         }
13541         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.pos);
13542     }
13543     ts.getTokenPosOfNode = getTokenPosOfNode;
13544     function getNonDecoratorTokenPosOfNode(node, sourceFile) {
13545         if (nodeIsMissing(node) || !node.decorators) {
13546             return getTokenPosOfNode(node, sourceFile);
13547         }
13548         return ts.skipTrivia((sourceFile || getSourceFileOfNode(node)).text, node.decorators.end);
13549     }
13550     ts.getNonDecoratorTokenPosOfNode = getNonDecoratorTokenPosOfNode;
13551     function getSourceTextOfNodeFromSourceFile(sourceFile, node, includeTrivia) {
13552         if (includeTrivia === void 0) { includeTrivia = false; }
13553         return getTextOfNodeFromSourceText(sourceFile.text, node, includeTrivia);
13554     }
13555     ts.getSourceTextOfNodeFromSourceFile = getSourceTextOfNodeFromSourceFile;
13556     function isJSDocTypeExpressionOrChild(node) {
13557         return !!ts.findAncestor(node, ts.isJSDocTypeExpression);
13558     }
13559     function isExportNamespaceAsDefaultDeclaration(node) {
13560         return !!(ts.isExportDeclaration(node) && node.exportClause && ts.isNamespaceExport(node.exportClause) && node.exportClause.name.escapedText === "default");
13561     }
13562     ts.isExportNamespaceAsDefaultDeclaration = isExportNamespaceAsDefaultDeclaration;
13563     function getTextOfNodeFromSourceText(sourceText, node, includeTrivia) {
13564         if (includeTrivia === void 0) { includeTrivia = false; }
13565         if (nodeIsMissing(node)) {
13566             return "";
13567         }
13568         var text = sourceText.substring(includeTrivia ? node.pos : ts.skipTrivia(sourceText, node.pos), node.end);
13569         if (isJSDocTypeExpressionOrChild(node)) {
13570             // strip space + asterisk at line start
13571             text = text.replace(/(^|\r?\n|\r)\s*\*\s*/g, "$1");
13572         }
13573         return text;
13574     }
13575     ts.getTextOfNodeFromSourceText = getTextOfNodeFromSourceText;
13576     function getTextOfNode(node, includeTrivia) {
13577         if (includeTrivia === void 0) { includeTrivia = false; }
13578         return getSourceTextOfNodeFromSourceFile(getSourceFileOfNode(node), node, includeTrivia);
13579     }
13580     ts.getTextOfNode = getTextOfNode;
13581     function getPos(range) {
13582         return range.pos;
13583     }
13584     /**
13585      * Note: it is expected that the `nodeArray` and the `node` are within the same file.
13586      * For example, searching for a `SourceFile` in a `SourceFile[]` wouldn't work.
13587      */
13588     function indexOfNode(nodeArray, node) {
13589         return ts.binarySearch(nodeArray, node, getPos, ts.compareValues);
13590     }
13591     ts.indexOfNode = indexOfNode;
13592     /**
13593      * Gets flags that control emit behavior of a node.
13594      */
13595     function getEmitFlags(node) {
13596         var emitNode = node.emitNode;
13597         return emitNode && emitNode.flags || 0;
13598     }
13599     ts.getEmitFlags = getEmitFlags;
13600     ;
13601     function getScriptTargetFeatures() {
13602         return {
13603             es2015: {
13604                 Array: ["find", "findIndex", "fill", "copyWithin", "entries", "keys", "values"],
13605                 RegExp: ["flags", "sticky", "unicode"],
13606                 Reflect: ["apply", "construct", "defineProperty", "deleteProperty", "get", " getOwnPropertyDescriptor", "getPrototypeOf", "has", "isExtensible", "ownKeys", "preventExtensions", "set", "setPrototypeOf"],
13607                 ArrayConstructor: ["from", "of"],
13608                 ObjectConstructor: ["assign", "getOwnPropertySymbols", "keys", "is", "setPrototypeOf"],
13609                 NumberConstructor: ["isFinite", "isInteger", "isNaN", "isSafeInteger", "parseFloat", "parseInt"],
13610                 Math: ["clz32", "imul", "sign", "log10", "log2", "log1p", "expm1", "cosh", "sinh", "tanh", "acosh", "asinh", "atanh", "hypot", "trunc", "fround", "cbrt"],
13611                 Map: ["entries", "keys", "values"],
13612                 Set: ["entries", "keys", "values"],
13613                 Promise: ts.emptyArray,
13614                 PromiseConstructor: ["all", "race", "reject", "resolve"],
13615                 Symbol: ["for", "keyFor"],
13616                 WeakMap: ["entries", "keys", "values"],
13617                 WeakSet: ["entries", "keys", "values"],
13618                 Iterator: ts.emptyArray,
13619                 AsyncIterator: ts.emptyArray,
13620                 String: ["codePointAt", "includes", "endsWith", "normalize", "repeat", "startsWith", "anchor", "big", "blink", "bold", "fixed", "fontcolor", "fontsize", "italics", "link", "small", "strike", "sub", "sup"],
13621                 StringConstructor: ["fromCodePoint", "raw"]
13622             },
13623             es2016: {
13624                 Array: ["includes"]
13625             },
13626             es2017: {
13627                 Atomics: ts.emptyArray,
13628                 SharedArrayBuffer: ts.emptyArray,
13629                 String: ["padStart", "padEnd"],
13630                 ObjectConstructor: ["values", "entries", "getOwnPropertyDescriptors"],
13631                 DateTimeFormat: ["formatToParts"]
13632             },
13633             es2018: {
13634                 Promise: ["finally"],
13635                 RegExpMatchArray: ["groups"],
13636                 RegExpExecArray: ["groups"],
13637                 RegExp: ["dotAll"],
13638                 Intl: ["PluralRules"],
13639                 AsyncIterable: ts.emptyArray,
13640                 AsyncIterableIterator: ts.emptyArray,
13641                 AsyncGenerator: ts.emptyArray,
13642                 AsyncGeneratorFunction: ts.emptyArray,
13643             },
13644             es2019: {
13645                 Array: ["flat", "flatMap"],
13646                 ObjectConstructor: ["fromEntries"],
13647                 String: ["trimStart", "trimEnd", "trimLeft", "trimRight"],
13648                 Symbol: ["description"]
13649             },
13650             es2020: {
13651                 BigInt: ts.emptyArray,
13652                 BigInt64Array: ts.emptyArray,
13653                 BigUint64Array: ts.emptyArray,
13654                 PromiseConstructor: ["allSettled"],
13655                 SymbolConstructor: ["matchAll"],
13656                 String: ["matchAll"],
13657                 DataView: ["setBigInt64", "setBigUint64", "getBigInt64", "getBigUint64"],
13658                 RelativeTimeFormat: ["format", "formatToParts", "resolvedOptions"]
13659             },
13660             esnext: {
13661                 PromiseConstructor: ["any"],
13662                 String: ["replaceAll"],
13663                 NumberFormat: ["formatToParts"]
13664             }
13665         };
13666     }
13667     ts.getScriptTargetFeatures = getScriptTargetFeatures;
13668     var GetLiteralTextFlags;
13669     (function (GetLiteralTextFlags) {
13670         GetLiteralTextFlags[GetLiteralTextFlags["None"] = 0] = "None";
13671         GetLiteralTextFlags[GetLiteralTextFlags["NeverAsciiEscape"] = 1] = "NeverAsciiEscape";
13672         GetLiteralTextFlags[GetLiteralTextFlags["JsxAttributeEscape"] = 2] = "JsxAttributeEscape";
13673         GetLiteralTextFlags[GetLiteralTextFlags["TerminateUnterminatedLiterals"] = 4] = "TerminateUnterminatedLiterals";
13674     })(GetLiteralTextFlags = ts.GetLiteralTextFlags || (ts.GetLiteralTextFlags = {}));
13675     function getLiteralText(node, sourceFile, flags) {
13676         // If we don't need to downlevel and we can reach the original source text using
13677         // the node's parent reference, then simply get the text as it was originally written.
13678         if (!nodeIsSynthesized(node) && node.parent && !(flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) && !((ts.isNumericLiteral(node) && node.numericLiteralFlags & 512 /* ContainsSeparator */) ||
13679             ts.isBigIntLiteral(node))) {
13680             return getSourceTextOfNodeFromSourceFile(sourceFile, node);
13681         }
13682         // If we can't reach the original source text, use the canonical form if it's a number,
13683         // or a (possibly escaped) quoted form of the original text if it's string-like.
13684         switch (node.kind) {
13685             case 10 /* StringLiteral */: {
13686                 var escapeText = flags & 2 /* JsxAttributeEscape */ ? escapeJsxAttributeString :
13687                     flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13688                         escapeNonAsciiString;
13689                 if (node.singleQuote) {
13690                     return "'" + escapeText(node.text, 39 /* singleQuote */) + "'";
13691                 }
13692                 else {
13693                     return '"' + escapeText(node.text, 34 /* doubleQuote */) + '"';
13694                 }
13695             }
13696             case 14 /* NoSubstitutionTemplateLiteral */:
13697             case 15 /* TemplateHead */:
13698             case 16 /* TemplateMiddle */:
13699             case 17 /* TemplateTail */: {
13700                 // If a NoSubstitutionTemplateLiteral appears to have a substitution in it, the original text
13701                 // had to include a backslash: `not \${a} substitution`.
13702                 var escapeText = flags & 1 /* NeverAsciiEscape */ || (getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? escapeString :
13703                     escapeNonAsciiString;
13704                 var rawText = node.rawText || escapeTemplateSubstitution(escapeText(node.text, 96 /* backtick */));
13705                 switch (node.kind) {
13706                     case 14 /* NoSubstitutionTemplateLiteral */:
13707                         return "`" + rawText + "`";
13708                     case 15 /* TemplateHead */:
13709                         return "`" + rawText + "${";
13710                     case 16 /* TemplateMiddle */:
13711                         return "}" + rawText + "${";
13712                     case 17 /* TemplateTail */:
13713                         return "}" + rawText + "`";
13714                 }
13715                 break;
13716             }
13717             case 8 /* NumericLiteral */:
13718             case 9 /* BigIntLiteral */:
13719                 return node.text;
13720             case 13 /* RegularExpressionLiteral */:
13721                 if (flags & 4 /* TerminateUnterminatedLiterals */ && node.isUnterminated) {
13722                     return node.text + (node.text.charCodeAt(node.text.length - 1) === 92 /* backslash */ ? " /" : "/");
13723                 }
13724                 return node.text;
13725         }
13726         return ts.Debug.fail("Literal kind '" + node.kind + "' not accounted for.");
13727     }
13728     ts.getLiteralText = getLiteralText;
13729     function getTextOfConstantValue(value) {
13730         return ts.isString(value) ? '"' + escapeNonAsciiString(value) + '"' : "" + value;
13731     }
13732     ts.getTextOfConstantValue = getTextOfConstantValue;
13733     // Make an identifier from an external module name by extracting the string after the last "/" and replacing
13734     // all non-alphanumeric characters with underscores
13735     function makeIdentifierFromModuleName(moduleName) {
13736         return ts.getBaseFileName(moduleName).replace(/^(\d)/, "_$1").replace(/\W/g, "_");
13737     }
13738     ts.makeIdentifierFromModuleName = makeIdentifierFromModuleName;
13739     function isBlockOrCatchScoped(declaration) {
13740         return (ts.getCombinedNodeFlags(declaration) & 3 /* BlockScoped */) !== 0 ||
13741             isCatchClauseVariableDeclarationOrBindingElement(declaration);
13742     }
13743     ts.isBlockOrCatchScoped = isBlockOrCatchScoped;
13744     function isCatchClauseVariableDeclarationOrBindingElement(declaration) {
13745         var node = getRootDeclaration(declaration);
13746         return node.kind === 249 /* VariableDeclaration */ && node.parent.kind === 287 /* CatchClause */;
13747     }
13748     ts.isCatchClauseVariableDeclarationOrBindingElement = isCatchClauseVariableDeclarationOrBindingElement;
13749     function isAmbientModule(node) {
13750         return ts.isModuleDeclaration(node) && (node.name.kind === 10 /* StringLiteral */ || isGlobalScopeAugmentation(node));
13751     }
13752     ts.isAmbientModule = isAmbientModule;
13753     function isModuleWithStringLiteralName(node) {
13754         return ts.isModuleDeclaration(node) && node.name.kind === 10 /* StringLiteral */;
13755     }
13756     ts.isModuleWithStringLiteralName = isModuleWithStringLiteralName;
13757     function isNonGlobalAmbientModule(node) {
13758         return ts.isModuleDeclaration(node) && ts.isStringLiteral(node.name);
13759     }
13760     ts.isNonGlobalAmbientModule = isNonGlobalAmbientModule;
13761     /**
13762      * An effective module (namespace) declaration is either
13763      * 1. An actual declaration: namespace X { ... }
13764      * 2. A Javascript declaration, which is:
13765      *    An identifier in a nested property access expression: Y in `X.Y.Z = { ... }`
13766      */
13767     function isEffectiveModuleDeclaration(node) {
13768         return ts.isModuleDeclaration(node) || ts.isIdentifier(node);
13769     }
13770     ts.isEffectiveModuleDeclaration = isEffectiveModuleDeclaration;
13771     /** Given a symbol for a module, checks that it is a shorthand ambient module. */
13772     function isShorthandAmbientModuleSymbol(moduleSymbol) {
13773         return isShorthandAmbientModule(moduleSymbol.valueDeclaration);
13774     }
13775     ts.isShorthandAmbientModuleSymbol = isShorthandAmbientModuleSymbol;
13776     function isShorthandAmbientModule(node) {
13777         // The only kind of module that can be missing a body is a shorthand ambient module.
13778         return node && node.kind === 256 /* ModuleDeclaration */ && (!node.body);
13779     }
13780     function isBlockScopedContainerTopLevel(node) {
13781         return node.kind === 297 /* SourceFile */ ||
13782             node.kind === 256 /* ModuleDeclaration */ ||
13783             ts.isFunctionLike(node);
13784     }
13785     ts.isBlockScopedContainerTopLevel = isBlockScopedContainerTopLevel;
13786     function isGlobalScopeAugmentation(module) {
13787         return !!(module.flags & 1024 /* GlobalAugmentation */);
13788     }
13789     ts.isGlobalScopeAugmentation = isGlobalScopeAugmentation;
13790     function isExternalModuleAugmentation(node) {
13791         return isAmbientModule(node) && isModuleAugmentationExternal(node);
13792     }
13793     ts.isExternalModuleAugmentation = isExternalModuleAugmentation;
13794     function isModuleAugmentationExternal(node) {
13795         // external module augmentation is a ambient module declaration that is either:
13796         // - defined in the top level scope and source file is an external module
13797         // - defined inside ambient module declaration located in the top level scope and source file not an external module
13798         switch (node.parent.kind) {
13799             case 297 /* SourceFile */:
13800                 return ts.isExternalModule(node.parent);
13801             case 257 /* ModuleBlock */:
13802                 return isAmbientModule(node.parent.parent) && ts.isSourceFile(node.parent.parent.parent) && !ts.isExternalModule(node.parent.parent.parent);
13803         }
13804         return false;
13805     }
13806     ts.isModuleAugmentationExternal = isModuleAugmentationExternal;
13807     function getNonAugmentationDeclaration(symbol) {
13808         return ts.find(symbol.declarations, function (d) { return !isExternalModuleAugmentation(d) && !(ts.isModuleDeclaration(d) && isGlobalScopeAugmentation(d)); });
13809     }
13810     ts.getNonAugmentationDeclaration = getNonAugmentationDeclaration;
13811     function isEffectiveExternalModule(node, compilerOptions) {
13812         return ts.isExternalModule(node) || compilerOptions.isolatedModules || ((getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS) && !!node.commonJsModuleIndicator);
13813     }
13814     ts.isEffectiveExternalModule = isEffectiveExternalModule;
13815     /**
13816      * Returns whether the source file will be treated as if it were in strict mode at runtime.
13817      */
13818     function isEffectiveStrictModeSourceFile(node, compilerOptions) {
13819         // We can only verify strict mode for JS/TS files
13820         switch (node.scriptKind) {
13821             case 1 /* JS */:
13822             case 3 /* TS */:
13823             case 2 /* JSX */:
13824             case 4 /* TSX */:
13825                 break;
13826             default:
13827                 return false;
13828         }
13829         // Strict mode does not matter for declaration files.
13830         if (node.isDeclarationFile) {
13831             return false;
13832         }
13833         // If `alwaysStrict` is set, then treat the file as strict.
13834         if (getStrictOptionValue(compilerOptions, "alwaysStrict")) {
13835             return true;
13836         }
13837         // Starting with a "use strict" directive indicates the file is strict.
13838         if (ts.startsWithUseStrict(node.statements)) {
13839             return true;
13840         }
13841         if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
13842             // ECMAScript Modules are always strict.
13843             if (getEmitModuleKind(compilerOptions) >= ts.ModuleKind.ES2015) {
13844                 return true;
13845             }
13846             // Other modules are strict unless otherwise specified.
13847             return !compilerOptions.noImplicitUseStrict;
13848         }
13849         return false;
13850     }
13851     ts.isEffectiveStrictModeSourceFile = isEffectiveStrictModeSourceFile;
13852     function isBlockScope(node, parentNode) {
13853         switch (node.kind) {
13854             case 297 /* SourceFile */:
13855             case 258 /* CaseBlock */:
13856             case 287 /* CatchClause */:
13857             case 256 /* ModuleDeclaration */:
13858             case 237 /* ForStatement */:
13859             case 238 /* ForInStatement */:
13860             case 239 /* ForOfStatement */:
13861             case 166 /* Constructor */:
13862             case 165 /* MethodDeclaration */:
13863             case 167 /* GetAccessor */:
13864             case 168 /* SetAccessor */:
13865             case 251 /* FunctionDeclaration */:
13866             case 208 /* FunctionExpression */:
13867             case 209 /* ArrowFunction */:
13868                 return true;
13869             case 230 /* Block */:
13870                 // function block is not considered block-scope container
13871                 // see comment in binder.ts: bind(...), case for SyntaxKind.Block
13872                 return !ts.isFunctionLike(parentNode);
13873         }
13874         return false;
13875     }
13876     ts.isBlockScope = isBlockScope;
13877     function isDeclarationWithTypeParameters(node) {
13878         switch (node.kind) {
13879             case 324 /* JSDocCallbackTag */:
13880             case 331 /* JSDocTypedefTag */:
13881             case 313 /* JSDocSignature */:
13882                 return true;
13883             default:
13884                 ts.assertType(node);
13885                 return isDeclarationWithTypeParameterChildren(node);
13886         }
13887     }
13888     ts.isDeclarationWithTypeParameters = isDeclarationWithTypeParameters;
13889     function isDeclarationWithTypeParameterChildren(node) {
13890         switch (node.kind) {
13891             case 169 /* CallSignature */:
13892             case 170 /* ConstructSignature */:
13893             case 164 /* MethodSignature */:
13894             case 171 /* IndexSignature */:
13895             case 174 /* FunctionType */:
13896             case 175 /* ConstructorType */:
13897             case 308 /* JSDocFunctionType */:
13898             case 252 /* ClassDeclaration */:
13899             case 221 /* ClassExpression */:
13900             case 253 /* InterfaceDeclaration */:
13901             case 254 /* TypeAliasDeclaration */:
13902             case 330 /* JSDocTemplateTag */:
13903             case 251 /* FunctionDeclaration */:
13904             case 165 /* MethodDeclaration */:
13905             case 166 /* Constructor */:
13906             case 167 /* GetAccessor */:
13907             case 168 /* SetAccessor */:
13908             case 208 /* FunctionExpression */:
13909             case 209 /* ArrowFunction */:
13910                 return true;
13911             default:
13912                 ts.assertType(node);
13913                 return false;
13914         }
13915     }
13916     ts.isDeclarationWithTypeParameterChildren = isDeclarationWithTypeParameterChildren;
13917     function isAnyImportSyntax(node) {
13918         switch (node.kind) {
13919             case 261 /* ImportDeclaration */:
13920             case 260 /* ImportEqualsDeclaration */:
13921                 return true;
13922             default:
13923                 return false;
13924         }
13925     }
13926     ts.isAnyImportSyntax = isAnyImportSyntax;
13927     function isLateVisibilityPaintedStatement(node) {
13928         switch (node.kind) {
13929             case 261 /* ImportDeclaration */:
13930             case 260 /* ImportEqualsDeclaration */:
13931             case 232 /* VariableStatement */:
13932             case 252 /* ClassDeclaration */:
13933             case 251 /* FunctionDeclaration */:
13934             case 256 /* ModuleDeclaration */:
13935             case 254 /* TypeAliasDeclaration */:
13936             case 253 /* InterfaceDeclaration */:
13937             case 255 /* EnumDeclaration */:
13938                 return true;
13939             default:
13940                 return false;
13941         }
13942     }
13943     ts.isLateVisibilityPaintedStatement = isLateVisibilityPaintedStatement;
13944     function isAnyImportOrReExport(node) {
13945         return isAnyImportSyntax(node) || ts.isExportDeclaration(node);
13946     }
13947     ts.isAnyImportOrReExport = isAnyImportOrReExport;
13948     // Gets the nearest enclosing block scope container that has the provided node
13949     // as a descendant, that is not the provided node.
13950     function getEnclosingBlockScopeContainer(node) {
13951         return ts.findAncestor(node.parent, function (current) { return isBlockScope(current, current.parent); });
13952     }
13953     ts.getEnclosingBlockScopeContainer = getEnclosingBlockScopeContainer;
13954     // Return display name of an identifier
13955     // Computed property names will just be emitted as "[<expr>]", where <expr> is the source
13956     // text of the expression in the computed property.
13957     function declarationNameToString(name) {
13958         return !name || getFullWidth(name) === 0 ? "(Missing)" : getTextOfNode(name);
13959     }
13960     ts.declarationNameToString = declarationNameToString;
13961     function getNameFromIndexInfo(info) {
13962         return info.declaration ? declarationNameToString(info.declaration.parameters[0].name) : undefined;
13963     }
13964     ts.getNameFromIndexInfo = getNameFromIndexInfo;
13965     function isComputedNonLiteralName(name) {
13966         return name.kind === 158 /* ComputedPropertyName */ && !isStringOrNumericLiteralLike(name.expression);
13967     }
13968     ts.isComputedNonLiteralName = isComputedNonLiteralName;
13969     function getTextOfPropertyName(name) {
13970         switch (name.kind) {
13971             case 78 /* Identifier */:
13972             case 79 /* PrivateIdentifier */:
13973                 return name.escapedText;
13974             case 10 /* StringLiteral */:
13975             case 8 /* NumericLiteral */:
13976             case 14 /* NoSubstitutionTemplateLiteral */:
13977                 return ts.escapeLeadingUnderscores(name.text);
13978             case 158 /* ComputedPropertyName */:
13979                 if (isStringOrNumericLiteralLike(name.expression))
13980                     return ts.escapeLeadingUnderscores(name.expression.text);
13981                 return ts.Debug.fail("Text of property name cannot be read from non-literal-valued ComputedPropertyNames");
13982             default:
13983                 return ts.Debug.assertNever(name);
13984         }
13985     }
13986     ts.getTextOfPropertyName = getTextOfPropertyName;
13987     function entityNameToString(name) {
13988         switch (name.kind) {
13989             case 107 /* ThisKeyword */:
13990                 return "this";
13991             case 79 /* PrivateIdentifier */:
13992             case 78 /* Identifier */:
13993                 return getFullWidth(name) === 0 ? ts.idText(name) : getTextOfNode(name);
13994             case 157 /* QualifiedName */:
13995                 return entityNameToString(name.left) + "." + entityNameToString(name.right);
13996             case 201 /* PropertyAccessExpression */:
13997                 if (ts.isIdentifier(name.name) || ts.isPrivateIdentifier(name.name)) {
13998                     return entityNameToString(name.expression) + "." + entityNameToString(name.name);
13999                 }
14000                 else {
14001                     return ts.Debug.assertNever(name.name);
14002                 }
14003             default:
14004                 return ts.Debug.assertNever(name);
14005         }
14006     }
14007     ts.entityNameToString = entityNameToString;
14008     function createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3) {
14009         var sourceFile = getSourceFileOfNode(node);
14010         return createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3);
14011     }
14012     ts.createDiagnosticForNode = createDiagnosticForNode;
14013     function createDiagnosticForNodeArray(sourceFile, nodes, message, arg0, arg1, arg2, arg3) {
14014         var start = ts.skipTrivia(sourceFile.text, nodes.pos);
14015         return createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2, arg3);
14016     }
14017     ts.createDiagnosticForNodeArray = createDiagnosticForNodeArray;
14018     function createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2, arg3) {
14019         var span = getErrorSpanForNode(sourceFile, node);
14020         return createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2, arg3);
14021     }
14022     ts.createDiagnosticForNodeInSourceFile = createDiagnosticForNodeInSourceFile;
14023     function createDiagnosticForNodeFromMessageChain(node, messageChain, relatedInformation) {
14024         var sourceFile = getSourceFileOfNode(node);
14025         var span = getErrorSpanForNode(sourceFile, node);
14026         return {
14027             file: sourceFile,
14028             start: span.start,
14029             length: span.length,
14030             code: messageChain.code,
14031             category: messageChain.category,
14032             messageText: messageChain.next ? messageChain : messageChain.messageText,
14033             relatedInformation: relatedInformation
14034         };
14035     }
14036     ts.createDiagnosticForNodeFromMessageChain = createDiagnosticForNodeFromMessageChain;
14037     function createDiagnosticForFileFromMessageChain(sourceFile, messageChain, relatedInformation) {
14038         return {
14039             file: sourceFile,
14040             start: 0,
14041             length: 0,
14042             code: messageChain.code,
14043             category: messageChain.category,
14044             messageText: messageChain.next ? messageChain : messageChain.messageText,
14045             relatedInformation: relatedInformation
14046         };
14047     }
14048     ts.createDiagnosticForFileFromMessageChain = createDiagnosticForFileFromMessageChain;
14049     function createDiagnosticForRange(sourceFile, range, message) {
14050         return {
14051             file: sourceFile,
14052             start: range.pos,
14053             length: range.end - range.pos,
14054             code: message.code,
14055             category: message.category,
14056             messageText: message.message,
14057         };
14058     }
14059     ts.createDiagnosticForRange = createDiagnosticForRange;
14060     function getSpanOfTokenAtPosition(sourceFile, pos) {
14061         var scanner = ts.createScanner(sourceFile.languageVersion, /*skipTrivia*/ true, sourceFile.languageVariant, sourceFile.text, /*onError:*/ undefined, pos);
14062         scanner.scan();
14063         var start = scanner.getTokenPos();
14064         return ts.createTextSpanFromBounds(start, scanner.getTextPos());
14065     }
14066     ts.getSpanOfTokenAtPosition = getSpanOfTokenAtPosition;
14067     function getErrorSpanForArrowFunction(sourceFile, node) {
14068         var pos = ts.skipTrivia(sourceFile.text, node.pos);
14069         if (node.body && node.body.kind === 230 /* Block */) {
14070             var startLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.pos).line;
14071             var endLine = ts.getLineAndCharacterOfPosition(sourceFile, node.body.end).line;
14072             if (startLine < endLine) {
14073                 // The arrow function spans multiple lines,
14074                 // make the error span be the first line, inclusive.
14075                 return ts.createTextSpan(pos, getEndLinePosition(startLine, sourceFile) - pos + 1);
14076             }
14077         }
14078         return ts.createTextSpanFromBounds(pos, node.end);
14079     }
14080     function getErrorSpanForNode(sourceFile, node) {
14081         var errorNode = node;
14082         switch (node.kind) {
14083             case 297 /* SourceFile */:
14084                 var pos_1 = ts.skipTrivia(sourceFile.text, 0, /*stopAfterLineBreak*/ false);
14085                 if (pos_1 === sourceFile.text.length) {
14086                     // file is empty - return span for the beginning of the file
14087                     return ts.createTextSpan(0, 0);
14088                 }
14089                 return getSpanOfTokenAtPosition(sourceFile, pos_1);
14090             // This list is a work in progress. Add missing node kinds to improve their error
14091             // spans.
14092             case 249 /* VariableDeclaration */:
14093             case 198 /* BindingElement */:
14094             case 252 /* ClassDeclaration */:
14095             case 221 /* ClassExpression */:
14096             case 253 /* InterfaceDeclaration */:
14097             case 256 /* ModuleDeclaration */:
14098             case 255 /* EnumDeclaration */:
14099             case 291 /* EnumMember */:
14100             case 251 /* FunctionDeclaration */:
14101             case 208 /* FunctionExpression */:
14102             case 165 /* MethodDeclaration */:
14103             case 167 /* GetAccessor */:
14104             case 168 /* SetAccessor */:
14105             case 254 /* TypeAliasDeclaration */:
14106             case 163 /* PropertyDeclaration */:
14107             case 162 /* PropertySignature */:
14108                 errorNode = node.name;
14109                 break;
14110             case 209 /* ArrowFunction */:
14111                 return getErrorSpanForArrowFunction(sourceFile, node);
14112             case 284 /* CaseClause */:
14113             case 285 /* DefaultClause */:
14114                 var start = ts.skipTrivia(sourceFile.text, node.pos);
14115                 var end = node.statements.length > 0 ? node.statements[0].pos : node.end;
14116                 return ts.createTextSpanFromBounds(start, end);
14117         }
14118         if (errorNode === undefined) {
14119             // If we don't have a better node, then just set the error on the first token of
14120             // construct.
14121             return getSpanOfTokenAtPosition(sourceFile, node.pos);
14122         }
14123         ts.Debug.assert(!ts.isJSDoc(errorNode));
14124         var isMissing = nodeIsMissing(errorNode);
14125         var pos = isMissing || ts.isJsxText(node)
14126             ? errorNode.pos
14127             : ts.skipTrivia(sourceFile.text, errorNode.pos);
14128         // These asserts should all be satisfied for a properly constructed `errorNode`.
14129         if (isMissing) {
14130             ts.Debug.assert(pos === errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14131             ts.Debug.assert(pos === errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14132         }
14133         else {
14134             ts.Debug.assert(pos >= errorNode.pos, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14135             ts.Debug.assert(pos <= errorNode.end, "This failure could trigger https://github.com/Microsoft/TypeScript/issues/20809");
14136         }
14137         return ts.createTextSpanFromBounds(pos, errorNode.end);
14138     }
14139     ts.getErrorSpanForNode = getErrorSpanForNode;
14140     function isExternalOrCommonJsModule(file) {
14141         return (file.externalModuleIndicator || file.commonJsModuleIndicator) !== undefined;
14142     }
14143     ts.isExternalOrCommonJsModule = isExternalOrCommonJsModule;
14144     function isJsonSourceFile(file) {
14145         return file.scriptKind === 6 /* JSON */;
14146     }
14147     ts.isJsonSourceFile = isJsonSourceFile;
14148     function isEnumConst(node) {
14149         return !!(ts.getCombinedModifierFlags(node) & 2048 /* Const */);
14150     }
14151     ts.isEnumConst = isEnumConst;
14152     function isDeclarationReadonly(declaration) {
14153         return !!(ts.getCombinedModifierFlags(declaration) & 64 /* Readonly */ && !ts.isParameterPropertyDeclaration(declaration, declaration.parent));
14154     }
14155     ts.isDeclarationReadonly = isDeclarationReadonly;
14156     function isVarConst(node) {
14157         return !!(ts.getCombinedNodeFlags(node) & 2 /* Const */);
14158     }
14159     ts.isVarConst = isVarConst;
14160     function isLet(node) {
14161         return !!(ts.getCombinedNodeFlags(node) & 1 /* Let */);
14162     }
14163     ts.isLet = isLet;
14164     function isSuperCall(n) {
14165         return n.kind === 203 /* CallExpression */ && n.expression.kind === 105 /* SuperKeyword */;
14166     }
14167     ts.isSuperCall = isSuperCall;
14168     function isImportCall(n) {
14169         return n.kind === 203 /* CallExpression */ && n.expression.kind === 99 /* ImportKeyword */;
14170     }
14171     ts.isImportCall = isImportCall;
14172     function isImportMeta(n) {
14173         return ts.isMetaProperty(n)
14174             && n.keywordToken === 99 /* ImportKeyword */
14175             && n.name.escapedText === "meta";
14176     }
14177     ts.isImportMeta = isImportMeta;
14178     function isLiteralImportTypeNode(n) {
14179         return ts.isImportTypeNode(n) && ts.isLiteralTypeNode(n.argument) && ts.isStringLiteral(n.argument.literal);
14180     }
14181     ts.isLiteralImportTypeNode = isLiteralImportTypeNode;
14182     function isPrologueDirective(node) {
14183         return node.kind === 233 /* ExpressionStatement */
14184             && node.expression.kind === 10 /* StringLiteral */;
14185     }
14186     ts.isPrologueDirective = isPrologueDirective;
14187     function isCustomPrologue(node) {
14188         return !!(getEmitFlags(node) & 1048576 /* CustomPrologue */);
14189     }
14190     ts.isCustomPrologue = isCustomPrologue;
14191     function isHoistedFunction(node) {
14192         return isCustomPrologue(node)
14193             && ts.isFunctionDeclaration(node);
14194     }
14195     ts.isHoistedFunction = isHoistedFunction;
14196     function isHoistedVariable(node) {
14197         return ts.isIdentifier(node.name)
14198             && !node.initializer;
14199     }
14200     function isHoistedVariableStatement(node) {
14201         return isCustomPrologue(node)
14202             && ts.isVariableStatement(node)
14203             && ts.every(node.declarationList.declarations, isHoistedVariable);
14204     }
14205     ts.isHoistedVariableStatement = isHoistedVariableStatement;
14206     function getLeadingCommentRangesOfNode(node, sourceFileOfNode) {
14207         return node.kind !== 11 /* JsxText */ ? ts.getLeadingCommentRanges(sourceFileOfNode.text, node.pos) : undefined;
14208     }
14209     ts.getLeadingCommentRangesOfNode = getLeadingCommentRangesOfNode;
14210     function getJSDocCommentRanges(node, text) {
14211         var commentRanges = (node.kind === 160 /* Parameter */ ||
14212             node.kind === 159 /* TypeParameter */ ||
14213             node.kind === 208 /* FunctionExpression */ ||
14214             node.kind === 209 /* ArrowFunction */ ||
14215             node.kind === 207 /* ParenthesizedExpression */) ?
14216             ts.concatenate(ts.getTrailingCommentRanges(text, node.pos), ts.getLeadingCommentRanges(text, node.pos)) :
14217             ts.getLeadingCommentRanges(text, node.pos);
14218         // True if the comment starts with '/**' but not if it is '/**/'
14219         return ts.filter(commentRanges, function (comment) {
14220             return text.charCodeAt(comment.pos + 1) === 42 /* asterisk */ &&
14221                 text.charCodeAt(comment.pos + 2) === 42 /* asterisk */ &&
14222                 text.charCodeAt(comment.pos + 3) !== 47 /* slash */;
14223         });
14224     }
14225     ts.getJSDocCommentRanges = getJSDocCommentRanges;
14226     ts.fullTripleSlashReferencePathRegEx = /^(\/\/\/\s*<reference\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
14227     var fullTripleSlashReferenceTypeReferenceDirectiveRegEx = /^(\/\/\/\s*<reference\s+types\s*=\s*)('|")(.+?)\2.*?\/>/;
14228     ts.fullTripleSlashAMDReferencePathRegEx = /^(\/\/\/\s*<amd-dependency\s+path\s*=\s*)('|")(.+?)\2.*?\/>/;
14229     var defaultLibReferenceRegEx = /^(\/\/\/\s*<reference\s+no-default-lib\s*=\s*)('|")(.+?)\2\s*\/>/;
14230     function isPartOfTypeNode(node) {
14231         if (172 /* FirstTypeNode */ <= node.kind && node.kind <= 195 /* LastTypeNode */) {
14232             return true;
14233         }
14234         switch (node.kind) {
14235             case 128 /* AnyKeyword */:
14236             case 152 /* UnknownKeyword */:
14237             case 144 /* NumberKeyword */:
14238             case 155 /* BigIntKeyword */:
14239             case 147 /* StringKeyword */:
14240             case 131 /* BooleanKeyword */:
14241             case 148 /* SymbolKeyword */:
14242             case 145 /* ObjectKeyword */:
14243             case 150 /* UndefinedKeyword */:
14244             case 141 /* NeverKeyword */:
14245                 return true;
14246             case 113 /* VoidKeyword */:
14247                 return node.parent.kind !== 212 /* VoidExpression */;
14248             case 223 /* ExpressionWithTypeArguments */:
14249                 return !isExpressionWithTypeArgumentsInClassExtendsClause(node);
14250             case 159 /* TypeParameter */:
14251                 return node.parent.kind === 190 /* MappedType */ || node.parent.kind === 185 /* InferType */;
14252             // Identifiers and qualified names may be type nodes, depending on their context. Climb
14253             // above them to find the lowest container
14254             case 78 /* Identifier */:
14255                 // If the identifier is the RHS of a qualified name, then it's a type iff its parent is.
14256                 if (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) {
14257                     node = node.parent;
14258                 }
14259                 else if (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node) {
14260                     node = node.parent;
14261                 }
14262                 // At this point, node is either a qualified name or an identifier
14263                 ts.Debug.assert(node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */ || node.kind === 201 /* PropertyAccessExpression */, "'node' was expected to be a qualified name, identifier or property access in 'isPartOfTypeNode'.");
14264             // falls through
14265             case 157 /* QualifiedName */:
14266             case 201 /* PropertyAccessExpression */:
14267             case 107 /* ThisKeyword */: {
14268                 var parent = node.parent;
14269                 if (parent.kind === 176 /* TypeQuery */) {
14270                     return false;
14271                 }
14272                 if (parent.kind === 195 /* ImportType */) {
14273                     return !parent.isTypeOf;
14274                 }
14275                 // Do not recursively call isPartOfTypeNode on the parent. In the example:
14276                 //
14277                 //     let a: A.B.C;
14278                 //
14279                 // Calling isPartOfTypeNode would consider the qualified name A.B a type node.
14280                 // Only C and A.B.C are type nodes.
14281                 if (172 /* FirstTypeNode */ <= parent.kind && parent.kind <= 195 /* LastTypeNode */) {
14282                     return true;
14283                 }
14284                 switch (parent.kind) {
14285                     case 223 /* ExpressionWithTypeArguments */:
14286                         return !isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14287                     case 159 /* TypeParameter */:
14288                         return node === parent.constraint;
14289                     case 330 /* JSDocTemplateTag */:
14290                         return node === parent.constraint;
14291                     case 163 /* PropertyDeclaration */:
14292                     case 162 /* PropertySignature */:
14293                     case 160 /* Parameter */:
14294                     case 249 /* VariableDeclaration */:
14295                         return node === parent.type;
14296                     case 251 /* FunctionDeclaration */:
14297                     case 208 /* FunctionExpression */:
14298                     case 209 /* ArrowFunction */:
14299                     case 166 /* Constructor */:
14300                     case 165 /* MethodDeclaration */:
14301                     case 164 /* MethodSignature */:
14302                     case 167 /* GetAccessor */:
14303                     case 168 /* SetAccessor */:
14304                         return node === parent.type;
14305                     case 169 /* CallSignature */:
14306                     case 170 /* ConstructSignature */:
14307                     case 171 /* IndexSignature */:
14308                         return node === parent.type;
14309                     case 206 /* TypeAssertionExpression */:
14310                         return node === parent.type;
14311                     case 203 /* CallExpression */:
14312                     case 204 /* NewExpression */:
14313                         return ts.contains(parent.typeArguments, node);
14314                     case 205 /* TaggedTemplateExpression */:
14315                         // TODO (drosen): TaggedTemplateExpressions may eventually support type arguments.
14316                         return false;
14317                 }
14318             }
14319         }
14320         return false;
14321     }
14322     ts.isPartOfTypeNode = isPartOfTypeNode;
14323     function isChildOfNodeWithKind(node, kind) {
14324         while (node) {
14325             if (node.kind === kind) {
14326                 return true;
14327             }
14328             node = node.parent;
14329         }
14330         return false;
14331     }
14332     ts.isChildOfNodeWithKind = isChildOfNodeWithKind;
14333     // Warning: This has the same semantics as the forEach family of functions,
14334     //          in that traversal terminates in the event that 'visitor' supplies a truthy value.
14335     function forEachReturnStatement(body, visitor) {
14336         return traverse(body);
14337         function traverse(node) {
14338             switch (node.kind) {
14339                 case 242 /* ReturnStatement */:
14340                     return visitor(node);
14341                 case 258 /* CaseBlock */:
14342                 case 230 /* Block */:
14343                 case 234 /* IfStatement */:
14344                 case 235 /* DoStatement */:
14345                 case 236 /* WhileStatement */:
14346                 case 237 /* ForStatement */:
14347                 case 238 /* ForInStatement */:
14348                 case 239 /* ForOfStatement */:
14349                 case 243 /* WithStatement */:
14350                 case 244 /* SwitchStatement */:
14351                 case 284 /* CaseClause */:
14352                 case 285 /* DefaultClause */:
14353                 case 245 /* LabeledStatement */:
14354                 case 247 /* TryStatement */:
14355                 case 287 /* CatchClause */:
14356                     return ts.forEachChild(node, traverse);
14357             }
14358         }
14359     }
14360     ts.forEachReturnStatement = forEachReturnStatement;
14361     function forEachYieldExpression(body, visitor) {
14362         return traverse(body);
14363         function traverse(node) {
14364             switch (node.kind) {
14365                 case 219 /* YieldExpression */:
14366                     visitor(node);
14367                     var operand = node.expression;
14368                     if (operand) {
14369                         traverse(operand);
14370                     }
14371                     return;
14372                 case 255 /* EnumDeclaration */:
14373                 case 253 /* InterfaceDeclaration */:
14374                 case 256 /* ModuleDeclaration */:
14375                 case 254 /* TypeAliasDeclaration */:
14376                     // These are not allowed inside a generator now, but eventually they may be allowed
14377                     // as local types. Regardless, skip them to avoid the work.
14378                     return;
14379                 default:
14380                     if (ts.isFunctionLike(node)) {
14381                         if (node.name && node.name.kind === 158 /* ComputedPropertyName */) {
14382                             // Note that we will not include methods/accessors of a class because they would require
14383                             // first descending into the class. This is by design.
14384                             traverse(node.name.expression);
14385                             return;
14386                         }
14387                     }
14388                     else if (!isPartOfTypeNode(node)) {
14389                         // This is the general case, which should include mostly expressions and statements.
14390                         // Also includes NodeArrays.
14391                         ts.forEachChild(node, traverse);
14392                     }
14393             }
14394         }
14395     }
14396     ts.forEachYieldExpression = forEachYieldExpression;
14397     /**
14398      * Gets the most likely element type for a TypeNode. This is not an exhaustive test
14399      * as it assumes a rest argument can only be an array type (either T[], or Array<T>).
14400      *
14401      * @param node The type node.
14402      */
14403     function getRestParameterElementType(node) {
14404         if (node && node.kind === 178 /* ArrayType */) {
14405             return node.elementType;
14406         }
14407         else if (node && node.kind === 173 /* TypeReference */) {
14408             return ts.singleOrUndefined(node.typeArguments);
14409         }
14410         else {
14411             return undefined;
14412         }
14413     }
14414     ts.getRestParameterElementType = getRestParameterElementType;
14415     function getMembersOfDeclaration(node) {
14416         switch (node.kind) {
14417             case 253 /* InterfaceDeclaration */:
14418             case 252 /* ClassDeclaration */:
14419             case 221 /* ClassExpression */:
14420             case 177 /* TypeLiteral */:
14421                 return node.members;
14422             case 200 /* ObjectLiteralExpression */:
14423                 return node.properties;
14424         }
14425     }
14426     ts.getMembersOfDeclaration = getMembersOfDeclaration;
14427     function isVariableLike(node) {
14428         if (node) {
14429             switch (node.kind) {
14430                 case 198 /* BindingElement */:
14431                 case 291 /* EnumMember */:
14432                 case 160 /* Parameter */:
14433                 case 288 /* PropertyAssignment */:
14434                 case 163 /* PropertyDeclaration */:
14435                 case 162 /* PropertySignature */:
14436                 case 289 /* ShorthandPropertyAssignment */:
14437                 case 249 /* VariableDeclaration */:
14438                     return true;
14439             }
14440         }
14441         return false;
14442     }
14443     ts.isVariableLike = isVariableLike;
14444     function isVariableLikeOrAccessor(node) {
14445         return isVariableLike(node) || ts.isAccessor(node);
14446     }
14447     ts.isVariableLikeOrAccessor = isVariableLikeOrAccessor;
14448     function isVariableDeclarationInVariableStatement(node) {
14449         return node.parent.kind === 250 /* VariableDeclarationList */
14450             && node.parent.parent.kind === 232 /* VariableStatement */;
14451     }
14452     ts.isVariableDeclarationInVariableStatement = isVariableDeclarationInVariableStatement;
14453     function isValidESSymbolDeclaration(node) {
14454         return ts.isVariableDeclaration(node) ? isVarConst(node) && ts.isIdentifier(node.name) && isVariableDeclarationInVariableStatement(node) :
14455             ts.isPropertyDeclaration(node) ? hasEffectiveReadonlyModifier(node) && hasStaticModifier(node) :
14456                 ts.isPropertySignature(node) && hasEffectiveReadonlyModifier(node);
14457     }
14458     ts.isValidESSymbolDeclaration = isValidESSymbolDeclaration;
14459     function introducesArgumentsExoticObject(node) {
14460         switch (node.kind) {
14461             case 165 /* MethodDeclaration */:
14462             case 164 /* MethodSignature */:
14463             case 166 /* Constructor */:
14464             case 167 /* GetAccessor */:
14465             case 168 /* SetAccessor */:
14466             case 251 /* FunctionDeclaration */:
14467             case 208 /* FunctionExpression */:
14468                 return true;
14469         }
14470         return false;
14471     }
14472     ts.introducesArgumentsExoticObject = introducesArgumentsExoticObject;
14473     function unwrapInnermostStatementOfLabel(node, beforeUnwrapLabelCallback) {
14474         while (true) {
14475             if (beforeUnwrapLabelCallback) {
14476                 beforeUnwrapLabelCallback(node);
14477             }
14478             if (node.statement.kind !== 245 /* LabeledStatement */) {
14479                 return node.statement;
14480             }
14481             node = node.statement;
14482         }
14483     }
14484     ts.unwrapInnermostStatementOfLabel = unwrapInnermostStatementOfLabel;
14485     function isFunctionBlock(node) {
14486         return node && node.kind === 230 /* Block */ && ts.isFunctionLike(node.parent);
14487     }
14488     ts.isFunctionBlock = isFunctionBlock;
14489     function isObjectLiteralMethod(node) {
14490         return node && node.kind === 165 /* MethodDeclaration */ && node.parent.kind === 200 /* ObjectLiteralExpression */;
14491     }
14492     ts.isObjectLiteralMethod = isObjectLiteralMethod;
14493     function isObjectLiteralOrClassExpressionMethod(node) {
14494         return node.kind === 165 /* MethodDeclaration */ &&
14495             (node.parent.kind === 200 /* ObjectLiteralExpression */ ||
14496                 node.parent.kind === 221 /* ClassExpression */);
14497     }
14498     ts.isObjectLiteralOrClassExpressionMethod = isObjectLiteralOrClassExpressionMethod;
14499     function isIdentifierTypePredicate(predicate) {
14500         return predicate && predicate.kind === 1 /* Identifier */;
14501     }
14502     ts.isIdentifierTypePredicate = isIdentifierTypePredicate;
14503     function isThisTypePredicate(predicate) {
14504         return predicate && predicate.kind === 0 /* This */;
14505     }
14506     ts.isThisTypePredicate = isThisTypePredicate;
14507     function getPropertyAssignment(objectLiteral, key, key2) {
14508         return objectLiteral.properties.filter(function (property) {
14509             if (property.kind === 288 /* PropertyAssignment */) {
14510                 var propName = getTextOfPropertyName(property.name);
14511                 return key === propName || (!!key2 && key2 === propName);
14512             }
14513             return false;
14514         });
14515     }
14516     ts.getPropertyAssignment = getPropertyAssignment;
14517     function getTsConfigObjectLiteralExpression(tsConfigSourceFile) {
14518         if (tsConfigSourceFile && tsConfigSourceFile.statements.length) {
14519             var expression = tsConfigSourceFile.statements[0].expression;
14520             return ts.tryCast(expression, ts.isObjectLiteralExpression);
14521         }
14522     }
14523     ts.getTsConfigObjectLiteralExpression = getTsConfigObjectLiteralExpression;
14524     function getTsConfigPropArrayElementValue(tsConfigSourceFile, propKey, elementValue) {
14525         return ts.firstDefined(getTsConfigPropArray(tsConfigSourceFile, propKey), function (property) {
14526             return ts.isArrayLiteralExpression(property.initializer) ?
14527                 ts.find(property.initializer.elements, function (element) { return ts.isStringLiteral(element) && element.text === elementValue; }) :
14528                 undefined;
14529         });
14530     }
14531     ts.getTsConfigPropArrayElementValue = getTsConfigPropArrayElementValue;
14532     function getTsConfigPropArray(tsConfigSourceFile, propKey) {
14533         var jsonObjectLiteral = getTsConfigObjectLiteralExpression(tsConfigSourceFile);
14534         return jsonObjectLiteral ? getPropertyAssignment(jsonObjectLiteral, propKey) : ts.emptyArray;
14535     }
14536     ts.getTsConfigPropArray = getTsConfigPropArray;
14537     function getContainingFunction(node) {
14538         return ts.findAncestor(node.parent, ts.isFunctionLike);
14539     }
14540     ts.getContainingFunction = getContainingFunction;
14541     function getContainingFunctionDeclaration(node) {
14542         return ts.findAncestor(node.parent, ts.isFunctionLikeDeclaration);
14543     }
14544     ts.getContainingFunctionDeclaration = getContainingFunctionDeclaration;
14545     function getContainingClass(node) {
14546         return ts.findAncestor(node.parent, ts.isClassLike);
14547     }
14548     ts.getContainingClass = getContainingClass;
14549     function getThisContainer(node, includeArrowFunctions) {
14550         ts.Debug.assert(node.kind !== 297 /* SourceFile */);
14551         while (true) {
14552             node = node.parent;
14553             if (!node) {
14554                 return ts.Debug.fail(); // If we never pass in a SourceFile, this should be unreachable, since we'll stop when we reach that.
14555             }
14556             switch (node.kind) {
14557                 case 158 /* ComputedPropertyName */:
14558                     // If the grandparent node is an object literal (as opposed to a class),
14559                     // then the computed property is not a 'this' container.
14560                     // A computed property name in a class needs to be a this container
14561                     // so that we can error on it.
14562                     if (ts.isClassLike(node.parent.parent)) {
14563                         return node;
14564                     }
14565                     // If this is a computed property, then the parent should not
14566                     // make it a this container. The parent might be a property
14567                     // in an object literal, like a method or accessor. But in order for
14568                     // such a parent to be a this container, the reference must be in
14569                     // the *body* of the container.
14570                     node = node.parent;
14571                     break;
14572                 case 161 /* Decorator */:
14573                     // Decorators are always applied outside of the body of a class or method.
14574                     if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14575                         // If the decorator's parent is a Parameter, we resolve the this container from
14576                         // the grandparent class declaration.
14577                         node = node.parent.parent;
14578                     }
14579                     else if (ts.isClassElement(node.parent)) {
14580                         // If the decorator's parent is a class element, we resolve the 'this' container
14581                         // from the parent class declaration.
14582                         node = node.parent;
14583                     }
14584                     break;
14585                 case 209 /* ArrowFunction */:
14586                     if (!includeArrowFunctions) {
14587                         continue;
14588                     }
14589                 // falls through
14590                 case 251 /* FunctionDeclaration */:
14591                 case 208 /* FunctionExpression */:
14592                 case 256 /* ModuleDeclaration */:
14593                 case 163 /* PropertyDeclaration */:
14594                 case 162 /* PropertySignature */:
14595                 case 165 /* MethodDeclaration */:
14596                 case 164 /* MethodSignature */:
14597                 case 166 /* Constructor */:
14598                 case 167 /* GetAccessor */:
14599                 case 168 /* SetAccessor */:
14600                 case 169 /* CallSignature */:
14601                 case 170 /* ConstructSignature */:
14602                 case 171 /* IndexSignature */:
14603                 case 255 /* EnumDeclaration */:
14604                 case 297 /* SourceFile */:
14605                     return node;
14606             }
14607         }
14608     }
14609     ts.getThisContainer = getThisContainer;
14610     function isInTopLevelContext(node) {
14611         // The name of a class or function declaration is a BindingIdentifier in its surrounding scope.
14612         if (ts.isIdentifier(node) && (ts.isClassDeclaration(node.parent) || ts.isFunctionDeclaration(node.parent)) && node.parent.name === node) {
14613             node = node.parent;
14614         }
14615         var container = getThisContainer(node, /*includeArrowFunctions*/ true);
14616         return ts.isSourceFile(container);
14617     }
14618     ts.isInTopLevelContext = isInTopLevelContext;
14619     function getNewTargetContainer(node) {
14620         var container = getThisContainer(node, /*includeArrowFunctions*/ false);
14621         if (container) {
14622             switch (container.kind) {
14623                 case 166 /* Constructor */:
14624                 case 251 /* FunctionDeclaration */:
14625                 case 208 /* FunctionExpression */:
14626                     return container;
14627             }
14628         }
14629         return undefined;
14630     }
14631     ts.getNewTargetContainer = getNewTargetContainer;
14632     /**
14633      * Given an super call/property node, returns the closest node where
14634      * - a super call/property access is legal in the node and not legal in the parent node the node.
14635      *   i.e. super call is legal in constructor but not legal in the class body.
14636      * - the container is an arrow function (so caller might need to call getSuperContainer again in case it needs to climb higher)
14637      * - a super call/property is definitely illegal in the container (but might be legal in some subnode)
14638      *   i.e. super property access is illegal in function declaration but can be legal in the statement list
14639      */
14640     function getSuperContainer(node, stopOnFunctions) {
14641         while (true) {
14642             node = node.parent;
14643             if (!node) {
14644                 return node;
14645             }
14646             switch (node.kind) {
14647                 case 158 /* ComputedPropertyName */:
14648                     node = node.parent;
14649                     break;
14650                 case 251 /* FunctionDeclaration */:
14651                 case 208 /* FunctionExpression */:
14652                 case 209 /* ArrowFunction */:
14653                     if (!stopOnFunctions) {
14654                         continue;
14655                     }
14656                 // falls through
14657                 case 163 /* PropertyDeclaration */:
14658                 case 162 /* PropertySignature */:
14659                 case 165 /* MethodDeclaration */:
14660                 case 164 /* MethodSignature */:
14661                 case 166 /* Constructor */:
14662                 case 167 /* GetAccessor */:
14663                 case 168 /* SetAccessor */:
14664                     return node;
14665                 case 161 /* Decorator */:
14666                     // Decorators are always applied outside of the body of a class or method.
14667                     if (node.parent.kind === 160 /* Parameter */ && ts.isClassElement(node.parent.parent)) {
14668                         // If the decorator's parent is a Parameter, we resolve the this container from
14669                         // the grandparent class declaration.
14670                         node = node.parent.parent;
14671                     }
14672                     else if (ts.isClassElement(node.parent)) {
14673                         // If the decorator's parent is a class element, we resolve the 'this' container
14674                         // from the parent class declaration.
14675                         node = node.parent;
14676                     }
14677                     break;
14678             }
14679         }
14680     }
14681     ts.getSuperContainer = getSuperContainer;
14682     function getImmediatelyInvokedFunctionExpression(func) {
14683         if (func.kind === 208 /* FunctionExpression */ || func.kind === 209 /* ArrowFunction */) {
14684             var prev = func;
14685             var parent = func.parent;
14686             while (parent.kind === 207 /* ParenthesizedExpression */) {
14687                 prev = parent;
14688                 parent = parent.parent;
14689             }
14690             if (parent.kind === 203 /* CallExpression */ && parent.expression === prev) {
14691                 return parent;
14692             }
14693         }
14694     }
14695     ts.getImmediatelyInvokedFunctionExpression = getImmediatelyInvokedFunctionExpression;
14696     function isSuperOrSuperProperty(node) {
14697         return node.kind === 105 /* SuperKeyword */
14698             || isSuperProperty(node);
14699     }
14700     ts.isSuperOrSuperProperty = isSuperOrSuperProperty;
14701     /**
14702      * Determines whether a node is a property or element access expression for `super`.
14703      */
14704     function isSuperProperty(node) {
14705         var kind = node.kind;
14706         return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */)
14707             && node.expression.kind === 105 /* SuperKeyword */;
14708     }
14709     ts.isSuperProperty = isSuperProperty;
14710     /**
14711      * Determines whether a node is a property or element access expression for `this`.
14712      */
14713     function isThisProperty(node) {
14714         var kind = node.kind;
14715         return (kind === 201 /* PropertyAccessExpression */ || kind === 202 /* ElementAccessExpression */)
14716             && node.expression.kind === 107 /* ThisKeyword */;
14717     }
14718     ts.isThisProperty = isThisProperty;
14719     function isThisInitializedDeclaration(node) {
14720         var _a;
14721         return !!node && ts.isVariableDeclaration(node) && ((_a = node.initializer) === null || _a === void 0 ? void 0 : _a.kind) === 107 /* ThisKeyword */;
14722     }
14723     ts.isThisInitializedDeclaration = isThisInitializedDeclaration;
14724     function getEntityNameFromTypeNode(node) {
14725         switch (node.kind) {
14726             case 173 /* TypeReference */:
14727                 return node.typeName;
14728             case 223 /* ExpressionWithTypeArguments */:
14729                 return isEntityNameExpression(node.expression)
14730                     ? node.expression
14731                     : undefined;
14732             // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s.
14733             case 78 /* Identifier */:
14734             case 157 /* QualifiedName */:
14735                 return node;
14736         }
14737         return undefined;
14738     }
14739     ts.getEntityNameFromTypeNode = getEntityNameFromTypeNode;
14740     function getInvokedExpression(node) {
14741         switch (node.kind) {
14742             case 205 /* TaggedTemplateExpression */:
14743                 return node.tag;
14744             case 275 /* JsxOpeningElement */:
14745             case 274 /* JsxSelfClosingElement */:
14746                 return node.tagName;
14747             default:
14748                 return node.expression;
14749         }
14750     }
14751     ts.getInvokedExpression = getInvokedExpression;
14752     function nodeCanBeDecorated(node, parent, grandparent) {
14753         // private names cannot be used with decorators yet
14754         if (ts.isNamedDeclaration(node) && ts.isPrivateIdentifier(node.name)) {
14755             return false;
14756         }
14757         switch (node.kind) {
14758             case 252 /* ClassDeclaration */:
14759                 // classes are valid targets
14760                 return true;
14761             case 163 /* PropertyDeclaration */:
14762                 // property declarations are valid if their parent is a class declaration.
14763                 return parent.kind === 252 /* ClassDeclaration */;
14764             case 167 /* GetAccessor */:
14765             case 168 /* SetAccessor */:
14766             case 165 /* MethodDeclaration */:
14767                 // if this method has a body and its parent is a class declaration, this is a valid target.
14768                 return node.body !== undefined
14769                     && parent.kind === 252 /* ClassDeclaration */;
14770             case 160 /* Parameter */:
14771                 // if the parameter's parent has a body and its grandparent is a class declaration, this is a valid target;
14772                 return parent.body !== undefined
14773                     && (parent.kind === 166 /* Constructor */
14774                         || parent.kind === 165 /* MethodDeclaration */
14775                         || parent.kind === 168 /* SetAccessor */)
14776                     && grandparent.kind === 252 /* ClassDeclaration */;
14777         }
14778         return false;
14779     }
14780     ts.nodeCanBeDecorated = nodeCanBeDecorated;
14781     function nodeIsDecorated(node, parent, grandparent) {
14782         return node.decorators !== undefined
14783             && nodeCanBeDecorated(node, parent, grandparent); // TODO: GH#18217
14784     }
14785     ts.nodeIsDecorated = nodeIsDecorated;
14786     function nodeOrChildIsDecorated(node, parent, grandparent) {
14787         return nodeIsDecorated(node, parent, grandparent) || childIsDecorated(node, parent); // TODO: GH#18217
14788     }
14789     ts.nodeOrChildIsDecorated = nodeOrChildIsDecorated;
14790     function childIsDecorated(node, parent) {
14791         switch (node.kind) {
14792             case 252 /* ClassDeclaration */:
14793                 return ts.some(node.members, function (m) { return nodeOrChildIsDecorated(m, node, parent); }); // TODO: GH#18217
14794             case 165 /* MethodDeclaration */:
14795             case 168 /* SetAccessor */:
14796                 return ts.some(node.parameters, function (p) { return nodeIsDecorated(p, node, parent); }); // TODO: GH#18217
14797             default:
14798                 return false;
14799         }
14800     }
14801     ts.childIsDecorated = childIsDecorated;
14802     function isJSXTagName(node) {
14803         var parent = node.parent;
14804         if (parent.kind === 275 /* JsxOpeningElement */ ||
14805             parent.kind === 274 /* JsxSelfClosingElement */ ||
14806             parent.kind === 276 /* JsxClosingElement */) {
14807             return parent.tagName === node;
14808         }
14809         return false;
14810     }
14811     ts.isJSXTagName = isJSXTagName;
14812     function isExpressionNode(node) {
14813         switch (node.kind) {
14814             case 105 /* SuperKeyword */:
14815             case 103 /* NullKeyword */:
14816             case 109 /* TrueKeyword */:
14817             case 94 /* FalseKeyword */:
14818             case 13 /* RegularExpressionLiteral */:
14819             case 199 /* ArrayLiteralExpression */:
14820             case 200 /* ObjectLiteralExpression */:
14821             case 201 /* PropertyAccessExpression */:
14822             case 202 /* ElementAccessExpression */:
14823             case 203 /* CallExpression */:
14824             case 204 /* NewExpression */:
14825             case 205 /* TaggedTemplateExpression */:
14826             case 224 /* AsExpression */:
14827             case 206 /* TypeAssertionExpression */:
14828             case 225 /* NonNullExpression */:
14829             case 207 /* ParenthesizedExpression */:
14830             case 208 /* FunctionExpression */:
14831             case 221 /* ClassExpression */:
14832             case 209 /* ArrowFunction */:
14833             case 212 /* VoidExpression */:
14834             case 210 /* DeleteExpression */:
14835             case 211 /* TypeOfExpression */:
14836             case 214 /* PrefixUnaryExpression */:
14837             case 215 /* PostfixUnaryExpression */:
14838             case 216 /* BinaryExpression */:
14839             case 217 /* ConditionalExpression */:
14840             case 220 /* SpreadElement */:
14841             case 218 /* TemplateExpression */:
14842             case 222 /* OmittedExpression */:
14843             case 273 /* JsxElement */:
14844             case 274 /* JsxSelfClosingElement */:
14845             case 277 /* JsxFragment */:
14846             case 219 /* YieldExpression */:
14847             case 213 /* AwaitExpression */:
14848             case 226 /* MetaProperty */:
14849                 return true;
14850             case 157 /* QualifiedName */:
14851                 while (node.parent.kind === 157 /* QualifiedName */) {
14852                     node = node.parent;
14853                 }
14854                 return node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node);
14855             case 78 /* Identifier */:
14856                 if (node.parent.kind === 176 /* TypeQuery */ || isJSXTagName(node)) {
14857                     return true;
14858                 }
14859             // falls through
14860             case 8 /* NumericLiteral */:
14861             case 9 /* BigIntLiteral */:
14862             case 10 /* StringLiteral */:
14863             case 14 /* NoSubstitutionTemplateLiteral */:
14864             case 107 /* ThisKeyword */:
14865                 return isInExpressionContext(node);
14866             default:
14867                 return false;
14868         }
14869     }
14870     ts.isExpressionNode = isExpressionNode;
14871     function isInExpressionContext(node) {
14872         var parent = node.parent;
14873         switch (parent.kind) {
14874             case 249 /* VariableDeclaration */:
14875             case 160 /* Parameter */:
14876             case 163 /* PropertyDeclaration */:
14877             case 162 /* PropertySignature */:
14878             case 291 /* EnumMember */:
14879             case 288 /* PropertyAssignment */:
14880             case 198 /* BindingElement */:
14881                 return parent.initializer === node;
14882             case 233 /* ExpressionStatement */:
14883             case 234 /* IfStatement */:
14884             case 235 /* DoStatement */:
14885             case 236 /* WhileStatement */:
14886             case 242 /* ReturnStatement */:
14887             case 243 /* WithStatement */:
14888             case 244 /* SwitchStatement */:
14889             case 284 /* CaseClause */:
14890             case 246 /* ThrowStatement */:
14891                 return parent.expression === node;
14892             case 237 /* ForStatement */:
14893                 var forStatement = parent;
14894                 return (forStatement.initializer === node && forStatement.initializer.kind !== 250 /* VariableDeclarationList */) ||
14895                     forStatement.condition === node ||
14896                     forStatement.incrementor === node;
14897             case 238 /* ForInStatement */:
14898             case 239 /* ForOfStatement */:
14899                 var forInStatement = parent;
14900                 return (forInStatement.initializer === node && forInStatement.initializer.kind !== 250 /* VariableDeclarationList */) ||
14901                     forInStatement.expression === node;
14902             case 206 /* TypeAssertionExpression */:
14903             case 224 /* AsExpression */:
14904                 return node === parent.expression;
14905             case 228 /* TemplateSpan */:
14906                 return node === parent.expression;
14907             case 158 /* ComputedPropertyName */:
14908                 return node === parent.expression;
14909             case 161 /* Decorator */:
14910             case 283 /* JsxExpression */:
14911             case 282 /* JsxSpreadAttribute */:
14912             case 290 /* SpreadAssignment */:
14913                 return true;
14914             case 223 /* ExpressionWithTypeArguments */:
14915                 return parent.expression === node && isExpressionWithTypeArgumentsInClassExtendsClause(parent);
14916             case 289 /* ShorthandPropertyAssignment */:
14917                 return parent.objectAssignmentInitializer === node;
14918             default:
14919                 return isExpressionNode(parent);
14920         }
14921     }
14922     ts.isInExpressionContext = isInExpressionContext;
14923     function isPartOfTypeQuery(node) {
14924         while (node.kind === 157 /* QualifiedName */ || node.kind === 78 /* Identifier */) {
14925             node = node.parent;
14926         }
14927         return node.kind === 176 /* TypeQuery */;
14928     }
14929     ts.isPartOfTypeQuery = isPartOfTypeQuery;
14930     function isExternalModuleImportEqualsDeclaration(node) {
14931         return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind === 272 /* ExternalModuleReference */;
14932     }
14933     ts.isExternalModuleImportEqualsDeclaration = isExternalModuleImportEqualsDeclaration;
14934     function getExternalModuleImportEqualsDeclarationExpression(node) {
14935         ts.Debug.assert(isExternalModuleImportEqualsDeclaration(node));
14936         return node.moduleReference.expression;
14937     }
14938     ts.getExternalModuleImportEqualsDeclarationExpression = getExternalModuleImportEqualsDeclarationExpression;
14939     function getExternalModuleRequireArgument(node) {
14940         return isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)
14941             && getLeftmostAccessExpression(node.initializer).arguments[0];
14942     }
14943     ts.getExternalModuleRequireArgument = getExternalModuleRequireArgument;
14944     function isInternalModuleImportEqualsDeclaration(node) {
14945         return node.kind === 260 /* ImportEqualsDeclaration */ && node.moduleReference.kind !== 272 /* ExternalModuleReference */;
14946     }
14947     ts.isInternalModuleImportEqualsDeclaration = isInternalModuleImportEqualsDeclaration;
14948     function isSourceFileJS(file) {
14949         return isInJSFile(file);
14950     }
14951     ts.isSourceFileJS = isSourceFileJS;
14952     function isSourceFileNotJS(file) {
14953         return !isInJSFile(file);
14954     }
14955     ts.isSourceFileNotJS = isSourceFileNotJS;
14956     function isInJSFile(node) {
14957         return !!node && !!(node.flags & 131072 /* JavaScriptFile */);
14958     }
14959     ts.isInJSFile = isInJSFile;
14960     function isInJsonFile(node) {
14961         return !!node && !!(node.flags & 33554432 /* JsonFile */);
14962     }
14963     ts.isInJsonFile = isInJsonFile;
14964     function isSourceFileNotJson(file) {
14965         return !isJsonSourceFile(file);
14966     }
14967     ts.isSourceFileNotJson = isSourceFileNotJson;
14968     function isInJSDoc(node) {
14969         return !!node && !!(node.flags & 4194304 /* JSDoc */);
14970     }
14971     ts.isInJSDoc = isInJSDoc;
14972     function isJSDocIndexSignature(node) {
14973         return ts.isTypeReferenceNode(node) &&
14974             ts.isIdentifier(node.typeName) &&
14975             node.typeName.escapedText === "Object" &&
14976             node.typeArguments && node.typeArguments.length === 2 &&
14977             (node.typeArguments[0].kind === 147 /* StringKeyword */ || node.typeArguments[0].kind === 144 /* NumberKeyword */);
14978     }
14979     ts.isJSDocIndexSignature = isJSDocIndexSignature;
14980     function isRequireCall(callExpression, requireStringLiteralLikeArgument) {
14981         if (callExpression.kind !== 203 /* CallExpression */) {
14982             return false;
14983         }
14984         var _a = callExpression, expression = _a.expression, args = _a.arguments;
14985         if (expression.kind !== 78 /* Identifier */ || expression.escapedText !== "require") {
14986             return false;
14987         }
14988         if (args.length !== 1) {
14989             return false;
14990         }
14991         var arg = args[0];
14992         return !requireStringLiteralLikeArgument || ts.isStringLiteralLike(arg);
14993     }
14994     ts.isRequireCall = isRequireCall;
14995     function isRequireVariableDeclaration(node, requireStringLiteralLikeArgument) {
14996         if (node.kind === 198 /* BindingElement */) {
14997             node = node.parent.parent;
14998         }
14999         return ts.isVariableDeclaration(node) && !!node.initializer && isRequireCall(getLeftmostAccessExpression(node.initializer), requireStringLiteralLikeArgument);
15000     }
15001     ts.isRequireVariableDeclaration = isRequireVariableDeclaration;
15002     function isRequireVariableStatement(node, requireStringLiteralLikeArgument) {
15003         if (requireStringLiteralLikeArgument === void 0) { requireStringLiteralLikeArgument = true; }
15004         return ts.isVariableStatement(node)
15005             && node.declarationList.declarations.length > 0
15006             && ts.every(node.declarationList.declarations, function (decl) { return isRequireVariableDeclaration(decl, requireStringLiteralLikeArgument); });
15007     }
15008     ts.isRequireVariableStatement = isRequireVariableStatement;
15009     function isSingleOrDoubleQuote(charCode) {
15010         return charCode === 39 /* singleQuote */ || charCode === 34 /* doubleQuote */;
15011     }
15012     ts.isSingleOrDoubleQuote = isSingleOrDoubleQuote;
15013     function isStringDoubleQuoted(str, sourceFile) {
15014         return getSourceTextOfNodeFromSourceFile(sourceFile, str).charCodeAt(0) === 34 /* doubleQuote */;
15015     }
15016     ts.isStringDoubleQuoted = isStringDoubleQuoted;
15017     function isAssignmentDeclaration(decl) {
15018         return ts.isBinaryExpression(decl) || isAccessExpression(decl) || ts.isIdentifier(decl) || ts.isCallExpression(decl);
15019     }
15020     ts.isAssignmentDeclaration = isAssignmentDeclaration;
15021     /** Get the initializer, taking into account defaulted Javascript initializers */
15022     function getEffectiveInitializer(node) {
15023         if (isInJSFile(node) && node.initializer &&
15024             ts.isBinaryExpression(node.initializer) &&
15025             (node.initializer.operatorToken.kind === 56 /* BarBarToken */ || node.initializer.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
15026             node.name && isEntityNameExpression(node.name) && isSameEntityName(node.name, node.initializer.left)) {
15027             return node.initializer.right;
15028         }
15029         return node.initializer;
15030     }
15031     ts.getEffectiveInitializer = getEffectiveInitializer;
15032     /** Get the declaration initializer when it is container-like (See getExpandoInitializer). */
15033     function getDeclaredExpandoInitializer(node) {
15034         var init = getEffectiveInitializer(node);
15035         return init && getExpandoInitializer(init, isPrototypeAccess(node.name));
15036     }
15037     ts.getDeclaredExpandoInitializer = getDeclaredExpandoInitializer;
15038     function hasExpandoValueProperty(node, isPrototypeAssignment) {
15039         return ts.forEach(node.properties, function (p) {
15040             return ts.isPropertyAssignment(p) &&
15041                 ts.isIdentifier(p.name) &&
15042                 p.name.escapedText === "value" &&
15043                 p.initializer &&
15044                 getExpandoInitializer(p.initializer, isPrototypeAssignment);
15045         });
15046     }
15047     /**
15048      * Get the assignment 'initializer' -- the righthand side-- when the initializer is container-like (See getExpandoInitializer).
15049      * We treat the right hand side of assignments with container-like initializers as declarations.
15050      */
15051     function getAssignedExpandoInitializer(node) {
15052         if (node && node.parent && ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */) {
15053             var isPrototypeAssignment = isPrototypeAccess(node.parent.left);
15054             return getExpandoInitializer(node.parent.right, isPrototypeAssignment) ||
15055                 getDefaultedExpandoInitializer(node.parent.left, node.parent.right, isPrototypeAssignment);
15056         }
15057         if (node && ts.isCallExpression(node) && isBindableObjectDefinePropertyCall(node)) {
15058             var result = hasExpandoValueProperty(node.arguments[2], node.arguments[1].text === "prototype");
15059             if (result) {
15060                 return result;
15061             }
15062         }
15063     }
15064     ts.getAssignedExpandoInitializer = getAssignedExpandoInitializer;
15065     /**
15066      * Recognized expando initializers are:
15067      * 1. (function() {})() -- IIFEs
15068      * 2. function() { } -- Function expressions
15069      * 3. class { } -- Class expressions
15070      * 4. {} -- Empty object literals
15071      * 5. { ... } -- Non-empty object literals, when used to initialize a prototype, like `C.prototype = { m() { } }`
15072      *
15073      * This function returns the provided initializer, or undefined if it is not valid.
15074      */
15075     function getExpandoInitializer(initializer, isPrototypeAssignment) {
15076         if (ts.isCallExpression(initializer)) {
15077             var e = skipParentheses(initializer.expression);
15078             return e.kind === 208 /* FunctionExpression */ || e.kind === 209 /* ArrowFunction */ ? initializer : undefined;
15079         }
15080         if (initializer.kind === 208 /* FunctionExpression */ ||
15081             initializer.kind === 221 /* ClassExpression */ ||
15082             initializer.kind === 209 /* ArrowFunction */) {
15083             return initializer;
15084         }
15085         if (ts.isObjectLiteralExpression(initializer) && (initializer.properties.length === 0 || isPrototypeAssignment)) {
15086             return initializer;
15087         }
15088     }
15089     ts.getExpandoInitializer = getExpandoInitializer;
15090     /**
15091      * A defaulted expando initializer matches the pattern
15092      * `Lhs = Lhs || ExpandoInitializer`
15093      * or `var Lhs = Lhs || ExpandoInitializer`
15094      *
15095      * The second Lhs is required to be the same as the first except that it may be prefixed with
15096      * 'window.', 'global.' or 'self.' The second Lhs is otherwise ignored by the binder and checker.
15097      */
15098     function getDefaultedExpandoInitializer(name, initializer, isPrototypeAssignment) {
15099         var e = ts.isBinaryExpression(initializer)
15100             && (initializer.operatorToken.kind === 56 /* BarBarToken */ || initializer.operatorToken.kind === 60 /* QuestionQuestionToken */)
15101             && getExpandoInitializer(initializer.right, isPrototypeAssignment);
15102         if (e && isSameEntityName(name, initializer.left)) {
15103             return e;
15104         }
15105     }
15106     function isDefaultedExpandoInitializer(node) {
15107         var name = ts.isVariableDeclaration(node.parent) ? node.parent.name :
15108             ts.isBinaryExpression(node.parent) && node.parent.operatorToken.kind === 62 /* EqualsToken */ ? node.parent.left :
15109                 undefined;
15110         return name && getExpandoInitializer(node.right, isPrototypeAccess(name)) && isEntityNameExpression(name) && isSameEntityName(name, node.left);
15111     }
15112     ts.isDefaultedExpandoInitializer = isDefaultedExpandoInitializer;
15113     /** Given an expando initializer, return its declaration name, or the left-hand side of the assignment if it's part of an assignment declaration. */
15114     function getNameOfExpando(node) {
15115         if (ts.isBinaryExpression(node.parent)) {
15116             var parent = ((node.parent.operatorToken.kind === 56 /* BarBarToken */ || node.parent.operatorToken.kind === 60 /* QuestionQuestionToken */) && ts.isBinaryExpression(node.parent.parent)) ? node.parent.parent : node.parent;
15117             if (parent.operatorToken.kind === 62 /* EqualsToken */ && ts.isIdentifier(parent.left)) {
15118                 return parent.left;
15119             }
15120         }
15121         else if (ts.isVariableDeclaration(node.parent)) {
15122             return node.parent.name;
15123         }
15124     }
15125     ts.getNameOfExpando = getNameOfExpando;
15126     /**
15127      * Is the 'declared' name the same as the one in the initializer?
15128      * @return true for identical entity names, as well as ones where the initializer is prefixed with
15129      * 'window', 'self' or 'global'. For example:
15130      *
15131      * var my = my || {}
15132      * var min = window.min || {}
15133      * my.app = self.my.app || class { }
15134      */
15135     function isSameEntityName(name, initializer) {
15136         if (isPropertyNameLiteral(name) && isPropertyNameLiteral(initializer)) {
15137             return getTextOfIdentifierOrLiteral(name) === getTextOfIdentifierOrLiteral(initializer);
15138         }
15139         if (ts.isIdentifier(name) && isLiteralLikeAccess(initializer) &&
15140             (initializer.expression.kind === 107 /* ThisKeyword */ ||
15141                 ts.isIdentifier(initializer.expression) &&
15142                     (initializer.expression.escapedText === "window" ||
15143                         initializer.expression.escapedText === "self" ||
15144                         initializer.expression.escapedText === "global"))) {
15145             var nameOrArgument = getNameOrArgument(initializer);
15146             if (ts.isPrivateIdentifier(nameOrArgument)) {
15147                 ts.Debug.fail("Unexpected PrivateIdentifier in name expression with literal-like access.");
15148             }
15149             return isSameEntityName(name, nameOrArgument);
15150         }
15151         if (isLiteralLikeAccess(name) && isLiteralLikeAccess(initializer)) {
15152             return getElementOrPropertyAccessName(name) === getElementOrPropertyAccessName(initializer)
15153                 && isSameEntityName(name.expression, initializer.expression);
15154         }
15155         return false;
15156     }
15157     ts.isSameEntityName = isSameEntityName;
15158     function getRightMostAssignedExpression(node) {
15159         while (isAssignmentExpression(node, /*excludeCompoundAssignments*/ true)) {
15160             node = node.right;
15161         }
15162         return node;
15163     }
15164     ts.getRightMostAssignedExpression = getRightMostAssignedExpression;
15165     function isExportsIdentifier(node) {
15166         return ts.isIdentifier(node) && node.escapedText === "exports";
15167     }
15168     ts.isExportsIdentifier = isExportsIdentifier;
15169     function isModuleIdentifier(node) {
15170         return ts.isIdentifier(node) && node.escapedText === "module";
15171     }
15172     ts.isModuleIdentifier = isModuleIdentifier;
15173     function isModuleExportsAccessExpression(node) {
15174         return (ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node))
15175             && isModuleIdentifier(node.expression)
15176             && getElementOrPropertyAccessName(node) === "exports";
15177     }
15178     ts.isModuleExportsAccessExpression = isModuleExportsAccessExpression;
15179     /// Given a BinaryExpression, returns SpecialPropertyAssignmentKind for the various kinds of property
15180     /// assignments we treat as special in the binder
15181     function getAssignmentDeclarationKind(expr) {
15182         var special = getAssignmentDeclarationKindWorker(expr);
15183         return special === 5 /* Property */ || isInJSFile(expr) ? special : 0 /* None */;
15184     }
15185     ts.getAssignmentDeclarationKind = getAssignmentDeclarationKind;
15186     function isBindableObjectDefinePropertyCall(expr) {
15187         return ts.length(expr.arguments) === 3 &&
15188             ts.isPropertyAccessExpression(expr.expression) &&
15189             ts.isIdentifier(expr.expression.expression) &&
15190             ts.idText(expr.expression.expression) === "Object" &&
15191             ts.idText(expr.expression.name) === "defineProperty" &&
15192             isStringOrNumericLiteralLike(expr.arguments[1]) &&
15193             isBindableStaticNameExpression(expr.arguments[0], /*excludeThisKeyword*/ true);
15194     }
15195     ts.isBindableObjectDefinePropertyCall = isBindableObjectDefinePropertyCall;
15196     /** x.y OR x[0] */
15197     function isLiteralLikeAccess(node) {
15198         return ts.isPropertyAccessExpression(node) || isLiteralLikeElementAccess(node);
15199     }
15200     ts.isLiteralLikeAccess = isLiteralLikeAccess;
15201     /** x[0] OR x['a'] OR x[Symbol.y] */
15202     function isLiteralLikeElementAccess(node) {
15203         return ts.isElementAccessExpression(node) && (isStringOrNumericLiteralLike(node.argumentExpression) ||
15204             isWellKnownSymbolSyntactically(node.argumentExpression));
15205     }
15206     ts.isLiteralLikeElementAccess = isLiteralLikeElementAccess;
15207     /** Any series of property and element accesses. */
15208     function isBindableStaticAccessExpression(node, excludeThisKeyword) {
15209         return ts.isPropertyAccessExpression(node) && (!excludeThisKeyword && node.expression.kind === 107 /* ThisKeyword */ || ts.isIdentifier(node.name) && isBindableStaticNameExpression(node.expression, /*excludeThisKeyword*/ true))
15210             || isBindableStaticElementAccessExpression(node, excludeThisKeyword);
15211     }
15212     ts.isBindableStaticAccessExpression = isBindableStaticAccessExpression;
15213     /** Any series of property and element accesses, ending in a literal element access */
15214     function isBindableStaticElementAccessExpression(node, excludeThisKeyword) {
15215         return isLiteralLikeElementAccess(node)
15216             && ((!excludeThisKeyword && node.expression.kind === 107 /* ThisKeyword */) ||
15217                 isEntityNameExpression(node.expression) ||
15218                 isBindableStaticAccessExpression(node.expression, /*excludeThisKeyword*/ true));
15219     }
15220     ts.isBindableStaticElementAccessExpression = isBindableStaticElementAccessExpression;
15221     function isBindableStaticNameExpression(node, excludeThisKeyword) {
15222         return isEntityNameExpression(node) || isBindableStaticAccessExpression(node, excludeThisKeyword);
15223     }
15224     ts.isBindableStaticNameExpression = isBindableStaticNameExpression;
15225     function getNameOrArgument(expr) {
15226         if (ts.isPropertyAccessExpression(expr)) {
15227             return expr.name;
15228         }
15229         return expr.argumentExpression;
15230     }
15231     ts.getNameOrArgument = getNameOrArgument;
15232     function getAssignmentDeclarationKindWorker(expr) {
15233         if (ts.isCallExpression(expr)) {
15234             if (!isBindableObjectDefinePropertyCall(expr)) {
15235                 return 0 /* None */;
15236             }
15237             var entityName = expr.arguments[0];
15238             if (isExportsIdentifier(entityName) || isModuleExportsAccessExpression(entityName)) {
15239                 return 8 /* ObjectDefinePropertyExports */;
15240             }
15241             if (isBindableStaticAccessExpression(entityName) && getElementOrPropertyAccessName(entityName) === "prototype") {
15242                 return 9 /* ObjectDefinePrototypeProperty */;
15243             }
15244             return 7 /* ObjectDefinePropertyValue */;
15245         }
15246         if (expr.operatorToken.kind !== 62 /* EqualsToken */ || !isAccessExpression(expr.left) || isVoidZero(getRightMostAssignedExpression(expr))) {
15247             return 0 /* None */;
15248         }
15249         if (isBindableStaticNameExpression(expr.left.expression, /*excludeThisKeyword*/ true) && getElementOrPropertyAccessName(expr.left) === "prototype" && ts.isObjectLiteralExpression(getInitializerOfBinaryExpression(expr))) {
15250             // F.prototype = { ... }
15251             return 6 /* Prototype */;
15252         }
15253         return getAssignmentDeclarationPropertyAccessKind(expr.left);
15254     }
15255     function isVoidZero(node) {
15256         return ts.isVoidExpression(node) && ts.isNumericLiteral(node.expression) && node.expression.text === "0";
15257     }
15258     /**
15259      * Does not handle signed numeric names like `a[+0]` - handling those would require handling prefix unary expressions
15260      * throughout late binding handling as well, which is awkward (but ultimately probably doable if there is demand)
15261      */
15262     /* @internal */
15263     function getElementOrPropertyAccessArgumentExpressionOrName(node) {
15264         if (ts.isPropertyAccessExpression(node)) {
15265             return node.name;
15266         }
15267         var arg = skipParentheses(node.argumentExpression);
15268         if (ts.isNumericLiteral(arg) || ts.isStringLiteralLike(arg)) {
15269             return arg;
15270         }
15271         return node;
15272     }
15273     ts.getElementOrPropertyAccessArgumentExpressionOrName = getElementOrPropertyAccessArgumentExpressionOrName;
15274     function getElementOrPropertyAccessName(node) {
15275         var name = getElementOrPropertyAccessArgumentExpressionOrName(node);
15276         if (name) {
15277             if (ts.isIdentifier(name)) {
15278                 return name.escapedText;
15279             }
15280             if (ts.isStringLiteralLike(name) || ts.isNumericLiteral(name)) {
15281                 return ts.escapeLeadingUnderscores(name.text);
15282             }
15283         }
15284         if (ts.isElementAccessExpression(node) && isWellKnownSymbolSyntactically(node.argumentExpression)) {
15285             return getPropertyNameForKnownSymbolName(ts.idText(node.argumentExpression.name));
15286         }
15287         return undefined;
15288     }
15289     ts.getElementOrPropertyAccessName = getElementOrPropertyAccessName;
15290     function getAssignmentDeclarationPropertyAccessKind(lhs) {
15291         if (lhs.expression.kind === 107 /* ThisKeyword */) {
15292             return 4 /* ThisProperty */;
15293         }
15294         else if (isModuleExportsAccessExpression(lhs)) {
15295             // module.exports = expr
15296             return 2 /* ModuleExports */;
15297         }
15298         else if (isBindableStaticNameExpression(lhs.expression, /*excludeThisKeyword*/ true)) {
15299             if (isPrototypeAccess(lhs.expression)) {
15300                 // F.G....prototype.x = expr
15301                 return 3 /* PrototypeProperty */;
15302             }
15303             var nextToLast = lhs;
15304             while (!ts.isIdentifier(nextToLast.expression)) {
15305                 nextToLast = nextToLast.expression;
15306             }
15307             var id = nextToLast.expression;
15308             if ((id.escapedText === "exports" ||
15309                 id.escapedText === "module" && getElementOrPropertyAccessName(nextToLast) === "exports") &&
15310                 // ExportsProperty does not support binding with computed names
15311                 isBindableStaticAccessExpression(lhs)) {
15312                 // exports.name = expr OR module.exports.name = expr OR exports["name"] = expr ...
15313                 return 1 /* ExportsProperty */;
15314             }
15315             if (isBindableStaticNameExpression(lhs, /*excludeThisKeyword*/ true) || (ts.isElementAccessExpression(lhs) && isDynamicName(lhs))) {
15316                 // F.G...x = expr
15317                 return 5 /* Property */;
15318             }
15319         }
15320         return 0 /* None */;
15321     }
15322     ts.getAssignmentDeclarationPropertyAccessKind = getAssignmentDeclarationPropertyAccessKind;
15323     function getInitializerOfBinaryExpression(expr) {
15324         while (ts.isBinaryExpression(expr.right)) {
15325             expr = expr.right;
15326         }
15327         return expr.right;
15328     }
15329     ts.getInitializerOfBinaryExpression = getInitializerOfBinaryExpression;
15330     function isPrototypePropertyAssignment(node) {
15331         return ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 3 /* PrototypeProperty */;
15332     }
15333     ts.isPrototypePropertyAssignment = isPrototypePropertyAssignment;
15334     function isSpecialPropertyDeclaration(expr) {
15335         return isInJSFile(expr) &&
15336             expr.parent && expr.parent.kind === 233 /* ExpressionStatement */ &&
15337             (!ts.isElementAccessExpression(expr) || isLiteralLikeElementAccess(expr)) &&
15338             !!ts.getJSDocTypeTag(expr.parent);
15339     }
15340     ts.isSpecialPropertyDeclaration = isSpecialPropertyDeclaration;
15341     function setValueDeclaration(symbol, node) {
15342         var valueDeclaration = symbol.valueDeclaration;
15343         if (!valueDeclaration ||
15344             !(node.flags & 8388608 /* Ambient */ && !(valueDeclaration.flags & 8388608 /* Ambient */)) &&
15345                 (isAssignmentDeclaration(valueDeclaration) && !isAssignmentDeclaration(node)) ||
15346             (valueDeclaration.kind !== node.kind && isEffectiveModuleDeclaration(valueDeclaration))) {
15347             // other kinds of value declarations take precedence over modules and assignment declarations
15348             symbol.valueDeclaration = node;
15349         }
15350     }
15351     ts.setValueDeclaration = setValueDeclaration;
15352     function isFunctionSymbol(symbol) {
15353         if (!symbol || !symbol.valueDeclaration) {
15354             return false;
15355         }
15356         var decl = symbol.valueDeclaration;
15357         return decl.kind === 251 /* FunctionDeclaration */ || ts.isVariableDeclaration(decl) && decl.initializer && ts.isFunctionLike(decl.initializer);
15358     }
15359     ts.isFunctionSymbol = isFunctionSymbol;
15360     function importFromModuleSpecifier(node) {
15361         return tryGetImportFromModuleSpecifier(node) || ts.Debug.failBadSyntaxKind(node.parent);
15362     }
15363     ts.importFromModuleSpecifier = importFromModuleSpecifier;
15364     function tryGetImportFromModuleSpecifier(node) {
15365         switch (node.parent.kind) {
15366             case 261 /* ImportDeclaration */:
15367             case 267 /* ExportDeclaration */:
15368                 return node.parent;
15369             case 272 /* ExternalModuleReference */:
15370                 return node.parent.parent;
15371             case 203 /* CallExpression */:
15372                 return isImportCall(node.parent) || isRequireCall(node.parent, /*checkArg*/ false) ? node.parent : undefined;
15373             case 191 /* LiteralType */:
15374                 ts.Debug.assert(ts.isStringLiteral(node));
15375                 return ts.tryCast(node.parent.parent, ts.isImportTypeNode);
15376             default:
15377                 return undefined;
15378         }
15379     }
15380     ts.tryGetImportFromModuleSpecifier = tryGetImportFromModuleSpecifier;
15381     function getExternalModuleName(node) {
15382         switch (node.kind) {
15383             case 261 /* ImportDeclaration */:
15384             case 267 /* ExportDeclaration */:
15385                 return node.moduleSpecifier;
15386             case 260 /* ImportEqualsDeclaration */:
15387                 return node.moduleReference.kind === 272 /* ExternalModuleReference */ ? node.moduleReference.expression : undefined;
15388             case 195 /* ImportType */:
15389                 return isLiteralImportTypeNode(node) ? node.argument.literal : undefined;
15390             default:
15391                 return ts.Debug.assertNever(node);
15392         }
15393     }
15394     ts.getExternalModuleName = getExternalModuleName;
15395     function getNamespaceDeclarationNode(node) {
15396         switch (node.kind) {
15397             case 261 /* ImportDeclaration */:
15398                 return node.importClause && ts.tryCast(node.importClause.namedBindings, ts.isNamespaceImport);
15399             case 260 /* ImportEqualsDeclaration */:
15400                 return node;
15401             case 267 /* ExportDeclaration */:
15402                 return node.exportClause && ts.tryCast(node.exportClause, ts.isNamespaceExport);
15403             default:
15404                 return ts.Debug.assertNever(node);
15405         }
15406     }
15407     ts.getNamespaceDeclarationNode = getNamespaceDeclarationNode;
15408     function isDefaultImport(node) {
15409         return node.kind === 261 /* ImportDeclaration */ && !!node.importClause && !!node.importClause.name;
15410     }
15411     ts.isDefaultImport = isDefaultImport;
15412     function forEachImportClauseDeclaration(node, action) {
15413         if (node.name) {
15414             var result = action(node);
15415             if (result)
15416                 return result;
15417         }
15418         if (node.namedBindings) {
15419             var result = ts.isNamespaceImport(node.namedBindings)
15420                 ? action(node.namedBindings)
15421                 : ts.forEach(node.namedBindings.elements, action);
15422             if (result)
15423                 return result;
15424         }
15425     }
15426     ts.forEachImportClauseDeclaration = forEachImportClauseDeclaration;
15427     function hasQuestionToken(node) {
15428         if (node) {
15429             switch (node.kind) {
15430                 case 160 /* Parameter */:
15431                 case 165 /* MethodDeclaration */:
15432                 case 164 /* MethodSignature */:
15433                 case 289 /* ShorthandPropertyAssignment */:
15434                 case 288 /* PropertyAssignment */:
15435                 case 163 /* PropertyDeclaration */:
15436                 case 162 /* PropertySignature */:
15437                     return node.questionToken !== undefined;
15438             }
15439         }
15440         return false;
15441     }
15442     ts.hasQuestionToken = hasQuestionToken;
15443     function isJSDocConstructSignature(node) {
15444         var param = ts.isJSDocFunctionType(node) ? ts.firstOrUndefined(node.parameters) : undefined;
15445         var name = ts.tryCast(param && param.name, ts.isIdentifier);
15446         return !!name && name.escapedText === "new";
15447     }
15448     ts.isJSDocConstructSignature = isJSDocConstructSignature;
15449     function isJSDocTypeAlias(node) {
15450         return node.kind === 331 /* JSDocTypedefTag */ || node.kind === 324 /* JSDocCallbackTag */ || node.kind === 325 /* JSDocEnumTag */;
15451     }
15452     ts.isJSDocTypeAlias = isJSDocTypeAlias;
15453     function isTypeAlias(node) {
15454         return isJSDocTypeAlias(node) || ts.isTypeAliasDeclaration(node);
15455     }
15456     ts.isTypeAlias = isTypeAlias;
15457     function getSourceOfAssignment(node) {
15458         return ts.isExpressionStatement(node) &&
15459             ts.isBinaryExpression(node.expression) &&
15460             node.expression.operatorToken.kind === 62 /* EqualsToken */
15461             ? getRightMostAssignedExpression(node.expression)
15462             : undefined;
15463     }
15464     function getSourceOfDefaultedAssignment(node) {
15465         return ts.isExpressionStatement(node) &&
15466             ts.isBinaryExpression(node.expression) &&
15467             getAssignmentDeclarationKind(node.expression) !== 0 /* None */ &&
15468             ts.isBinaryExpression(node.expression.right) &&
15469             (node.expression.right.operatorToken.kind === 56 /* BarBarToken */ || node.expression.right.operatorToken.kind === 60 /* QuestionQuestionToken */)
15470             ? node.expression.right.right
15471             : undefined;
15472     }
15473     function getSingleInitializerOfVariableStatementOrPropertyDeclaration(node) {
15474         switch (node.kind) {
15475             case 232 /* VariableStatement */:
15476                 var v = getSingleVariableOfVariableStatement(node);
15477                 return v && v.initializer;
15478             case 163 /* PropertyDeclaration */:
15479                 return node.initializer;
15480             case 288 /* PropertyAssignment */:
15481                 return node.initializer;
15482         }
15483     }
15484     ts.getSingleInitializerOfVariableStatementOrPropertyDeclaration = getSingleInitializerOfVariableStatementOrPropertyDeclaration;
15485     function getSingleVariableOfVariableStatement(node) {
15486         return ts.isVariableStatement(node) ? ts.firstOrUndefined(node.declarationList.declarations) : undefined;
15487     }
15488     ts.getSingleVariableOfVariableStatement = getSingleVariableOfVariableStatement;
15489     function getNestedModuleDeclaration(node) {
15490         return ts.isModuleDeclaration(node) &&
15491             node.body &&
15492             node.body.kind === 256 /* ModuleDeclaration */
15493             ? node.body
15494             : undefined;
15495     }
15496     function getJSDocCommentsAndTags(hostNode, noCache) {
15497         var result;
15498         // Pull parameter comments from declaring function as well
15499         if (isVariableLike(hostNode) && ts.hasInitializer(hostNode) && ts.hasJSDocNodes(hostNode.initializer)) {
15500             result = ts.append(result, ts.last(hostNode.initializer.jsDoc));
15501         }
15502         var node = hostNode;
15503         while (node && node.parent) {
15504             if (ts.hasJSDocNodes(node)) {
15505                 result = ts.append(result, ts.last(node.jsDoc));
15506             }
15507             if (node.kind === 160 /* Parameter */) {
15508                 result = ts.addRange(result, (noCache ? ts.getJSDocParameterTagsNoCache : ts.getJSDocParameterTags)(node));
15509                 break;
15510             }
15511             if (node.kind === 159 /* TypeParameter */) {
15512                 result = ts.addRange(result, (noCache ? ts.getJSDocTypeParameterTagsNoCache : ts.getJSDocTypeParameterTags)(node));
15513                 break;
15514             }
15515             node = getNextJSDocCommentLocation(node);
15516         }
15517         return result || ts.emptyArray;
15518     }
15519     ts.getJSDocCommentsAndTags = getJSDocCommentsAndTags;
15520     function getNextJSDocCommentLocation(node) {
15521         var parent = node.parent;
15522         if (parent.kind === 288 /* PropertyAssignment */ ||
15523             parent.kind === 266 /* ExportAssignment */ ||
15524             parent.kind === 163 /* PropertyDeclaration */ ||
15525             parent.kind === 233 /* ExpressionStatement */ && node.kind === 201 /* PropertyAccessExpression */ ||
15526             getNestedModuleDeclaration(parent) ||
15527             ts.isBinaryExpression(node) && node.operatorToken.kind === 62 /* EqualsToken */) {
15528             return parent;
15529         }
15530         // Try to recognize this pattern when node is initializer of variable declaration and JSDoc comments are on containing variable statement.
15531         // /**
15532         //   * @param {number} name
15533         //   * @returns {number}
15534         //   */
15535         // var x = function(name) { return name.length; }
15536         else if (parent.parent &&
15537             (getSingleVariableOfVariableStatement(parent.parent) === node ||
15538                 ts.isBinaryExpression(parent) && parent.operatorToken.kind === 62 /* EqualsToken */)) {
15539             return parent.parent;
15540         }
15541         else if (parent.parent && parent.parent.parent &&
15542             (getSingleVariableOfVariableStatement(parent.parent.parent) ||
15543                 getSingleInitializerOfVariableStatementOrPropertyDeclaration(parent.parent.parent) === node ||
15544                 getSourceOfDefaultedAssignment(parent.parent.parent))) {
15545             return parent.parent.parent;
15546         }
15547     }
15548     /** Does the opposite of `getJSDocParameterTags`: given a JSDoc parameter, finds the parameter corresponding to it. */
15549     function getParameterSymbolFromJSDoc(node) {
15550         if (node.symbol) {
15551             return node.symbol;
15552         }
15553         if (!ts.isIdentifier(node.name)) {
15554             return undefined;
15555         }
15556         var name = node.name.escapedText;
15557         var decl = getHostSignatureFromJSDoc(node);
15558         if (!decl) {
15559             return undefined;
15560         }
15561         var parameter = ts.find(decl.parameters, function (p) { return p.name.kind === 78 /* Identifier */ && p.name.escapedText === name; });
15562         return parameter && parameter.symbol;
15563     }
15564     ts.getParameterSymbolFromJSDoc = getParameterSymbolFromJSDoc;
15565     function getHostSignatureFromJSDoc(node) {
15566         var host = getEffectiveJSDocHost(node);
15567         return host && ts.isFunctionLike(host) ? host : undefined;
15568     }
15569     ts.getHostSignatureFromJSDoc = getHostSignatureFromJSDoc;
15570     function getEffectiveJSDocHost(node) {
15571         var host = getJSDocHost(node);
15572         var decl = getSourceOfDefaultedAssignment(host) ||
15573             getSourceOfAssignment(host) ||
15574             getSingleInitializerOfVariableStatementOrPropertyDeclaration(host) ||
15575             getSingleVariableOfVariableStatement(host) ||
15576             getNestedModuleDeclaration(host) ||
15577             host;
15578         return decl;
15579     }
15580     ts.getEffectiveJSDocHost = getEffectiveJSDocHost;
15581     /** Use getEffectiveJSDocHost if you additionally need to look for jsdoc on parent nodes, like assignments.  */
15582     function getJSDocHost(node) {
15583         return ts.Debug.checkDefined(ts.findAncestor(node.parent, ts.isJSDoc)).parent;
15584     }
15585     ts.getJSDocHost = getJSDocHost;
15586     function getTypeParameterFromJsDoc(node) {
15587         var name = node.name.escapedText;
15588         var typeParameters = node.parent.parent.parent.typeParameters;
15589         return typeParameters && ts.find(typeParameters, function (p) { return p.name.escapedText === name; });
15590     }
15591     ts.getTypeParameterFromJsDoc = getTypeParameterFromJsDoc;
15592     function hasRestParameter(s) {
15593         var last = ts.lastOrUndefined(s.parameters);
15594         return !!last && isRestParameter(last);
15595     }
15596     ts.hasRestParameter = hasRestParameter;
15597     function isRestParameter(node) {
15598         var type = ts.isJSDocParameterTag(node) ? (node.typeExpression && node.typeExpression.type) : node.type;
15599         return node.dotDotDotToken !== undefined || !!type && type.kind === 309 /* JSDocVariadicType */;
15600     }
15601     ts.isRestParameter = isRestParameter;
15602     function hasTypeArguments(node) {
15603         return !!node.typeArguments;
15604     }
15605     ts.hasTypeArguments = hasTypeArguments;
15606     var AssignmentKind;
15607     (function (AssignmentKind) {
15608         AssignmentKind[AssignmentKind["None"] = 0] = "None";
15609         AssignmentKind[AssignmentKind["Definite"] = 1] = "Definite";
15610         AssignmentKind[AssignmentKind["Compound"] = 2] = "Compound";
15611     })(AssignmentKind = ts.AssignmentKind || (ts.AssignmentKind = {}));
15612     function getAssignmentTargetKind(node) {
15613         var parent = node.parent;
15614         while (true) {
15615             switch (parent.kind) {
15616                 case 216 /* BinaryExpression */:
15617                     var binaryOperator = parent.operatorToken.kind;
15618                     return isAssignmentOperator(binaryOperator) && parent.left === node ?
15619                         binaryOperator === 62 /* EqualsToken */ || isLogicalOrCoalescingAssignmentOperator(binaryOperator) ? 1 /* Definite */ : 2 /* Compound */ :
15620                         0 /* None */;
15621                 case 214 /* PrefixUnaryExpression */:
15622                 case 215 /* PostfixUnaryExpression */:
15623                     var unaryOperator = parent.operator;
15624                     return unaryOperator === 45 /* PlusPlusToken */ || unaryOperator === 46 /* MinusMinusToken */ ? 2 /* Compound */ : 0 /* None */;
15625                 case 238 /* ForInStatement */:
15626                 case 239 /* ForOfStatement */:
15627                     return parent.initializer === node ? 1 /* Definite */ : 0 /* None */;
15628                 case 207 /* ParenthesizedExpression */:
15629                 case 199 /* ArrayLiteralExpression */:
15630                 case 220 /* SpreadElement */:
15631                 case 225 /* NonNullExpression */:
15632                     node = parent;
15633                     break;
15634                 case 289 /* ShorthandPropertyAssignment */:
15635                     if (parent.name !== node) {
15636                         return 0 /* None */;
15637                     }
15638                     node = parent.parent;
15639                     break;
15640                 case 288 /* PropertyAssignment */:
15641                     if (parent.name === node) {
15642                         return 0 /* None */;
15643                     }
15644                     node = parent.parent;
15645                     break;
15646                 default:
15647                     return 0 /* None */;
15648             }
15649             parent = node.parent;
15650         }
15651     }
15652     ts.getAssignmentTargetKind = getAssignmentTargetKind;
15653     // A node is an assignment target if it is on the left hand side of an '=' token, if it is parented by a property
15654     // assignment in an object literal that is an assignment target, or if it is parented by an array literal that is
15655     // an assignment target. Examples include 'a = xxx', '{ p: a } = xxx', '[{ a }] = xxx'.
15656     // (Note that `p` is not a target in the above examples, only `a`.)
15657     function isAssignmentTarget(node) {
15658         return getAssignmentTargetKind(node) !== 0 /* None */;
15659     }
15660     ts.isAssignmentTarget = isAssignmentTarget;
15661     /**
15662      * Indicates whether a node could contain a `var` VariableDeclarationList that contributes to
15663      * the same `var` declaration scope as the node's parent.
15664      */
15665     function isNodeWithPossibleHoistedDeclaration(node) {
15666         switch (node.kind) {
15667             case 230 /* Block */:
15668             case 232 /* VariableStatement */:
15669             case 243 /* WithStatement */:
15670             case 234 /* IfStatement */:
15671             case 244 /* SwitchStatement */:
15672             case 258 /* CaseBlock */:
15673             case 284 /* CaseClause */:
15674             case 285 /* DefaultClause */:
15675             case 245 /* LabeledStatement */:
15676             case 237 /* ForStatement */:
15677             case 238 /* ForInStatement */:
15678             case 239 /* ForOfStatement */:
15679             case 235 /* DoStatement */:
15680             case 236 /* WhileStatement */:
15681             case 247 /* TryStatement */:
15682             case 287 /* CatchClause */:
15683                 return true;
15684         }
15685         return false;
15686     }
15687     ts.isNodeWithPossibleHoistedDeclaration = isNodeWithPossibleHoistedDeclaration;
15688     function isValueSignatureDeclaration(node) {
15689         return ts.isFunctionExpression(node) || ts.isArrowFunction(node) || ts.isMethodOrAccessor(node) || ts.isFunctionDeclaration(node) || ts.isConstructorDeclaration(node);
15690     }
15691     ts.isValueSignatureDeclaration = isValueSignatureDeclaration;
15692     function walkUp(node, kind) {
15693         while (node && node.kind === kind) {
15694             node = node.parent;
15695         }
15696         return node;
15697     }
15698     function walkUpParenthesizedTypes(node) {
15699         return walkUp(node, 186 /* ParenthesizedType */);
15700     }
15701     ts.walkUpParenthesizedTypes = walkUpParenthesizedTypes;
15702     function walkUpParenthesizedExpressions(node) {
15703         return walkUp(node, 207 /* ParenthesizedExpression */);
15704     }
15705     ts.walkUpParenthesizedExpressions = walkUpParenthesizedExpressions;
15706     /**
15707      * Walks up parenthesized types.
15708      * It returns both the outermost parenthesized type and its parent.
15709      * If given node is not a parenthesiezd type, undefined is return as the former.
15710      */
15711     function walkUpParenthesizedTypesAndGetParentAndChild(node) {
15712         var child;
15713         while (node && node.kind === 186 /* ParenthesizedType */) {
15714             child = node;
15715             node = node.parent;
15716         }
15717         return [child, node];
15718     }
15719     ts.walkUpParenthesizedTypesAndGetParentAndChild = walkUpParenthesizedTypesAndGetParentAndChild;
15720     function skipParentheses(node) {
15721         return ts.skipOuterExpressions(node, 1 /* Parentheses */);
15722     }
15723     ts.skipParentheses = skipParentheses;
15724     function skipParenthesesUp(node) {
15725         while (node.kind === 207 /* ParenthesizedExpression */) {
15726             node = node.parent;
15727         }
15728         return node;
15729     }
15730     // a node is delete target iff. it is PropertyAccessExpression/ElementAccessExpression with parentheses skipped
15731     function isDeleteTarget(node) {
15732         if (node.kind !== 201 /* PropertyAccessExpression */ && node.kind !== 202 /* ElementAccessExpression */) {
15733             return false;
15734         }
15735         node = walkUpParenthesizedExpressions(node.parent);
15736         return node && node.kind === 210 /* DeleteExpression */;
15737     }
15738     ts.isDeleteTarget = isDeleteTarget;
15739     function isNodeDescendantOf(node, ancestor) {
15740         while (node) {
15741             if (node === ancestor)
15742                 return true;
15743             node = node.parent;
15744         }
15745         return false;
15746     }
15747     ts.isNodeDescendantOf = isNodeDescendantOf;
15748     // True if `name` is the name of a declaration node
15749     function isDeclarationName(name) {
15750         return !ts.isSourceFile(name) && !ts.isBindingPattern(name) && ts.isDeclaration(name.parent) && name.parent.name === name;
15751     }
15752     ts.isDeclarationName = isDeclarationName;
15753     // See GH#16030
15754     function getDeclarationFromName(name) {
15755         var parent = name.parent;
15756         switch (name.kind) {
15757             case 10 /* StringLiteral */:
15758             case 14 /* NoSubstitutionTemplateLiteral */:
15759             case 8 /* NumericLiteral */:
15760                 if (ts.isComputedPropertyName(parent))
15761                     return parent.parent;
15762             // falls through
15763             case 78 /* Identifier */:
15764                 if (ts.isDeclaration(parent)) {
15765                     return parent.name === name ? parent : undefined;
15766                 }
15767                 else if (ts.isQualifiedName(parent)) {
15768                     var tag = parent.parent;
15769                     return ts.isJSDocParameterTag(tag) && tag.name === parent ? tag : undefined;
15770                 }
15771                 else {
15772                     var binExp = parent.parent;
15773                     return ts.isBinaryExpression(binExp) &&
15774                         getAssignmentDeclarationKind(binExp) !== 0 /* None */ &&
15775                         (binExp.left.symbol || binExp.symbol) &&
15776                         ts.getNameOfDeclaration(binExp) === name
15777                         ? binExp
15778                         : undefined;
15779                 }
15780             case 79 /* PrivateIdentifier */:
15781                 return ts.isDeclaration(parent) && parent.name === name ? parent : undefined;
15782             default:
15783                 return undefined;
15784         }
15785     }
15786     ts.getDeclarationFromName = getDeclarationFromName;
15787     function isLiteralComputedPropertyDeclarationName(node) {
15788         return isStringOrNumericLiteralLike(node) &&
15789             node.parent.kind === 158 /* ComputedPropertyName */ &&
15790             ts.isDeclaration(node.parent.parent);
15791     }
15792     ts.isLiteralComputedPropertyDeclarationName = isLiteralComputedPropertyDeclarationName;
15793     // Return true if the given identifier is classified as an IdentifierName
15794     function isIdentifierName(node) {
15795         var parent = node.parent;
15796         switch (parent.kind) {
15797             case 163 /* PropertyDeclaration */:
15798             case 162 /* PropertySignature */:
15799             case 165 /* MethodDeclaration */:
15800             case 164 /* MethodSignature */:
15801             case 167 /* GetAccessor */:
15802             case 168 /* SetAccessor */:
15803             case 291 /* EnumMember */:
15804             case 288 /* PropertyAssignment */:
15805             case 201 /* PropertyAccessExpression */:
15806                 // Name in member declaration or property name in property access
15807                 return parent.name === node;
15808             case 157 /* QualifiedName */:
15809                 // Name on right hand side of dot in a type query or type reference
15810                 return parent.right === node;
15811             case 198 /* BindingElement */:
15812             case 265 /* ImportSpecifier */:
15813                 // Property name in binding element or import specifier
15814                 return parent.propertyName === node;
15815             case 270 /* ExportSpecifier */:
15816             case 280 /* JsxAttribute */:
15817                 // Any name in an export specifier or JSX Attribute
15818                 return true;
15819         }
15820         return false;
15821     }
15822     ts.isIdentifierName = isIdentifierName;
15823     // An alias symbol is created by one of the following declarations:
15824     // import <symbol> = ...
15825     // import <symbol> from ...
15826     // import * as <symbol> from ...
15827     // import { x as <symbol> } from ...
15828     // export { x as <symbol> } from ...
15829     // export * as ns <symbol> from ...
15830     // export = <EntityNameExpression>
15831     // export default <EntityNameExpression>
15832     // module.exports = <EntityNameExpression>
15833     // {<Identifier>}
15834     // {name: <EntityNameExpression>}
15835     function isAliasSymbolDeclaration(node) {
15836         return node.kind === 260 /* ImportEqualsDeclaration */ ||
15837             node.kind === 259 /* NamespaceExportDeclaration */ ||
15838             node.kind === 262 /* ImportClause */ && !!node.name ||
15839             node.kind === 263 /* NamespaceImport */ ||
15840             node.kind === 269 /* NamespaceExport */ ||
15841             node.kind === 265 /* ImportSpecifier */ ||
15842             node.kind === 270 /* ExportSpecifier */ ||
15843             node.kind === 266 /* ExportAssignment */ && exportAssignmentIsAlias(node) ||
15844             ts.isBinaryExpression(node) && getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && exportAssignmentIsAlias(node) ||
15845             ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */ && isAliasableExpression(node.parent.right) ||
15846             node.kind === 289 /* ShorthandPropertyAssignment */ ||
15847             node.kind === 288 /* PropertyAssignment */ && isAliasableExpression(node.initializer);
15848     }
15849     ts.isAliasSymbolDeclaration = isAliasSymbolDeclaration;
15850     function getAliasDeclarationFromName(node) {
15851         switch (node.parent.kind) {
15852             case 262 /* ImportClause */:
15853             case 265 /* ImportSpecifier */:
15854             case 263 /* NamespaceImport */:
15855             case 270 /* ExportSpecifier */:
15856             case 266 /* ExportAssignment */:
15857             case 260 /* ImportEqualsDeclaration */:
15858                 return node.parent;
15859             case 157 /* QualifiedName */:
15860                 do {
15861                     node = node.parent;
15862                 } while (node.parent.kind === 157 /* QualifiedName */);
15863                 return getAliasDeclarationFromName(node);
15864         }
15865     }
15866     ts.getAliasDeclarationFromName = getAliasDeclarationFromName;
15867     function isAliasableExpression(e) {
15868         return isEntityNameExpression(e) || ts.isClassExpression(e);
15869     }
15870     ts.isAliasableExpression = isAliasableExpression;
15871     function exportAssignmentIsAlias(node) {
15872         var e = getExportAssignmentExpression(node);
15873         return isAliasableExpression(e);
15874     }
15875     ts.exportAssignmentIsAlias = exportAssignmentIsAlias;
15876     function getExportAssignmentExpression(node) {
15877         return ts.isExportAssignment(node) ? node.expression : node.right;
15878     }
15879     ts.getExportAssignmentExpression = getExportAssignmentExpression;
15880     function getPropertyAssignmentAliasLikeExpression(node) {
15881         return node.kind === 289 /* ShorthandPropertyAssignment */ ? node.name : node.kind === 288 /* PropertyAssignment */ ? node.initializer :
15882             node.parent.right;
15883     }
15884     ts.getPropertyAssignmentAliasLikeExpression = getPropertyAssignmentAliasLikeExpression;
15885     function getEffectiveBaseTypeNode(node) {
15886         var baseType = getClassExtendsHeritageElement(node);
15887         if (baseType && isInJSFile(node)) {
15888             // Prefer an @augments tag because it may have type parameters.
15889             var tag = ts.getJSDocAugmentsTag(node);
15890             if (tag) {
15891                 return tag.class;
15892             }
15893         }
15894         return baseType;
15895     }
15896     ts.getEffectiveBaseTypeNode = getEffectiveBaseTypeNode;
15897     function getClassExtendsHeritageElement(node) {
15898         var heritageClause = getHeritageClause(node.heritageClauses, 93 /* ExtendsKeyword */);
15899         return heritageClause && heritageClause.types.length > 0 ? heritageClause.types[0] : undefined;
15900     }
15901     ts.getClassExtendsHeritageElement = getClassExtendsHeritageElement;
15902     function getEffectiveImplementsTypeNodes(node) {
15903         if (isInJSFile(node)) {
15904             return ts.getJSDocImplementsTags(node).map(function (n) { return n.class; });
15905         }
15906         else {
15907             var heritageClause = getHeritageClause(node.heritageClauses, 116 /* ImplementsKeyword */);
15908             return heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.types;
15909         }
15910     }
15911     ts.getEffectiveImplementsTypeNodes = getEffectiveImplementsTypeNodes;
15912     /** Returns the node in an `extends` or `implements` clause of a class or interface. */
15913     function getAllSuperTypeNodes(node) {
15914         return ts.isInterfaceDeclaration(node) ? getInterfaceBaseTypeNodes(node) || ts.emptyArray :
15915             ts.isClassLike(node) ? ts.concatenate(ts.singleElementArray(getEffectiveBaseTypeNode(node)), getEffectiveImplementsTypeNodes(node)) || ts.emptyArray :
15916                 ts.emptyArray;
15917     }
15918     ts.getAllSuperTypeNodes = getAllSuperTypeNodes;
15919     function getInterfaceBaseTypeNodes(node) {
15920         var heritageClause = getHeritageClause(node.heritageClauses, 93 /* ExtendsKeyword */);
15921         return heritageClause ? heritageClause.types : undefined;
15922     }
15923     ts.getInterfaceBaseTypeNodes = getInterfaceBaseTypeNodes;
15924     function getHeritageClause(clauses, kind) {
15925         if (clauses) {
15926             for (var _i = 0, clauses_1 = clauses; _i < clauses_1.length; _i++) {
15927                 var clause = clauses_1[_i];
15928                 if (clause.token === kind) {
15929                     return clause;
15930                 }
15931             }
15932         }
15933         return undefined;
15934     }
15935     ts.getHeritageClause = getHeritageClause;
15936     function getAncestor(node, kind) {
15937         while (node) {
15938             if (node.kind === kind) {
15939                 return node;
15940             }
15941             node = node.parent;
15942         }
15943         return undefined;
15944     }
15945     ts.getAncestor = getAncestor;
15946     function isKeyword(token) {
15947         return 80 /* FirstKeyword */ <= token && token <= 156 /* LastKeyword */;
15948     }
15949     ts.isKeyword = isKeyword;
15950     function isContextualKeyword(token) {
15951         return 125 /* FirstContextualKeyword */ <= token && token <= 156 /* LastContextualKeyword */;
15952     }
15953     ts.isContextualKeyword = isContextualKeyword;
15954     function isNonContextualKeyword(token) {
15955         return isKeyword(token) && !isContextualKeyword(token);
15956     }
15957     ts.isNonContextualKeyword = isNonContextualKeyword;
15958     function isFutureReservedKeyword(token) {
15959         return 116 /* FirstFutureReservedWord */ <= token && token <= 124 /* LastFutureReservedWord */;
15960     }
15961     ts.isFutureReservedKeyword = isFutureReservedKeyword;
15962     function isStringANonContextualKeyword(name) {
15963         var token = ts.stringToToken(name);
15964         return token !== undefined && isNonContextualKeyword(token);
15965     }
15966     ts.isStringANonContextualKeyword = isStringANonContextualKeyword;
15967     function isStringAKeyword(name) {
15968         var token = ts.stringToToken(name);
15969         return token !== undefined && isKeyword(token);
15970     }
15971     ts.isStringAKeyword = isStringAKeyword;
15972     function isIdentifierANonContextualKeyword(_a) {
15973         var originalKeywordKind = _a.originalKeywordKind;
15974         return !!originalKeywordKind && !isContextualKeyword(originalKeywordKind);
15975     }
15976     ts.isIdentifierANonContextualKeyword = isIdentifierANonContextualKeyword;
15977     function isTrivia(token) {
15978         return 2 /* FirstTriviaToken */ <= token && token <= 7 /* LastTriviaToken */;
15979     }
15980     ts.isTrivia = isTrivia;
15981     var FunctionFlags;
15982     (function (FunctionFlags) {
15983         FunctionFlags[FunctionFlags["Normal"] = 0] = "Normal";
15984         FunctionFlags[FunctionFlags["Generator"] = 1] = "Generator";
15985         FunctionFlags[FunctionFlags["Async"] = 2] = "Async";
15986         FunctionFlags[FunctionFlags["Invalid"] = 4] = "Invalid";
15987         FunctionFlags[FunctionFlags["AsyncGenerator"] = 3] = "AsyncGenerator";
15988     })(FunctionFlags = ts.FunctionFlags || (ts.FunctionFlags = {}));
15989     function getFunctionFlags(node) {
15990         if (!node) {
15991             return 4 /* Invalid */;
15992         }
15993         var flags = 0 /* Normal */;
15994         switch (node.kind) {
15995             case 251 /* FunctionDeclaration */:
15996             case 208 /* FunctionExpression */:
15997             case 165 /* MethodDeclaration */:
15998                 if (node.asteriskToken) {
15999                     flags |= 1 /* Generator */;
16000                 }
16001             // falls through
16002             case 209 /* ArrowFunction */:
16003                 if (hasSyntacticModifier(node, 256 /* Async */)) {
16004                     flags |= 2 /* Async */;
16005                 }
16006                 break;
16007         }
16008         if (!node.body) {
16009             flags |= 4 /* Invalid */;
16010         }
16011         return flags;
16012     }
16013     ts.getFunctionFlags = getFunctionFlags;
16014     function isAsyncFunction(node) {
16015         switch (node.kind) {
16016             case 251 /* FunctionDeclaration */:
16017             case 208 /* FunctionExpression */:
16018             case 209 /* ArrowFunction */:
16019             case 165 /* MethodDeclaration */:
16020                 return node.body !== undefined
16021                     && node.asteriskToken === undefined
16022                     && hasSyntacticModifier(node, 256 /* Async */);
16023         }
16024         return false;
16025     }
16026     ts.isAsyncFunction = isAsyncFunction;
16027     function isStringOrNumericLiteralLike(node) {
16028         return ts.isStringLiteralLike(node) || ts.isNumericLiteral(node);
16029     }
16030     ts.isStringOrNumericLiteralLike = isStringOrNumericLiteralLike;
16031     function isSignedNumericLiteral(node) {
16032         return ts.isPrefixUnaryExpression(node) && (node.operator === 39 /* PlusToken */ || node.operator === 40 /* MinusToken */) && ts.isNumericLiteral(node.operand);
16033     }
16034     ts.isSignedNumericLiteral = isSignedNumericLiteral;
16035     /**
16036      * A declaration has a dynamic name if all of the following are true:
16037      *   1. The declaration has a computed property name.
16038      *   2. The computed name is *not* expressed as a StringLiteral.
16039      *   3. The computed name is *not* expressed as a NumericLiteral.
16040      *   4. The computed name is *not* expressed as a PlusToken or MinusToken
16041      *      immediately followed by a NumericLiteral.
16042      *   5. The computed name is *not* expressed as `Symbol.<name>`, where `<name>`
16043      *      is a property of the Symbol constructor that denotes a built-in
16044      *      Symbol.
16045      */
16046     function hasDynamicName(declaration) {
16047         var name = ts.getNameOfDeclaration(declaration);
16048         return !!name && isDynamicName(name);
16049     }
16050     ts.hasDynamicName = hasDynamicName;
16051     function isDynamicName(name) {
16052         if (!(name.kind === 158 /* ComputedPropertyName */ || name.kind === 202 /* ElementAccessExpression */)) {
16053             return false;
16054         }
16055         var expr = ts.isElementAccessExpression(name) ? skipParentheses(name.argumentExpression) : name.expression;
16056         return !isStringOrNumericLiteralLike(expr) &&
16057             !isSignedNumericLiteral(expr) &&
16058             !isWellKnownSymbolSyntactically(expr);
16059     }
16060     ts.isDynamicName = isDynamicName;
16061     /**
16062      * Checks if the expression is of the form:
16063      *    Symbol.name
16064      * where Symbol is literally the word "Symbol", and name is any identifierName
16065      */
16066     function isWellKnownSymbolSyntactically(node) {
16067         return ts.isPropertyAccessExpression(node) && isESSymbolIdentifier(node.expression);
16068     }
16069     ts.isWellKnownSymbolSyntactically = isWellKnownSymbolSyntactically;
16070     function getPropertyNameForPropertyNameNode(name) {
16071         switch (name.kind) {
16072             case 78 /* Identifier */:
16073             case 79 /* PrivateIdentifier */:
16074                 return name.escapedText;
16075             case 10 /* StringLiteral */:
16076             case 8 /* NumericLiteral */:
16077                 return ts.escapeLeadingUnderscores(name.text);
16078             case 158 /* ComputedPropertyName */:
16079                 var nameExpression = name.expression;
16080                 if (isWellKnownSymbolSyntactically(nameExpression)) {
16081                     return getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
16082                 }
16083                 else if (isStringOrNumericLiteralLike(nameExpression)) {
16084                     return ts.escapeLeadingUnderscores(nameExpression.text);
16085                 }
16086                 else if (isSignedNumericLiteral(nameExpression)) {
16087                     if (nameExpression.operator === 40 /* MinusToken */) {
16088                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
16089                     }
16090                     return nameExpression.operand.text;
16091                 }
16092                 return undefined;
16093             default:
16094                 return ts.Debug.assertNever(name);
16095         }
16096     }
16097     ts.getPropertyNameForPropertyNameNode = getPropertyNameForPropertyNameNode;
16098     function isPropertyNameLiteral(node) {
16099         switch (node.kind) {
16100             case 78 /* Identifier */:
16101             case 10 /* StringLiteral */:
16102             case 14 /* NoSubstitutionTemplateLiteral */:
16103             case 8 /* NumericLiteral */:
16104                 return true;
16105             default:
16106                 return false;
16107         }
16108     }
16109     ts.isPropertyNameLiteral = isPropertyNameLiteral;
16110     function getTextOfIdentifierOrLiteral(node) {
16111         return ts.isIdentifierOrPrivateIdentifier(node) ? ts.idText(node) : node.text;
16112     }
16113     ts.getTextOfIdentifierOrLiteral = getTextOfIdentifierOrLiteral;
16114     function getEscapedTextOfIdentifierOrLiteral(node) {
16115         return ts.isIdentifierOrPrivateIdentifier(node) ? node.escapedText : ts.escapeLeadingUnderscores(node.text);
16116     }
16117     ts.getEscapedTextOfIdentifierOrLiteral = getEscapedTextOfIdentifierOrLiteral;
16118     function getPropertyNameForUniqueESSymbol(symbol) {
16119         return "__@" + ts.getSymbolId(symbol) + "@" + symbol.escapedName;
16120     }
16121     ts.getPropertyNameForUniqueESSymbol = getPropertyNameForUniqueESSymbol;
16122     function getPropertyNameForKnownSymbolName(symbolName) {
16123         return "__@" + symbolName;
16124     }
16125     ts.getPropertyNameForKnownSymbolName = getPropertyNameForKnownSymbolName;
16126     function getSymbolNameForPrivateIdentifier(containingClassSymbol, description) {
16127         return "__#" + ts.getSymbolId(containingClassSymbol) + "@" + description;
16128     }
16129     ts.getSymbolNameForPrivateIdentifier = getSymbolNameForPrivateIdentifier;
16130     function isKnownSymbol(symbol) {
16131         return ts.startsWith(symbol.escapedName, "__@");
16132     }
16133     ts.isKnownSymbol = isKnownSymbol;
16134     /**
16135      * Includes the word "Symbol" with unicode escapes
16136      */
16137     function isESSymbolIdentifier(node) {
16138         return node.kind === 78 /* Identifier */ && node.escapedText === "Symbol";
16139     }
16140     ts.isESSymbolIdentifier = isESSymbolIdentifier;
16141     function isPushOrUnshiftIdentifier(node) {
16142         return node.escapedText === "push" || node.escapedText === "unshift";
16143     }
16144     ts.isPushOrUnshiftIdentifier = isPushOrUnshiftIdentifier;
16145     function isParameterDeclaration(node) {
16146         var root = getRootDeclaration(node);
16147         return root.kind === 160 /* Parameter */;
16148     }
16149     ts.isParameterDeclaration = isParameterDeclaration;
16150     function getRootDeclaration(node) {
16151         while (node.kind === 198 /* BindingElement */) {
16152             node = node.parent.parent;
16153         }
16154         return node;
16155     }
16156     ts.getRootDeclaration = getRootDeclaration;
16157     function nodeStartsNewLexicalEnvironment(node) {
16158         var kind = node.kind;
16159         return kind === 166 /* Constructor */
16160             || kind === 208 /* FunctionExpression */
16161             || kind === 251 /* FunctionDeclaration */
16162             || kind === 209 /* ArrowFunction */
16163             || kind === 165 /* MethodDeclaration */
16164             || kind === 167 /* GetAccessor */
16165             || kind === 168 /* SetAccessor */
16166             || kind === 256 /* ModuleDeclaration */
16167             || kind === 297 /* SourceFile */;
16168     }
16169     ts.nodeStartsNewLexicalEnvironment = nodeStartsNewLexicalEnvironment;
16170     function nodeIsSynthesized(range) {
16171         return positionIsSynthesized(range.pos)
16172             || positionIsSynthesized(range.end);
16173     }
16174     ts.nodeIsSynthesized = nodeIsSynthesized;
16175     function getOriginalSourceFile(sourceFile) {
16176         return ts.getParseTreeNode(sourceFile, ts.isSourceFile) || sourceFile;
16177     }
16178     ts.getOriginalSourceFile = getOriginalSourceFile;
16179     var Associativity;
16180     (function (Associativity) {
16181         Associativity[Associativity["Left"] = 0] = "Left";
16182         Associativity[Associativity["Right"] = 1] = "Right";
16183     })(Associativity = ts.Associativity || (ts.Associativity = {}));
16184     function getExpressionAssociativity(expression) {
16185         var operator = getOperator(expression);
16186         var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined;
16187         return getOperatorAssociativity(expression.kind, operator, hasArguments);
16188     }
16189     ts.getExpressionAssociativity = getExpressionAssociativity;
16190     function getOperatorAssociativity(kind, operator, hasArguments) {
16191         switch (kind) {
16192             case 204 /* NewExpression */:
16193                 return hasArguments ? 0 /* Left */ : 1 /* Right */;
16194             case 214 /* PrefixUnaryExpression */:
16195             case 211 /* TypeOfExpression */:
16196             case 212 /* VoidExpression */:
16197             case 210 /* DeleteExpression */:
16198             case 213 /* AwaitExpression */:
16199             case 217 /* ConditionalExpression */:
16200             case 219 /* YieldExpression */:
16201                 return 1 /* Right */;
16202             case 216 /* BinaryExpression */:
16203                 switch (operator) {
16204                     case 42 /* AsteriskAsteriskToken */:
16205                     case 62 /* EqualsToken */:
16206                     case 63 /* PlusEqualsToken */:
16207                     case 64 /* MinusEqualsToken */:
16208                     case 66 /* AsteriskAsteriskEqualsToken */:
16209                     case 65 /* AsteriskEqualsToken */:
16210                     case 67 /* SlashEqualsToken */:
16211                     case 68 /* PercentEqualsToken */:
16212                     case 69 /* LessThanLessThanEqualsToken */:
16213                     case 70 /* GreaterThanGreaterThanEqualsToken */:
16214                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
16215                     case 72 /* AmpersandEqualsToken */:
16216                     case 77 /* CaretEqualsToken */:
16217                     case 73 /* BarEqualsToken */:
16218                     case 74 /* BarBarEqualsToken */:
16219                     case 75 /* AmpersandAmpersandEqualsToken */:
16220                     case 76 /* QuestionQuestionEqualsToken */:
16221                         return 1 /* Right */;
16222                 }
16223         }
16224         return 0 /* Left */;
16225     }
16226     ts.getOperatorAssociativity = getOperatorAssociativity;
16227     function getExpressionPrecedence(expression) {
16228         var operator = getOperator(expression);
16229         var hasArguments = expression.kind === 204 /* NewExpression */ && expression.arguments !== undefined;
16230         return getOperatorPrecedence(expression.kind, operator, hasArguments);
16231     }
16232     ts.getExpressionPrecedence = getExpressionPrecedence;
16233     function getOperator(expression) {
16234         if (expression.kind === 216 /* BinaryExpression */) {
16235             return expression.operatorToken.kind;
16236         }
16237         else if (expression.kind === 214 /* PrefixUnaryExpression */ || expression.kind === 215 /* PostfixUnaryExpression */) {
16238             return expression.operator;
16239         }
16240         else {
16241             return expression.kind;
16242         }
16243     }
16244     ts.getOperator = getOperator;
16245     var OperatorPrecedence;
16246     (function (OperatorPrecedence) {
16247         // Expression:
16248         //     AssignmentExpression
16249         //     Expression `,` AssignmentExpression
16250         OperatorPrecedence[OperatorPrecedence["Comma"] = 0] = "Comma";
16251         // NOTE: `Spread` is higher than `Comma` due to how it is parsed in |ElementList|
16252         // SpreadElement:
16253         //     `...` AssignmentExpression
16254         OperatorPrecedence[OperatorPrecedence["Spread"] = 1] = "Spread";
16255         // AssignmentExpression:
16256         //     ConditionalExpression
16257         //     YieldExpression
16258         //     ArrowFunction
16259         //     AsyncArrowFunction
16260         //     LeftHandSideExpression `=` AssignmentExpression
16261         //     LeftHandSideExpression AssignmentOperator AssignmentExpression
16262         //
16263         // NOTE: AssignmentExpression is broken down into several precedences due to the requirements
16264         //       of the parenthesizer rules.
16265         // AssignmentExpression: YieldExpression
16266         // YieldExpression:
16267         //     `yield`
16268         //     `yield` AssignmentExpression
16269         //     `yield` `*` AssignmentExpression
16270         OperatorPrecedence[OperatorPrecedence["Yield"] = 2] = "Yield";
16271         // AssignmentExpression: LeftHandSideExpression `=` AssignmentExpression
16272         // AssignmentExpression: LeftHandSideExpression AssignmentOperator AssignmentExpression
16273         // AssignmentOperator: one of
16274         //     `*=` `/=` `%=` `+=` `-=` `<<=` `>>=` `>>>=` `&=` `^=` `|=` `**=`
16275         OperatorPrecedence[OperatorPrecedence["Assignment"] = 3] = "Assignment";
16276         // NOTE: `Conditional` is considered higher than `Assignment` here, but in reality they have
16277         //       the same precedence.
16278         // AssignmentExpression: ConditionalExpression
16279         // ConditionalExpression:
16280         //     ShortCircuitExpression
16281         //     ShortCircuitExpression `?` AssignmentExpression `:` AssignmentExpression
16282         // ShortCircuitExpression:
16283         //     LogicalORExpression
16284         //     CoalesceExpression
16285         OperatorPrecedence[OperatorPrecedence["Conditional"] = 4] = "Conditional";
16286         // CoalesceExpression:
16287         //     CoalesceExpressionHead `??` BitwiseORExpression
16288         // CoalesceExpressionHead:
16289         //     CoalesceExpression
16290         //     BitwiseORExpression
16291         OperatorPrecedence[OperatorPrecedence["Coalesce"] = 4] = "Coalesce";
16292         // LogicalORExpression:
16293         //     LogicalANDExpression
16294         //     LogicalORExpression `||` LogicalANDExpression
16295         OperatorPrecedence[OperatorPrecedence["LogicalOR"] = 5] = "LogicalOR";
16296         // LogicalANDExpression:
16297         //     BitwiseORExpression
16298         //     LogicalANDExprerssion `&&` BitwiseORExpression
16299         OperatorPrecedence[OperatorPrecedence["LogicalAND"] = 6] = "LogicalAND";
16300         // BitwiseORExpression:
16301         //     BitwiseXORExpression
16302         //     BitwiseORExpression `^` BitwiseXORExpression
16303         OperatorPrecedence[OperatorPrecedence["BitwiseOR"] = 7] = "BitwiseOR";
16304         // BitwiseXORExpression:
16305         //     BitwiseANDExpression
16306         //     BitwiseXORExpression `^` BitwiseANDExpression
16307         OperatorPrecedence[OperatorPrecedence["BitwiseXOR"] = 8] = "BitwiseXOR";
16308         // BitwiseANDExpression:
16309         //     EqualityExpression
16310         //     BitwiseANDExpression `^` EqualityExpression
16311         OperatorPrecedence[OperatorPrecedence["BitwiseAND"] = 9] = "BitwiseAND";
16312         // EqualityExpression:
16313         //     RelationalExpression
16314         //     EqualityExpression `==` RelationalExpression
16315         //     EqualityExpression `!=` RelationalExpression
16316         //     EqualityExpression `===` RelationalExpression
16317         //     EqualityExpression `!==` RelationalExpression
16318         OperatorPrecedence[OperatorPrecedence["Equality"] = 10] = "Equality";
16319         // RelationalExpression:
16320         //     ShiftExpression
16321         //     RelationalExpression `<` ShiftExpression
16322         //     RelationalExpression `>` ShiftExpression
16323         //     RelationalExpression `<=` ShiftExpression
16324         //     RelationalExpression `>=` ShiftExpression
16325         //     RelationalExpression `instanceof` ShiftExpression
16326         //     RelationalExpression `in` ShiftExpression
16327         //     [+TypeScript] RelationalExpression `as` Type
16328         OperatorPrecedence[OperatorPrecedence["Relational"] = 11] = "Relational";
16329         // ShiftExpression:
16330         //     AdditiveExpression
16331         //     ShiftExpression `<<` AdditiveExpression
16332         //     ShiftExpression `>>` AdditiveExpression
16333         //     ShiftExpression `>>>` AdditiveExpression
16334         OperatorPrecedence[OperatorPrecedence["Shift"] = 12] = "Shift";
16335         // AdditiveExpression:
16336         //     MultiplicativeExpression
16337         //     AdditiveExpression `+` MultiplicativeExpression
16338         //     AdditiveExpression `-` MultiplicativeExpression
16339         OperatorPrecedence[OperatorPrecedence["Additive"] = 13] = "Additive";
16340         // MultiplicativeExpression:
16341         //     ExponentiationExpression
16342         //     MultiplicativeExpression MultiplicativeOperator ExponentiationExpression
16343         // MultiplicativeOperator: one of `*`, `/`, `%`
16344         OperatorPrecedence[OperatorPrecedence["Multiplicative"] = 14] = "Multiplicative";
16345         // ExponentiationExpression:
16346         //     UnaryExpression
16347         //     UpdateExpression `**` ExponentiationExpression
16348         OperatorPrecedence[OperatorPrecedence["Exponentiation"] = 15] = "Exponentiation";
16349         // UnaryExpression:
16350         //     UpdateExpression
16351         //     `delete` UnaryExpression
16352         //     `void` UnaryExpression
16353         //     `typeof` UnaryExpression
16354         //     `+` UnaryExpression
16355         //     `-` UnaryExpression
16356         //     `~` UnaryExpression
16357         //     `!` UnaryExpression
16358         //     AwaitExpression
16359         // UpdateExpression:            // TODO: Do we need to investigate the precedence here?
16360         //     `++` UnaryExpression
16361         //     `--` UnaryExpression
16362         OperatorPrecedence[OperatorPrecedence["Unary"] = 16] = "Unary";
16363         // UpdateExpression:
16364         //     LeftHandSideExpression
16365         //     LeftHandSideExpression `++`
16366         //     LeftHandSideExpression `--`
16367         OperatorPrecedence[OperatorPrecedence["Update"] = 17] = "Update";
16368         // LeftHandSideExpression:
16369         //     NewExpression
16370         //     CallExpression
16371         // NewExpression:
16372         //     MemberExpression
16373         //     `new` NewExpression
16374         OperatorPrecedence[OperatorPrecedence["LeftHandSide"] = 18] = "LeftHandSide";
16375         // CallExpression:
16376         //     CoverCallExpressionAndAsyncArrowHead
16377         //     SuperCall
16378         //     ImportCall
16379         //     CallExpression Arguments
16380         //     CallExpression `[` Expression `]`
16381         //     CallExpression `.` IdentifierName
16382         //     CallExpression TemplateLiteral
16383         // MemberExpression:
16384         //     PrimaryExpression
16385         //     MemberExpression `[` Expression `]`
16386         //     MemberExpression `.` IdentifierName
16387         //     MemberExpression TemplateLiteral
16388         //     SuperProperty
16389         //     MetaProperty
16390         //     `new` MemberExpression Arguments
16391         OperatorPrecedence[OperatorPrecedence["Member"] = 19] = "Member";
16392         // TODO: JSXElement?
16393         // PrimaryExpression:
16394         //     `this`
16395         //     IdentifierReference
16396         //     Literal
16397         //     ArrayLiteral
16398         //     ObjectLiteral
16399         //     FunctionExpression
16400         //     ClassExpression
16401         //     GeneratorExpression
16402         //     AsyncFunctionExpression
16403         //     AsyncGeneratorExpression
16404         //     RegularExpressionLiteral
16405         //     TemplateLiteral
16406         //     CoverParenthesizedExpressionAndArrowParameterList
16407         OperatorPrecedence[OperatorPrecedence["Primary"] = 20] = "Primary";
16408         OperatorPrecedence[OperatorPrecedence["Highest"] = 20] = "Highest";
16409         OperatorPrecedence[OperatorPrecedence["Lowest"] = 0] = "Lowest";
16410         // -1 is lower than all other precedences. Returning it will cause binary expression
16411         // parsing to stop.
16412         OperatorPrecedence[OperatorPrecedence["Invalid"] = -1] = "Invalid";
16413     })(OperatorPrecedence = ts.OperatorPrecedence || (ts.OperatorPrecedence = {}));
16414     function getOperatorPrecedence(nodeKind, operatorKind, hasArguments) {
16415         switch (nodeKind) {
16416             case 337 /* CommaListExpression */:
16417                 return 0 /* Comma */;
16418             case 220 /* SpreadElement */:
16419                 return 1 /* Spread */;
16420             case 219 /* YieldExpression */:
16421                 return 2 /* Yield */;
16422             case 217 /* ConditionalExpression */:
16423                 return 4 /* Conditional */;
16424             case 216 /* BinaryExpression */:
16425                 switch (operatorKind) {
16426                     case 27 /* CommaToken */:
16427                         return 0 /* Comma */;
16428                     case 62 /* EqualsToken */:
16429                     case 63 /* PlusEqualsToken */:
16430                     case 64 /* MinusEqualsToken */:
16431                     case 66 /* AsteriskAsteriskEqualsToken */:
16432                     case 65 /* AsteriskEqualsToken */:
16433                     case 67 /* SlashEqualsToken */:
16434                     case 68 /* PercentEqualsToken */:
16435                     case 69 /* LessThanLessThanEqualsToken */:
16436                     case 70 /* GreaterThanGreaterThanEqualsToken */:
16437                     case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
16438                     case 72 /* AmpersandEqualsToken */:
16439                     case 77 /* CaretEqualsToken */:
16440                     case 73 /* BarEqualsToken */:
16441                     case 74 /* BarBarEqualsToken */:
16442                     case 75 /* AmpersandAmpersandEqualsToken */:
16443                     case 76 /* QuestionQuestionEqualsToken */:
16444                         return 3 /* Assignment */;
16445                     default:
16446                         return getBinaryOperatorPrecedence(operatorKind);
16447                 }
16448             // TODO: Should prefix `++` and `--` be moved to the `Update` precedence?
16449             // TODO: We are missing `TypeAssertionExpression`
16450             case 214 /* PrefixUnaryExpression */:
16451             case 211 /* TypeOfExpression */:
16452             case 212 /* VoidExpression */:
16453             case 210 /* DeleteExpression */:
16454             case 213 /* AwaitExpression */:
16455                 return 16 /* Unary */;
16456             case 215 /* PostfixUnaryExpression */:
16457                 return 17 /* Update */;
16458             case 203 /* CallExpression */:
16459                 return 18 /* LeftHandSide */;
16460             case 204 /* NewExpression */:
16461                 return hasArguments ? 19 /* Member */ : 18 /* LeftHandSide */;
16462             case 205 /* TaggedTemplateExpression */:
16463             case 201 /* PropertyAccessExpression */:
16464             case 202 /* ElementAccessExpression */:
16465                 return 19 /* Member */;
16466             case 107 /* ThisKeyword */:
16467             case 105 /* SuperKeyword */:
16468             case 78 /* Identifier */:
16469             case 103 /* NullKeyword */:
16470             case 109 /* TrueKeyword */:
16471             case 94 /* FalseKeyword */:
16472             case 8 /* NumericLiteral */:
16473             case 9 /* BigIntLiteral */:
16474             case 10 /* StringLiteral */:
16475             case 199 /* ArrayLiteralExpression */:
16476             case 200 /* ObjectLiteralExpression */:
16477             case 208 /* FunctionExpression */:
16478             case 209 /* ArrowFunction */:
16479             case 221 /* ClassExpression */:
16480             case 13 /* RegularExpressionLiteral */:
16481             case 14 /* NoSubstitutionTemplateLiteral */:
16482             case 218 /* TemplateExpression */:
16483             case 207 /* ParenthesizedExpression */:
16484             case 222 /* OmittedExpression */:
16485             case 273 /* JsxElement */:
16486             case 274 /* JsxSelfClosingElement */:
16487             case 277 /* JsxFragment */:
16488                 return 20 /* Primary */;
16489             default:
16490                 return -1 /* Invalid */;
16491         }
16492     }
16493     ts.getOperatorPrecedence = getOperatorPrecedence;
16494     function getBinaryOperatorPrecedence(kind) {
16495         switch (kind) {
16496             case 60 /* QuestionQuestionToken */:
16497                 return 4 /* Coalesce */;
16498             case 56 /* BarBarToken */:
16499                 return 5 /* LogicalOR */;
16500             case 55 /* AmpersandAmpersandToken */:
16501                 return 6 /* LogicalAND */;
16502             case 51 /* BarToken */:
16503                 return 7 /* BitwiseOR */;
16504             case 52 /* CaretToken */:
16505                 return 8 /* BitwiseXOR */;
16506             case 50 /* AmpersandToken */:
16507                 return 9 /* BitwiseAND */;
16508             case 34 /* EqualsEqualsToken */:
16509             case 35 /* ExclamationEqualsToken */:
16510             case 36 /* EqualsEqualsEqualsToken */:
16511             case 37 /* ExclamationEqualsEqualsToken */:
16512                 return 10 /* Equality */;
16513             case 29 /* LessThanToken */:
16514             case 31 /* GreaterThanToken */:
16515             case 32 /* LessThanEqualsToken */:
16516             case 33 /* GreaterThanEqualsToken */:
16517             case 101 /* InstanceOfKeyword */:
16518             case 100 /* InKeyword */:
16519             case 126 /* AsKeyword */:
16520                 return 11 /* Relational */;
16521             case 47 /* LessThanLessThanToken */:
16522             case 48 /* GreaterThanGreaterThanToken */:
16523             case 49 /* GreaterThanGreaterThanGreaterThanToken */:
16524                 return 12 /* Shift */;
16525             case 39 /* PlusToken */:
16526             case 40 /* MinusToken */:
16527                 return 13 /* Additive */;
16528             case 41 /* AsteriskToken */:
16529             case 43 /* SlashToken */:
16530             case 44 /* PercentToken */:
16531                 return 14 /* Multiplicative */;
16532             case 42 /* AsteriskAsteriskToken */:
16533                 return 15 /* Exponentiation */;
16534         }
16535         // -1 is lower than all other precedences.  Returning it will cause binary expression
16536         // parsing to stop.
16537         return -1;
16538     }
16539     ts.getBinaryOperatorPrecedence = getBinaryOperatorPrecedence;
16540     function getSemanticJsxChildren(children) {
16541         return ts.filter(children, function (i) {
16542             switch (i.kind) {
16543                 case 283 /* JsxExpression */:
16544                     return !!i.expression;
16545                 case 11 /* JsxText */:
16546                     return !i.containsOnlyTriviaWhiteSpaces;
16547                 default:
16548                     return true;
16549             }
16550         });
16551     }
16552     ts.getSemanticJsxChildren = getSemanticJsxChildren;
16553     function createDiagnosticCollection() {
16554         var nonFileDiagnostics = []; // See GH#19873
16555         var filesWithDiagnostics = [];
16556         var fileDiagnostics = new ts.Map();
16557         var hasReadNonFileDiagnostics = false;
16558         return {
16559             add: add,
16560             lookup: lookup,
16561             getGlobalDiagnostics: getGlobalDiagnostics,
16562             getDiagnostics: getDiagnostics,
16563             reattachFileDiagnostics: reattachFileDiagnostics
16564         };
16565         function reattachFileDiagnostics(newFile) {
16566             ts.forEach(fileDiagnostics.get(newFile.fileName), function (diagnostic) { return diagnostic.file = newFile; });
16567         }
16568         function lookup(diagnostic) {
16569             var diagnostics;
16570             if (diagnostic.file) {
16571                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16572             }
16573             else {
16574                 diagnostics = nonFileDiagnostics;
16575             }
16576             if (!diagnostics) {
16577                 return undefined;
16578             }
16579             var result = ts.binarySearch(diagnostics, diagnostic, ts.identity, compareDiagnosticsSkipRelatedInformation);
16580             if (result >= 0) {
16581                 return diagnostics[result];
16582             }
16583             return undefined;
16584         }
16585         function add(diagnostic) {
16586             var diagnostics;
16587             if (diagnostic.file) {
16588                 diagnostics = fileDiagnostics.get(diagnostic.file.fileName);
16589                 if (!diagnostics) {
16590                     diagnostics = []; // See GH#19873
16591                     fileDiagnostics.set(diagnostic.file.fileName, diagnostics);
16592                     ts.insertSorted(filesWithDiagnostics, diagnostic.file.fileName, ts.compareStringsCaseSensitive);
16593                 }
16594             }
16595             else {
16596                 // If we've already read the non-file diagnostics, do not modify the existing array.
16597                 if (hasReadNonFileDiagnostics) {
16598                     hasReadNonFileDiagnostics = false;
16599                     nonFileDiagnostics = nonFileDiagnostics.slice();
16600                 }
16601                 diagnostics = nonFileDiagnostics;
16602             }
16603             ts.insertSorted(diagnostics, diagnostic, compareDiagnostics);
16604         }
16605         function getGlobalDiagnostics() {
16606             hasReadNonFileDiagnostics = true;
16607             return nonFileDiagnostics;
16608         }
16609         function getDiagnostics(fileName) {
16610             if (fileName) {
16611                 return fileDiagnostics.get(fileName) || [];
16612             }
16613             var fileDiags = ts.flatMapToMutable(filesWithDiagnostics, function (f) { return fileDiagnostics.get(f); });
16614             if (!nonFileDiagnostics.length) {
16615                 return fileDiags;
16616             }
16617             fileDiags.unshift.apply(fileDiags, nonFileDiagnostics);
16618             return fileDiags;
16619         }
16620     }
16621     ts.createDiagnosticCollection = createDiagnosticCollection;
16622     var templateSubstitutionRegExp = /\$\{/g;
16623     function escapeTemplateSubstitution(str) {
16624         return str.replace(templateSubstitutionRegExp, "\\${");
16625     }
16626     /** @internal */
16627     function hasInvalidEscape(template) {
16628         return template && !!(ts.isNoSubstitutionTemplateLiteral(template)
16629             ? template.templateFlags
16630             : (template.head.templateFlags || ts.some(template.templateSpans, function (span) { return !!span.literal.templateFlags; })));
16631     }
16632     ts.hasInvalidEscape = hasInvalidEscape;
16633     // This consists of the first 19 unprintable ASCII characters, canonical escapes, lineSeparator,
16634     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16635     // the language service. These characters should be escaped when printing, and if any characters are added,
16636     // the map below must be updated. Note that this regexp *does not* include the 'delete' character.
16637     // There is no reason for this other than that JSON.stringify does not handle it either.
16638     var doubleQuoteEscapedCharsRegExp = /[\\\"\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16639     var singleQuoteEscapedCharsRegExp = /[\\\'\u0000-\u001f\t\v\f\b\r\n\u2028\u2029\u0085]/g;
16640     // Template strings should be preserved as much as possible
16641     var backtickQuoteEscapedCharsRegExp = /[\\`]/g;
16642     var escapedCharsMap = new ts.Map(ts.getEntries({
16643         "\t": "\\t",
16644         "\v": "\\v",
16645         "\f": "\\f",
16646         "\b": "\\b",
16647         "\r": "\\r",
16648         "\n": "\\n",
16649         "\\": "\\\\",
16650         "\"": "\\\"",
16651         "\'": "\\\'",
16652         "\`": "\\\`",
16653         "\u2028": "\\u2028",
16654         "\u2029": "\\u2029",
16655         "\u0085": "\\u0085" // nextLine
16656     }));
16657     function encodeUtf16EscapeSequence(charCode) {
16658         var hexCharCode = charCode.toString(16).toUpperCase();
16659         var paddedHexCode = ("0000" + hexCharCode).slice(-4);
16660         return "\\u" + paddedHexCode;
16661     }
16662     function getReplacement(c, offset, input) {
16663         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16664             var lookAhead = input.charCodeAt(offset + c.length);
16665             if (lookAhead >= 48 /* _0 */ && lookAhead <= 57 /* _9 */) {
16666                 // 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)
16667                 return "\\x00";
16668             }
16669             // Otherwise, keep printing a literal \0 for the null character
16670             return "\\0";
16671         }
16672         return escapedCharsMap.get(c) || encodeUtf16EscapeSequence(c.charCodeAt(0));
16673     }
16674     /**
16675      * Based heavily on the abstract 'Quote'/'QuoteJSONString' operation from ECMA-262 (24.3.2.2),
16676      * but augmented for a few select characters (e.g. lineSeparator, paragraphSeparator, nextLine)
16677      * Note that this doesn't actually wrap the input in double quotes.
16678      */
16679     function escapeString(s, quoteChar) {
16680         var escapedCharsRegExp = quoteChar === 96 /* backtick */ ? backtickQuoteEscapedCharsRegExp :
16681             quoteChar === 39 /* singleQuote */ ? singleQuoteEscapedCharsRegExp :
16682                 doubleQuoteEscapedCharsRegExp;
16683         return s.replace(escapedCharsRegExp, getReplacement);
16684     }
16685     ts.escapeString = escapeString;
16686     var nonAsciiCharacters = /[^\u0000-\u007F]/g;
16687     function escapeNonAsciiString(s, quoteChar) {
16688         s = escapeString(s, quoteChar);
16689         // Replace non-ASCII characters with '\uNNNN' escapes if any exist.
16690         // Otherwise just return the original string.
16691         return nonAsciiCharacters.test(s) ?
16692             s.replace(nonAsciiCharacters, function (c) { return encodeUtf16EscapeSequence(c.charCodeAt(0)); }) :
16693             s;
16694     }
16695     ts.escapeNonAsciiString = escapeNonAsciiString;
16696     // This consists of the first 19 unprintable ASCII characters, JSX canonical escapes, lineSeparator,
16697     // paragraphSeparator, and nextLine. The latter three are just desirable to suppress new lines in
16698     // the language service. These characters should be escaped when printing, and if any characters are added,
16699     // the map below must be updated.
16700     var jsxDoubleQuoteEscapedCharsRegExp = /[\"\u0000-\u001f\u2028\u2029\u0085]/g;
16701     var jsxSingleQuoteEscapedCharsRegExp = /[\'\u0000-\u001f\u2028\u2029\u0085]/g;
16702     var jsxEscapedCharsMap = new ts.Map(ts.getEntries({
16703         "\"": "&quot;",
16704         "\'": "&apos;"
16705     }));
16706     function encodeJsxCharacterEntity(charCode) {
16707         var hexCharCode = charCode.toString(16).toUpperCase();
16708         return "&#x" + hexCharCode + ";";
16709     }
16710     function getJsxAttributeStringReplacement(c) {
16711         if (c.charCodeAt(0) === 0 /* nullCharacter */) {
16712             return "&#0;";
16713         }
16714         return jsxEscapedCharsMap.get(c) || encodeJsxCharacterEntity(c.charCodeAt(0));
16715     }
16716     function escapeJsxAttributeString(s, quoteChar) {
16717         var escapedCharsRegExp = quoteChar === 39 /* singleQuote */ ? jsxSingleQuoteEscapedCharsRegExp :
16718             jsxDoubleQuoteEscapedCharsRegExp;
16719         return s.replace(escapedCharsRegExp, getJsxAttributeStringReplacement);
16720     }
16721     ts.escapeJsxAttributeString = escapeJsxAttributeString;
16722     /**
16723      * Strip off existed surrounding single quotes, double quotes, or backticks from a given string
16724      *
16725      * @return non-quoted string
16726      */
16727     function stripQuotes(name) {
16728         var length = name.length;
16729         if (length >= 2 && name.charCodeAt(0) === name.charCodeAt(length - 1) && isQuoteOrBacktick(name.charCodeAt(0))) {
16730             return name.substring(1, length - 1);
16731         }
16732         return name;
16733     }
16734     ts.stripQuotes = stripQuotes;
16735     function isQuoteOrBacktick(charCode) {
16736         return charCode === 39 /* singleQuote */ ||
16737             charCode === 34 /* doubleQuote */ ||
16738             charCode === 96 /* backtick */;
16739     }
16740     function isIntrinsicJsxName(name) {
16741         var ch = name.charCodeAt(0);
16742         return (ch >= 97 /* a */ && ch <= 122 /* z */) || ts.stringContains(name, "-");
16743     }
16744     ts.isIntrinsicJsxName = isIntrinsicJsxName;
16745     var indentStrings = ["", "    "];
16746     function getIndentString(level) {
16747         // prepopulate cache
16748         var singleLevel = indentStrings[1];
16749         for (var current = indentStrings.length; current <= level; current++) {
16750             indentStrings.push(indentStrings[current - 1] + singleLevel);
16751         }
16752         return indentStrings[level];
16753     }
16754     ts.getIndentString = getIndentString;
16755     function getIndentSize() {
16756         return indentStrings[1].length;
16757     }
16758     ts.getIndentSize = getIndentSize;
16759     function createTextWriter(newLine) {
16760         var output;
16761         var indent;
16762         var lineStart;
16763         var lineCount;
16764         var linePos;
16765         var hasTrailingComment = false;
16766         function updateLineCountAndPosFor(s) {
16767             var lineStartsOfS = ts.computeLineStarts(s);
16768             if (lineStartsOfS.length > 1) {
16769                 lineCount = lineCount + lineStartsOfS.length - 1;
16770                 linePos = output.length - s.length + ts.last(lineStartsOfS);
16771                 lineStart = (linePos - output.length) === 0;
16772             }
16773             else {
16774                 lineStart = false;
16775             }
16776         }
16777         function writeText(s) {
16778             if (s && s.length) {
16779                 if (lineStart) {
16780                     s = getIndentString(indent) + s;
16781                     lineStart = false;
16782                 }
16783                 output += s;
16784                 updateLineCountAndPosFor(s);
16785             }
16786         }
16787         function write(s) {
16788             if (s)
16789                 hasTrailingComment = false;
16790             writeText(s);
16791         }
16792         function writeComment(s) {
16793             if (s)
16794                 hasTrailingComment = true;
16795             writeText(s);
16796         }
16797         function reset() {
16798             output = "";
16799             indent = 0;
16800             lineStart = true;
16801             lineCount = 0;
16802             linePos = 0;
16803             hasTrailingComment = false;
16804         }
16805         function rawWrite(s) {
16806             if (s !== undefined) {
16807                 output += s;
16808                 updateLineCountAndPosFor(s);
16809                 hasTrailingComment = false;
16810             }
16811         }
16812         function writeLiteral(s) {
16813             if (s && s.length) {
16814                 write(s);
16815             }
16816         }
16817         function writeLine(force) {
16818             if (!lineStart || force) {
16819                 output += newLine;
16820                 lineCount++;
16821                 linePos = output.length;
16822                 lineStart = true;
16823                 hasTrailingComment = false;
16824             }
16825         }
16826         function getTextPosWithWriteLine() {
16827             return lineStart ? output.length : (output.length + newLine.length);
16828         }
16829         reset();
16830         return {
16831             write: write,
16832             rawWrite: rawWrite,
16833             writeLiteral: writeLiteral,
16834             writeLine: writeLine,
16835             increaseIndent: function () { indent++; },
16836             decreaseIndent: function () { indent--; },
16837             getIndent: function () { return indent; },
16838             getTextPos: function () { return output.length; },
16839             getLine: function () { return lineCount; },
16840             getColumn: function () { return lineStart ? indent * getIndentSize() : output.length - linePos; },
16841             getText: function () { return output; },
16842             isAtStartOfLine: function () { return lineStart; },
16843             hasTrailingComment: function () { return hasTrailingComment; },
16844             hasTrailingWhitespace: function () { return !!output.length && ts.isWhiteSpaceLike(output.charCodeAt(output.length - 1)); },
16845             clear: reset,
16846             reportInaccessibleThisError: ts.noop,
16847             reportPrivateInBaseOfClassExpression: ts.noop,
16848             reportInaccessibleUniqueSymbolError: ts.noop,
16849             trackSymbol: ts.noop,
16850             writeKeyword: write,
16851             writeOperator: write,
16852             writeParameter: write,
16853             writeProperty: write,
16854             writePunctuation: write,
16855             writeSpace: write,
16856             writeStringLiteral: write,
16857             writeSymbol: function (s, _) { return write(s); },
16858             writeTrailingSemicolon: write,
16859             writeComment: writeComment,
16860             getTextPosWithWriteLine: getTextPosWithWriteLine
16861         };
16862     }
16863     ts.createTextWriter = createTextWriter;
16864     function getTrailingSemicolonDeferringWriter(writer) {
16865         var pendingTrailingSemicolon = false;
16866         function commitPendingTrailingSemicolon() {
16867             if (pendingTrailingSemicolon) {
16868                 writer.writeTrailingSemicolon(";");
16869                 pendingTrailingSemicolon = false;
16870             }
16871         }
16872         return __assign(__assign({}, writer), { writeTrailingSemicolon: function () {
16873                 pendingTrailingSemicolon = true;
16874             },
16875             writeLiteral: function (s) {
16876                 commitPendingTrailingSemicolon();
16877                 writer.writeLiteral(s);
16878             },
16879             writeStringLiteral: function (s) {
16880                 commitPendingTrailingSemicolon();
16881                 writer.writeStringLiteral(s);
16882             },
16883             writeSymbol: function (s, sym) {
16884                 commitPendingTrailingSemicolon();
16885                 writer.writeSymbol(s, sym);
16886             },
16887             writePunctuation: function (s) {
16888                 commitPendingTrailingSemicolon();
16889                 writer.writePunctuation(s);
16890             },
16891             writeKeyword: function (s) {
16892                 commitPendingTrailingSemicolon();
16893                 writer.writeKeyword(s);
16894             },
16895             writeOperator: function (s) {
16896                 commitPendingTrailingSemicolon();
16897                 writer.writeOperator(s);
16898             },
16899             writeParameter: function (s) {
16900                 commitPendingTrailingSemicolon();
16901                 writer.writeParameter(s);
16902             },
16903             writeSpace: function (s) {
16904                 commitPendingTrailingSemicolon();
16905                 writer.writeSpace(s);
16906             },
16907             writeProperty: function (s) {
16908                 commitPendingTrailingSemicolon();
16909                 writer.writeProperty(s);
16910             },
16911             writeComment: function (s) {
16912                 commitPendingTrailingSemicolon();
16913                 writer.writeComment(s);
16914             },
16915             writeLine: function () {
16916                 commitPendingTrailingSemicolon();
16917                 writer.writeLine();
16918             },
16919             increaseIndent: function () {
16920                 commitPendingTrailingSemicolon();
16921                 writer.increaseIndent();
16922             },
16923             decreaseIndent: function () {
16924                 commitPendingTrailingSemicolon();
16925                 writer.decreaseIndent();
16926             } });
16927     }
16928     ts.getTrailingSemicolonDeferringWriter = getTrailingSemicolonDeferringWriter;
16929     function hostUsesCaseSensitiveFileNames(host) {
16930         return host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : false;
16931     }
16932     ts.hostUsesCaseSensitiveFileNames = hostUsesCaseSensitiveFileNames;
16933     function hostGetCanonicalFileName(host) {
16934         return ts.createGetCanonicalFileName(hostUsesCaseSensitiveFileNames(host));
16935     }
16936     ts.hostGetCanonicalFileName = hostGetCanonicalFileName;
16937     function getResolvedExternalModuleName(host, file, referenceFile) {
16938         return file.moduleName || getExternalModuleNameFromPath(host, file.fileName, referenceFile && referenceFile.fileName);
16939     }
16940     ts.getResolvedExternalModuleName = getResolvedExternalModuleName;
16941     function getExternalModuleNameFromDeclaration(host, resolver, declaration) {
16942         var file = resolver.getExternalModuleFileFromDeclaration(declaration);
16943         if (!file || file.isDeclarationFile) {
16944             return undefined;
16945         }
16946         return getResolvedExternalModuleName(host, file);
16947     }
16948     ts.getExternalModuleNameFromDeclaration = getExternalModuleNameFromDeclaration;
16949     /**
16950      * Resolves a local path to a path which is absolute to the base of the emit
16951      */
16952     function getExternalModuleNameFromPath(host, fileName, referencePath) {
16953         var getCanonicalFileName = function (f) { return host.getCanonicalFileName(f); };
16954         var dir = ts.toPath(referencePath ? ts.getDirectoryPath(referencePath) : host.getCommonSourceDirectory(), host.getCurrentDirectory(), getCanonicalFileName);
16955         var filePath = ts.getNormalizedAbsolutePath(fileName, host.getCurrentDirectory());
16956         var relativePath = ts.getRelativePathToDirectoryOrUrl(dir, filePath, dir, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
16957         var extensionless = removeFileExtension(relativePath);
16958         return referencePath ? ts.ensurePathIsNonModuleName(extensionless) : extensionless;
16959     }
16960     ts.getExternalModuleNameFromPath = getExternalModuleNameFromPath;
16961     function getOwnEmitOutputFilePath(fileName, host, extension) {
16962         var compilerOptions = host.getCompilerOptions();
16963         var emitOutputFilePathWithoutExtension;
16964         if (compilerOptions.outDir) {
16965             emitOutputFilePathWithoutExtension = removeFileExtension(getSourceFilePathInNewDir(fileName, host, compilerOptions.outDir));
16966         }
16967         else {
16968             emitOutputFilePathWithoutExtension = removeFileExtension(fileName);
16969         }
16970         return emitOutputFilePathWithoutExtension + extension;
16971     }
16972     ts.getOwnEmitOutputFilePath = getOwnEmitOutputFilePath;
16973     function getDeclarationEmitOutputFilePath(fileName, host) {
16974         return getDeclarationEmitOutputFilePathWorker(fileName, host.getCompilerOptions(), host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
16975     }
16976     ts.getDeclarationEmitOutputFilePath = getDeclarationEmitOutputFilePath;
16977     function getDeclarationEmitOutputFilePathWorker(fileName, options, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
16978         var outputDir = options.declarationDir || options.outDir; // Prefer declaration folder if specified
16979         var path = outputDir
16980             ? getSourceFilePathInNewDirWorker(fileName, outputDir, currentDirectory, commonSourceDirectory, getCanonicalFileName)
16981             : fileName;
16982         return removeFileExtension(path) + ".d.ts" /* Dts */;
16983     }
16984     ts.getDeclarationEmitOutputFilePathWorker = getDeclarationEmitOutputFilePathWorker;
16985     function outFile(options) {
16986         return options.outFile || options.out;
16987     }
16988     ts.outFile = outFile;
16989     /** Returns 'undefined' if and only if 'options.paths' is undefined. */
16990     function getPathsBasePath(options, host) {
16991         var _a, _b;
16992         if (!options.paths)
16993             return undefined;
16994         return (_a = options.baseUrl) !== null && _a !== void 0 ? _a : ts.Debug.checkDefined(options.pathsBasePath || ((_b = host.getCurrentDirectory) === null || _b === void 0 ? void 0 : _b.call(host)), "Encountered 'paths' without a 'baseUrl', config file, or host 'getCurrentDirectory'.");
16995     }
16996     ts.getPathsBasePath = getPathsBasePath;
16997     /**
16998      * Gets the source files that are expected to have an emit output.
16999      *
17000      * Originally part of `forEachExpectedEmitFile`, this functionality was extracted to support
17001      * transformations.
17002      *
17003      * @param host An EmitHost.
17004      * @param targetSourceFile An optional target source file to emit.
17005      */
17006     function getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit) {
17007         var options = host.getCompilerOptions();
17008         if (outFile(options)) {
17009             var moduleKind = getEmitModuleKind(options);
17010             var moduleEmitEnabled_1 = options.emitDeclarationOnly || moduleKind === ts.ModuleKind.AMD || moduleKind === ts.ModuleKind.System;
17011             // Can emit only sources that are not declaration file and are either non module code or module with --module or --target es6 specified
17012             return ts.filter(host.getSourceFiles(), function (sourceFile) {
17013                 return (moduleEmitEnabled_1 || !ts.isExternalModule(sourceFile)) &&
17014                     sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit);
17015             });
17016         }
17017         else {
17018             var sourceFiles = targetSourceFile === undefined ? host.getSourceFiles() : [targetSourceFile];
17019             return ts.filter(sourceFiles, function (sourceFile) { return sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit); });
17020         }
17021     }
17022     ts.getSourceFilesToEmit = getSourceFilesToEmit;
17023     /** Don't call this for `--outFile`, just for `--outDir` or plain emit. `--outFile` needs additional checks. */
17024     function sourceFileMayBeEmitted(sourceFile, host, forceDtsEmit) {
17025         var options = host.getCompilerOptions();
17026         return !(options.noEmitForJsFiles && isSourceFileJS(sourceFile)) &&
17027             !sourceFile.isDeclarationFile &&
17028             !host.isSourceFileFromExternalLibrary(sourceFile) &&
17029             !(isJsonSourceFile(sourceFile) && host.getResolvedProjectReferenceToRedirect(sourceFile.fileName)) &&
17030             (forceDtsEmit || !host.isSourceOfProjectReferenceRedirect(sourceFile.fileName));
17031     }
17032     ts.sourceFileMayBeEmitted = sourceFileMayBeEmitted;
17033     function getSourceFilePathInNewDir(fileName, host, newDirPath) {
17034         return getSourceFilePathInNewDirWorker(fileName, newDirPath, host.getCurrentDirectory(), host.getCommonSourceDirectory(), function (f) { return host.getCanonicalFileName(f); });
17035     }
17036     ts.getSourceFilePathInNewDir = getSourceFilePathInNewDir;
17037     function getSourceFilePathInNewDirWorker(fileName, newDirPath, currentDirectory, commonSourceDirectory, getCanonicalFileName) {
17038         var sourceFilePath = ts.getNormalizedAbsolutePath(fileName, currentDirectory);
17039         var isSourceFileInCommonSourceDirectory = getCanonicalFileName(sourceFilePath).indexOf(getCanonicalFileName(commonSourceDirectory)) === 0;
17040         sourceFilePath = isSourceFileInCommonSourceDirectory ? sourceFilePath.substring(commonSourceDirectory.length) : sourceFilePath;
17041         return ts.combinePaths(newDirPath, sourceFilePath);
17042     }
17043     ts.getSourceFilePathInNewDirWorker = getSourceFilePathInNewDirWorker;
17044     function writeFile(host, diagnostics, fileName, data, writeByteOrderMark, sourceFiles) {
17045         host.writeFile(fileName, data, writeByteOrderMark, function (hostErrorMessage) {
17046             diagnostics.add(createCompilerDiagnostic(ts.Diagnostics.Could_not_write_file_0_Colon_1, fileName, hostErrorMessage));
17047         }, sourceFiles);
17048     }
17049     ts.writeFile = writeFile;
17050     function ensureDirectoriesExist(directoryPath, createDirectory, directoryExists) {
17051         if (directoryPath.length > ts.getRootLength(directoryPath) && !directoryExists(directoryPath)) {
17052             var parentDirectory = ts.getDirectoryPath(directoryPath);
17053             ensureDirectoriesExist(parentDirectory, createDirectory, directoryExists);
17054             createDirectory(directoryPath);
17055         }
17056     }
17057     function writeFileEnsuringDirectories(path, data, writeByteOrderMark, writeFile, createDirectory, directoryExists) {
17058         // PERF: Checking for directory existence is expensive.  Instead, assume the directory exists
17059         // and fall back to creating it if the file write fails.
17060         try {
17061             writeFile(path, data, writeByteOrderMark);
17062         }
17063         catch (_a) {
17064             ensureDirectoriesExist(ts.getDirectoryPath(ts.normalizePath(path)), createDirectory, directoryExists);
17065             writeFile(path, data, writeByteOrderMark);
17066         }
17067     }
17068     ts.writeFileEnsuringDirectories = writeFileEnsuringDirectories;
17069     function getLineOfLocalPosition(sourceFile, pos) {
17070         var lineStarts = ts.getLineStarts(sourceFile);
17071         return ts.computeLineOfPosition(lineStarts, pos);
17072     }
17073     ts.getLineOfLocalPosition = getLineOfLocalPosition;
17074     function getLineOfLocalPositionFromLineMap(lineMap, pos) {
17075         return ts.computeLineOfPosition(lineMap, pos);
17076     }
17077     ts.getLineOfLocalPositionFromLineMap = getLineOfLocalPositionFromLineMap;
17078     function getFirstConstructorWithBody(node) {
17079         return ts.find(node.members, function (member) { return ts.isConstructorDeclaration(member) && nodeIsPresent(member.body); });
17080     }
17081     ts.getFirstConstructorWithBody = getFirstConstructorWithBody;
17082     function getSetAccessorValueParameter(accessor) {
17083         if (accessor && accessor.parameters.length > 0) {
17084             var hasThis = accessor.parameters.length === 2 && parameterIsThisKeyword(accessor.parameters[0]);
17085             return accessor.parameters[hasThis ? 1 : 0];
17086         }
17087     }
17088     ts.getSetAccessorValueParameter = getSetAccessorValueParameter;
17089     /** Get the type annotation for the value parameter. */
17090     function getSetAccessorTypeAnnotationNode(accessor) {
17091         var parameter = getSetAccessorValueParameter(accessor);
17092         return parameter && parameter.type;
17093     }
17094     ts.getSetAccessorTypeAnnotationNode = getSetAccessorTypeAnnotationNode;
17095     function getThisParameter(signature) {
17096         // callback tags do not currently support this parameters
17097         if (signature.parameters.length && !ts.isJSDocSignature(signature)) {
17098             var thisParameter = signature.parameters[0];
17099             if (parameterIsThisKeyword(thisParameter)) {
17100                 return thisParameter;
17101             }
17102         }
17103     }
17104     ts.getThisParameter = getThisParameter;
17105     function parameterIsThisKeyword(parameter) {
17106         return isThisIdentifier(parameter.name);
17107     }
17108     ts.parameterIsThisKeyword = parameterIsThisKeyword;
17109     function isThisIdentifier(node) {
17110         return !!node && node.kind === 78 /* Identifier */ && identifierIsThisKeyword(node);
17111     }
17112     ts.isThisIdentifier = isThisIdentifier;
17113     function identifierIsThisKeyword(id) {
17114         return id.originalKeywordKind === 107 /* ThisKeyword */;
17115     }
17116     ts.identifierIsThisKeyword = identifierIsThisKeyword;
17117     function getAllAccessorDeclarations(declarations, accessor) {
17118         // TODO: GH#18217
17119         var firstAccessor;
17120         var secondAccessor;
17121         var getAccessor;
17122         var setAccessor;
17123         if (hasDynamicName(accessor)) {
17124             firstAccessor = accessor;
17125             if (accessor.kind === 167 /* GetAccessor */) {
17126                 getAccessor = accessor;
17127             }
17128             else if (accessor.kind === 168 /* SetAccessor */) {
17129                 setAccessor = accessor;
17130             }
17131             else {
17132                 ts.Debug.fail("Accessor has wrong kind");
17133             }
17134         }
17135         else {
17136             ts.forEach(declarations, function (member) {
17137                 if (ts.isAccessor(member)
17138                     && hasSyntacticModifier(member, 32 /* Static */) === hasSyntacticModifier(accessor, 32 /* Static */)) {
17139                     var memberName = getPropertyNameForPropertyNameNode(member.name);
17140                     var accessorName = getPropertyNameForPropertyNameNode(accessor.name);
17141                     if (memberName === accessorName) {
17142                         if (!firstAccessor) {
17143                             firstAccessor = member;
17144                         }
17145                         else if (!secondAccessor) {
17146                             secondAccessor = member;
17147                         }
17148                         if (member.kind === 167 /* GetAccessor */ && !getAccessor) {
17149                             getAccessor = member;
17150                         }
17151                         if (member.kind === 168 /* SetAccessor */ && !setAccessor) {
17152                             setAccessor = member;
17153                         }
17154                     }
17155                 }
17156             });
17157         }
17158         return {
17159             firstAccessor: firstAccessor,
17160             secondAccessor: secondAccessor,
17161             getAccessor: getAccessor,
17162             setAccessor: setAccessor
17163         };
17164     }
17165     ts.getAllAccessorDeclarations = getAllAccessorDeclarations;
17166     /**
17167      * Gets the effective type annotation of a variable, parameter, or property. If the node was
17168      * parsed in a JavaScript file, gets the type annotation from JSDoc.  Also gets the type of
17169      * functions only the JSDoc case.
17170      */
17171     function getEffectiveTypeAnnotationNode(node) {
17172         if (!isInJSFile(node) && ts.isFunctionDeclaration(node))
17173             return undefined;
17174         var type = node.type;
17175         if (type || !isInJSFile(node))
17176             return type;
17177         return ts.isJSDocPropertyLikeTag(node) ? node.typeExpression && node.typeExpression.type : ts.getJSDocType(node);
17178     }
17179     ts.getEffectiveTypeAnnotationNode = getEffectiveTypeAnnotationNode;
17180     function getTypeAnnotationNode(node) {
17181         return node.type;
17182     }
17183     ts.getTypeAnnotationNode = getTypeAnnotationNode;
17184     /**
17185      * Gets the effective return type annotation of a signature. If the node was parsed in a
17186      * JavaScript file, gets the return type annotation from JSDoc.
17187      */
17188     function getEffectiveReturnTypeNode(node) {
17189         return ts.isJSDocSignature(node) ?
17190             node.type && node.type.typeExpression && node.type.typeExpression.type :
17191             node.type || (isInJSFile(node) ? ts.getJSDocReturnType(node) : undefined);
17192     }
17193     ts.getEffectiveReturnTypeNode = getEffectiveReturnTypeNode;
17194     function getJSDocTypeParameterDeclarations(node) {
17195         return ts.flatMap(ts.getJSDocTags(node), function (tag) { return isNonTypeAliasTemplate(tag) ? tag.typeParameters : undefined; });
17196     }
17197     ts.getJSDocTypeParameterDeclarations = getJSDocTypeParameterDeclarations;
17198     /** template tags are only available when a typedef isn't already using them */
17199     function isNonTypeAliasTemplate(tag) {
17200         return ts.isJSDocTemplateTag(tag) && !(tag.parent.kind === 311 /* JSDocComment */ && tag.parent.tags.some(isJSDocTypeAlias));
17201     }
17202     /**
17203      * Gets the effective type annotation of the value parameter of a set accessor. If the node
17204      * was parsed in a JavaScript file, gets the type annotation from JSDoc.
17205      */
17206     function getEffectiveSetAccessorTypeAnnotationNode(node) {
17207         var parameter = getSetAccessorValueParameter(node);
17208         return parameter && getEffectiveTypeAnnotationNode(parameter);
17209     }
17210     ts.getEffectiveSetAccessorTypeAnnotationNode = getEffectiveSetAccessorTypeAnnotationNode;
17211     function emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments) {
17212         emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, node.pos, leadingComments);
17213     }
17214     ts.emitNewLineBeforeLeadingComments = emitNewLineBeforeLeadingComments;
17215     function emitNewLineBeforeLeadingCommentsOfPosition(lineMap, writer, pos, leadingComments) {
17216         // If the leading comments start on different line than the start of node, write new line
17217         if (leadingComments && leadingComments.length && pos !== leadingComments[0].pos &&
17218             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, leadingComments[0].pos)) {
17219             writer.writeLine();
17220         }
17221     }
17222     ts.emitNewLineBeforeLeadingCommentsOfPosition = emitNewLineBeforeLeadingCommentsOfPosition;
17223     function emitNewLineBeforeLeadingCommentOfPosition(lineMap, writer, pos, commentPos) {
17224         // If the leading comments start on different line than the start of node, write new line
17225         if (pos !== commentPos &&
17226             getLineOfLocalPositionFromLineMap(lineMap, pos) !== getLineOfLocalPositionFromLineMap(lineMap, commentPos)) {
17227             writer.writeLine();
17228         }
17229     }
17230     ts.emitNewLineBeforeLeadingCommentOfPosition = emitNewLineBeforeLeadingCommentOfPosition;
17231     function emitComments(text, lineMap, writer, comments, leadingSeparator, trailingSeparator, newLine, writeComment) {
17232         if (comments && comments.length > 0) {
17233             if (leadingSeparator) {
17234                 writer.writeSpace(" ");
17235             }
17236             var emitInterveningSeparator = false;
17237             for (var _i = 0, comments_1 = comments; _i < comments_1.length; _i++) {
17238                 var comment = comments_1[_i];
17239                 if (emitInterveningSeparator) {
17240                     writer.writeSpace(" ");
17241                     emitInterveningSeparator = false;
17242                 }
17243                 writeComment(text, lineMap, writer, comment.pos, comment.end, newLine);
17244                 if (comment.hasTrailingNewLine) {
17245                     writer.writeLine();
17246                 }
17247                 else {
17248                     emitInterveningSeparator = true;
17249                 }
17250             }
17251             if (emitInterveningSeparator && trailingSeparator) {
17252                 writer.writeSpace(" ");
17253             }
17254         }
17255     }
17256     ts.emitComments = emitComments;
17257     /**
17258      * Detached comment is a comment at the top of file or function body that is separated from
17259      * the next statement by space.
17260      */
17261     function emitDetachedComments(text, lineMap, writer, writeComment, node, newLine, removeComments) {
17262         var leadingComments;
17263         var currentDetachedCommentInfo;
17264         if (removeComments) {
17265             // removeComments is true, only reserve pinned comment at the top of file
17266             // For example:
17267             //      /*! Pinned Comment */
17268             //
17269             //      var x = 10;
17270             if (node.pos === 0) {
17271                 leadingComments = ts.filter(ts.getLeadingCommentRanges(text, node.pos), isPinnedCommentLocal);
17272             }
17273         }
17274         else {
17275             // removeComments is false, just get detached as normal and bypass the process to filter comment
17276             leadingComments = ts.getLeadingCommentRanges(text, node.pos);
17277         }
17278         if (leadingComments) {
17279             var detachedComments = [];
17280             var lastComment = void 0;
17281             for (var _i = 0, leadingComments_1 = leadingComments; _i < leadingComments_1.length; _i++) {
17282                 var comment = leadingComments_1[_i];
17283                 if (lastComment) {
17284                     var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, lastComment.end);
17285                     var commentLine = getLineOfLocalPositionFromLineMap(lineMap, comment.pos);
17286                     if (commentLine >= lastCommentLine + 2) {
17287                         // There was a blank line between the last comment and this comment.  This
17288                         // comment is not part of the copyright comments.  Return what we have so
17289                         // far.
17290                         break;
17291                     }
17292                 }
17293                 detachedComments.push(comment);
17294                 lastComment = comment;
17295             }
17296             if (detachedComments.length) {
17297                 // All comments look like they could have been part of the copyright header.  Make
17298                 // sure there is at least one blank line between it and the node.  If not, it's not
17299                 // a copyright header.
17300                 var lastCommentLine = getLineOfLocalPositionFromLineMap(lineMap, ts.last(detachedComments).end);
17301                 var nodeLine = getLineOfLocalPositionFromLineMap(lineMap, ts.skipTrivia(text, node.pos));
17302                 if (nodeLine >= lastCommentLine + 2) {
17303                     // Valid detachedComments
17304                     emitNewLineBeforeLeadingComments(lineMap, writer, node, leadingComments);
17305                     emitComments(text, lineMap, writer, detachedComments, /*leadingSeparator*/ false, /*trailingSeparator*/ true, newLine, writeComment);
17306                     currentDetachedCommentInfo = { nodePos: node.pos, detachedCommentEndPos: ts.last(detachedComments).end };
17307                 }
17308             }
17309         }
17310         return currentDetachedCommentInfo;
17311         function isPinnedCommentLocal(comment) {
17312             return isPinnedComment(text, comment.pos);
17313         }
17314     }
17315     ts.emitDetachedComments = emitDetachedComments;
17316     function writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine) {
17317         if (text.charCodeAt(commentPos + 1) === 42 /* asterisk */) {
17318             var firstCommentLineAndCharacter = ts.computeLineAndCharacterOfPosition(lineMap, commentPos);
17319             var lineCount = lineMap.length;
17320             var firstCommentLineIndent = void 0;
17321             for (var pos = commentPos, currentLine = firstCommentLineAndCharacter.line; pos < commentEnd; currentLine++) {
17322                 var nextLineStart = (currentLine + 1) === lineCount
17323                     ? text.length + 1
17324                     : lineMap[currentLine + 1];
17325                 if (pos !== commentPos) {
17326                     // If we are not emitting first line, we need to write the spaces to adjust the alignment
17327                     if (firstCommentLineIndent === undefined) {
17328                         firstCommentLineIndent = calculateIndent(text, lineMap[firstCommentLineAndCharacter.line], commentPos);
17329                     }
17330                     // These are number of spaces writer is going to write at current indent
17331                     var currentWriterIndentSpacing = writer.getIndent() * getIndentSize();
17332                     // Number of spaces we want to be writing
17333                     // eg: Assume writer indent
17334                     // module m {
17335                     //         /* starts at character 9 this is line 1
17336                     //    * starts at character pos 4 line                        --1  = 8 - 8 + 3
17337                     //   More left indented comment */                            --2  = 8 - 8 + 2
17338                     //     class c { }
17339                     // }
17340                     // module m {
17341                     //     /* this is line 1 -- Assume current writer indent 8
17342                     //      * line                                                --3 = 8 - 4 + 5
17343                     //            More right indented comment */                  --4 = 8 - 4 + 11
17344                     //     class c { }
17345                     // }
17346                     var spacesToEmit = currentWriterIndentSpacing - firstCommentLineIndent + calculateIndent(text, pos, nextLineStart);
17347                     if (spacesToEmit > 0) {
17348                         var numberOfSingleSpacesToEmit = spacesToEmit % getIndentSize();
17349                         var indentSizeSpaceString = getIndentString((spacesToEmit - numberOfSingleSpacesToEmit) / getIndentSize());
17350                         // Write indent size string ( in eg 1: = "", 2: "" , 3: string with 8 spaces 4: string with 12 spaces
17351                         writer.rawWrite(indentSizeSpaceString);
17352                         // Emit the single spaces (in eg: 1: 3 spaces, 2: 2 spaces, 3: 1 space, 4: 3 spaces)
17353                         while (numberOfSingleSpacesToEmit) {
17354                             writer.rawWrite(" ");
17355                             numberOfSingleSpacesToEmit--;
17356                         }
17357                     }
17358                     else {
17359                         // No spaces to emit write empty string
17360                         writer.rawWrite("");
17361                     }
17362                 }
17363                 // Write the comment line text
17364                 writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart);
17365                 pos = nextLineStart;
17366             }
17367         }
17368         else {
17369             // Single line comment of style //....
17370             writer.writeComment(text.substring(commentPos, commentEnd));
17371         }
17372     }
17373     ts.writeCommentRange = writeCommentRange;
17374     function writeTrimmedCurrentLine(text, commentEnd, writer, newLine, pos, nextLineStart) {
17375         var end = Math.min(commentEnd, nextLineStart - 1);
17376         var currentLineText = text.substring(pos, end).replace(/^\s+|\s+$/g, "");
17377         if (currentLineText) {
17378             // trimmed forward and ending spaces text
17379             writer.writeComment(currentLineText);
17380             if (end !== commentEnd) {
17381                 writer.writeLine();
17382             }
17383         }
17384         else {
17385             // Empty string - make sure we write empty line
17386             writer.rawWrite(newLine);
17387         }
17388     }
17389     function calculateIndent(text, pos, end) {
17390         var currentLineIndent = 0;
17391         for (; pos < end && ts.isWhiteSpaceSingleLine(text.charCodeAt(pos)); pos++) {
17392             if (text.charCodeAt(pos) === 9 /* tab */) {
17393                 // Tabs = TabSize = indent size and go to next tabStop
17394                 currentLineIndent += getIndentSize() - (currentLineIndent % getIndentSize());
17395             }
17396             else {
17397                 // Single space
17398                 currentLineIndent++;
17399             }
17400         }
17401         return currentLineIndent;
17402     }
17403     function hasEffectiveModifiers(node) {
17404         return getEffectiveModifierFlags(node) !== 0 /* None */;
17405     }
17406     ts.hasEffectiveModifiers = hasEffectiveModifiers;
17407     function hasSyntacticModifiers(node) {
17408         return getSyntacticModifierFlags(node) !== 0 /* None */;
17409     }
17410     ts.hasSyntacticModifiers = hasSyntacticModifiers;
17411     function hasEffectiveModifier(node, flags) {
17412         return !!getSelectedEffectiveModifierFlags(node, flags);
17413     }
17414     ts.hasEffectiveModifier = hasEffectiveModifier;
17415     function hasSyntacticModifier(node, flags) {
17416         return !!getSelectedSyntacticModifierFlags(node, flags);
17417     }
17418     ts.hasSyntacticModifier = hasSyntacticModifier;
17419     function hasStaticModifier(node) {
17420         return hasSyntacticModifier(node, 32 /* Static */);
17421     }
17422     ts.hasStaticModifier = hasStaticModifier;
17423     function hasEffectiveReadonlyModifier(node) {
17424         return hasEffectiveModifier(node, 64 /* Readonly */);
17425     }
17426     ts.hasEffectiveReadonlyModifier = hasEffectiveReadonlyModifier;
17427     function getSelectedEffectiveModifierFlags(node, flags) {
17428         return getEffectiveModifierFlags(node) & flags;
17429     }
17430     ts.getSelectedEffectiveModifierFlags = getSelectedEffectiveModifierFlags;
17431     function getSelectedSyntacticModifierFlags(node, flags) {
17432         return getSyntacticModifierFlags(node) & flags;
17433     }
17434     ts.getSelectedSyntacticModifierFlags = getSelectedSyntacticModifierFlags;
17435     function getModifierFlagsWorker(node, includeJSDoc, alwaysIncludeJSDoc) {
17436         if (node.kind >= 0 /* FirstToken */ && node.kind <= 156 /* LastToken */) {
17437             return 0 /* None */;
17438         }
17439         if (!(node.modifierFlagsCache & 536870912 /* HasComputedFlags */)) {
17440             node.modifierFlagsCache = getSyntacticModifierFlagsNoCache(node) | 536870912 /* HasComputedFlags */;
17441         }
17442         if (includeJSDoc && !(node.modifierFlagsCache & 4096 /* HasComputedJSDocModifiers */) && (alwaysIncludeJSDoc || isInJSFile(node)) && node.parent) {
17443             node.modifierFlagsCache |= getJSDocModifierFlagsNoCache(node) | 4096 /* HasComputedJSDocModifiers */;
17444         }
17445         return node.modifierFlagsCache & ~(536870912 /* HasComputedFlags */ | 4096 /* HasComputedJSDocModifiers */);
17446     }
17447     /**
17448      * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifiers will be cached on the node to improve performance.
17449      *
17450      * NOTE: This function may use `parent` pointers.
17451      */
17452     function getEffectiveModifierFlags(node) {
17453         return getModifierFlagsWorker(node, /*includeJSDoc*/ true);
17454     }
17455     ts.getEffectiveModifierFlags = getEffectiveModifierFlags;
17456     function getEffectiveModifierFlagsAlwaysIncludeJSDoc(node) {
17457         return getModifierFlagsWorker(node, /*includeJSDOc*/ true, /*alwaysIncludeJSDOc*/ true);
17458     }
17459     ts.getEffectiveModifierFlagsAlwaysIncludeJSDoc = getEffectiveModifierFlagsAlwaysIncludeJSDoc;
17460     /**
17461      * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifiers will be cached on the node to improve performance.
17462      *
17463      * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
17464      */
17465     function getSyntacticModifierFlags(node) {
17466         return getModifierFlagsWorker(node, /*includeJSDoc*/ false);
17467     }
17468     ts.getSyntacticModifierFlags = getSyntacticModifierFlags;
17469     function getJSDocModifierFlagsNoCache(node) {
17470         var flags = 0 /* None */;
17471         if (!!node.parent && !ts.isParameter(node)) {
17472             if (isInJSFile(node)) {
17473                 if (ts.getJSDocPublicTagNoCache(node))
17474                     flags |= 4 /* Public */;
17475                 if (ts.getJSDocPrivateTagNoCache(node))
17476                     flags |= 8 /* Private */;
17477                 if (ts.getJSDocProtectedTagNoCache(node))
17478                     flags |= 16 /* Protected */;
17479                 if (ts.getJSDocReadonlyTagNoCache(node))
17480                     flags |= 64 /* Readonly */;
17481             }
17482             if (ts.getJSDocDeprecatedTagNoCache(node))
17483                 flags |= 8192 /* Deprecated */;
17484         }
17485         return flags;
17486     }
17487     /**
17488      * Gets the effective ModifierFlags for the provided node, including JSDoc modifiers. The modifier flags cache on the node is ignored.
17489      *
17490      * NOTE: This function may use `parent` pointers.
17491      */
17492     function getEffectiveModifierFlagsNoCache(node) {
17493         return getSyntacticModifierFlagsNoCache(node) | getJSDocModifierFlagsNoCache(node);
17494     }
17495     ts.getEffectiveModifierFlagsNoCache = getEffectiveModifierFlagsNoCache;
17496     /**
17497      * Gets the ModifierFlags for syntactic modifiers on the provided node. The modifier flags cache on the node is ignored.
17498      *
17499      * NOTE: This function does not use `parent` pointers and will not include modifiers from JSDoc.
17500      */
17501     function getSyntacticModifierFlagsNoCache(node) {
17502         var flags = modifiersToFlags(node.modifiers);
17503         if (node.flags & 4 /* NestedNamespace */ || (node.kind === 78 /* Identifier */ && node.isInJSDocNamespace)) {
17504             flags |= 1 /* Export */;
17505         }
17506         return flags;
17507     }
17508     ts.getSyntacticModifierFlagsNoCache = getSyntacticModifierFlagsNoCache;
17509     function modifiersToFlags(modifiers) {
17510         var flags = 0 /* None */;
17511         if (modifiers) {
17512             for (var _i = 0, modifiers_1 = modifiers; _i < modifiers_1.length; _i++) {
17513                 var modifier = modifiers_1[_i];
17514                 flags |= modifierToFlag(modifier.kind);
17515             }
17516         }
17517         return flags;
17518     }
17519     ts.modifiersToFlags = modifiersToFlags;
17520     function modifierToFlag(token) {
17521         switch (token) {
17522             case 123 /* StaticKeyword */: return 32 /* Static */;
17523             case 122 /* PublicKeyword */: return 4 /* Public */;
17524             case 121 /* ProtectedKeyword */: return 16 /* Protected */;
17525             case 120 /* PrivateKeyword */: return 8 /* Private */;
17526             case 125 /* AbstractKeyword */: return 128 /* Abstract */;
17527             case 92 /* ExportKeyword */: return 1 /* Export */;
17528             case 133 /* DeclareKeyword */: return 2 /* Ambient */;
17529             case 84 /* ConstKeyword */: return 2048 /* Const */;
17530             case 87 /* DefaultKeyword */: return 512 /* Default */;
17531             case 129 /* AsyncKeyword */: return 256 /* Async */;
17532             case 142 /* ReadonlyKeyword */: return 64 /* Readonly */;
17533         }
17534         return 0 /* None */;
17535     }
17536     ts.modifierToFlag = modifierToFlag;
17537     function isLogicalOperator(token) {
17538         return token === 56 /* BarBarToken */
17539             || token === 55 /* AmpersandAmpersandToken */
17540             || token === 53 /* ExclamationToken */;
17541     }
17542     ts.isLogicalOperator = isLogicalOperator;
17543     function isLogicalOrCoalescingAssignmentOperator(token) {
17544         return token === 74 /* BarBarEqualsToken */
17545             || token === 75 /* AmpersandAmpersandEqualsToken */
17546             || token === 76 /* QuestionQuestionEqualsToken */;
17547     }
17548     ts.isLogicalOrCoalescingAssignmentOperator = isLogicalOrCoalescingAssignmentOperator;
17549     function isLogicalOrCoalescingAssignmentExpression(expr) {
17550         return isLogicalOrCoalescingAssignmentOperator(expr.operatorToken.kind);
17551     }
17552     ts.isLogicalOrCoalescingAssignmentExpression = isLogicalOrCoalescingAssignmentExpression;
17553     function isAssignmentOperator(token) {
17554         return token >= 62 /* FirstAssignment */ && token <= 77 /* LastAssignment */;
17555     }
17556     ts.isAssignmentOperator = isAssignmentOperator;
17557     /** Get `C` given `N` if `N` is in the position `class C extends N` where `N` is an ExpressionWithTypeArguments. */
17558     function tryGetClassExtendingExpressionWithTypeArguments(node) {
17559         var cls = tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
17560         return cls && !cls.isImplements ? cls.class : undefined;
17561     }
17562     ts.tryGetClassExtendingExpressionWithTypeArguments = tryGetClassExtendingExpressionWithTypeArguments;
17563     function tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node) {
17564         return ts.isExpressionWithTypeArguments(node)
17565             && ts.isHeritageClause(node.parent)
17566             && ts.isClassLike(node.parent.parent)
17567             ? { class: node.parent.parent, isImplements: node.parent.token === 116 /* ImplementsKeyword */ }
17568             : undefined;
17569     }
17570     ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments = tryGetClassImplementingOrExtendingExpressionWithTypeArguments;
17571     function isAssignmentExpression(node, excludeCompoundAssignment) {
17572         return ts.isBinaryExpression(node)
17573             && (excludeCompoundAssignment
17574                 ? node.operatorToken.kind === 62 /* EqualsToken */
17575                 : isAssignmentOperator(node.operatorToken.kind))
17576             && ts.isLeftHandSideExpression(node.left);
17577     }
17578     ts.isAssignmentExpression = isAssignmentExpression;
17579     function isDestructuringAssignment(node) {
17580         if (isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
17581             var kind = node.left.kind;
17582             return kind === 200 /* ObjectLiteralExpression */
17583                 || kind === 199 /* ArrayLiteralExpression */;
17584         }
17585         return false;
17586     }
17587     ts.isDestructuringAssignment = isDestructuringAssignment;
17588     function isExpressionWithTypeArgumentsInClassExtendsClause(node) {
17589         return tryGetClassExtendingExpressionWithTypeArguments(node) !== undefined;
17590     }
17591     ts.isExpressionWithTypeArgumentsInClassExtendsClause = isExpressionWithTypeArgumentsInClassExtendsClause;
17592     function isEntityNameExpression(node) {
17593         return node.kind === 78 /* Identifier */ || isPropertyAccessEntityNameExpression(node);
17594     }
17595     ts.isEntityNameExpression = isEntityNameExpression;
17596     function getFirstIdentifier(node) {
17597         switch (node.kind) {
17598             case 78 /* Identifier */:
17599                 return node;
17600             case 157 /* QualifiedName */:
17601                 do {
17602                     node = node.left;
17603                 } while (node.kind !== 78 /* Identifier */);
17604                 return node;
17605             case 201 /* PropertyAccessExpression */:
17606                 do {
17607                     node = node.expression;
17608                 } while (node.kind !== 78 /* Identifier */);
17609                 return node;
17610         }
17611     }
17612     ts.getFirstIdentifier = getFirstIdentifier;
17613     function isDottedName(node) {
17614         return node.kind === 78 /* Identifier */ || node.kind === 107 /* ThisKeyword */ || node.kind === 105 /* SuperKeyword */ ||
17615             node.kind === 201 /* PropertyAccessExpression */ && isDottedName(node.expression) ||
17616             node.kind === 207 /* ParenthesizedExpression */ && isDottedName(node.expression);
17617     }
17618     ts.isDottedName = isDottedName;
17619     function isPropertyAccessEntityNameExpression(node) {
17620         return ts.isPropertyAccessExpression(node) && ts.isIdentifier(node.name) && isEntityNameExpression(node.expression);
17621     }
17622     ts.isPropertyAccessEntityNameExpression = isPropertyAccessEntityNameExpression;
17623     function tryGetPropertyAccessOrIdentifierToString(expr) {
17624         if (ts.isPropertyAccessExpression(expr)) {
17625             var baseStr = tryGetPropertyAccessOrIdentifierToString(expr.expression);
17626             if (baseStr !== undefined) {
17627                 return baseStr + "." + entityNameToString(expr.name);
17628             }
17629         }
17630         else if (ts.isIdentifier(expr)) {
17631             return ts.unescapeLeadingUnderscores(expr.escapedText);
17632         }
17633         return undefined;
17634     }
17635     ts.tryGetPropertyAccessOrIdentifierToString = tryGetPropertyAccessOrIdentifierToString;
17636     function isPrototypeAccess(node) {
17637         return isBindableStaticAccessExpression(node) && getElementOrPropertyAccessName(node) === "prototype";
17638     }
17639     ts.isPrototypeAccess = isPrototypeAccess;
17640     function isRightSideOfQualifiedNameOrPropertyAccess(node) {
17641         return (node.parent.kind === 157 /* QualifiedName */ && node.parent.right === node) ||
17642             (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.name === node);
17643     }
17644     ts.isRightSideOfQualifiedNameOrPropertyAccess = isRightSideOfQualifiedNameOrPropertyAccess;
17645     function isEmptyObjectLiteral(expression) {
17646         return expression.kind === 200 /* ObjectLiteralExpression */ &&
17647             expression.properties.length === 0;
17648     }
17649     ts.isEmptyObjectLiteral = isEmptyObjectLiteral;
17650     function isEmptyArrayLiteral(expression) {
17651         return expression.kind === 199 /* ArrayLiteralExpression */ &&
17652             expression.elements.length === 0;
17653     }
17654     ts.isEmptyArrayLiteral = isEmptyArrayLiteral;
17655     function getLocalSymbolForExportDefault(symbol) {
17656         if (!isExportDefaultSymbol(symbol))
17657             return undefined;
17658         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
17659             var decl = _a[_i];
17660             if (decl.localSymbol)
17661                 return decl.localSymbol;
17662         }
17663         return undefined;
17664     }
17665     ts.getLocalSymbolForExportDefault = getLocalSymbolForExportDefault;
17666     function isExportDefaultSymbol(symbol) {
17667         return symbol && ts.length(symbol.declarations) > 0 && hasSyntacticModifier(symbol.declarations[0], 512 /* Default */);
17668     }
17669     /** Return ".ts", ".d.ts", or ".tsx", if that is the extension. */
17670     function tryExtractTSExtension(fileName) {
17671         return ts.find(ts.supportedTSExtensionsForExtractExtension, function (extension) { return ts.fileExtensionIs(fileName, extension); });
17672     }
17673     ts.tryExtractTSExtension = tryExtractTSExtension;
17674     /**
17675      * Replace each instance of non-ascii characters by one, two, three, or four escape sequences
17676      * representing the UTF-8 encoding of the character, and return the expanded char code list.
17677      */
17678     function getExpandedCharCodes(input) {
17679         var output = [];
17680         var length = input.length;
17681         for (var i = 0; i < length; i++) {
17682             var charCode = input.charCodeAt(i);
17683             // handle utf8
17684             if (charCode < 0x80) {
17685                 output.push(charCode);
17686             }
17687             else if (charCode < 0x800) {
17688                 output.push((charCode >> 6) | 192);
17689                 output.push((charCode & 63) | 128);
17690             }
17691             else if (charCode < 0x10000) {
17692                 output.push((charCode >> 12) | 224);
17693                 output.push(((charCode >> 6) & 63) | 128);
17694                 output.push((charCode & 63) | 128);
17695             }
17696             else if (charCode < 0x20000) {
17697                 output.push((charCode >> 18) | 240);
17698                 output.push(((charCode >> 12) & 63) | 128);
17699                 output.push(((charCode >> 6) & 63) | 128);
17700                 output.push((charCode & 63) | 128);
17701             }
17702             else {
17703                 ts.Debug.assert(false, "Unexpected code point");
17704             }
17705         }
17706         return output;
17707     }
17708     var base64Digits = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
17709     /**
17710      * Converts a string to a base-64 encoded ASCII string.
17711      */
17712     function convertToBase64(input) {
17713         var result = "";
17714         var charCodes = getExpandedCharCodes(input);
17715         var i = 0;
17716         var length = charCodes.length;
17717         var byte1, byte2, byte3, byte4;
17718         while (i < length) {
17719             // Convert every 6-bits in the input 3 character points
17720             // into a base64 digit
17721             byte1 = charCodes[i] >> 2;
17722             byte2 = (charCodes[i] & 3) << 4 | charCodes[i + 1] >> 4;
17723             byte3 = (charCodes[i + 1] & 15) << 2 | charCodes[i + 2] >> 6;
17724             byte4 = charCodes[i + 2] & 63;
17725             // We are out of characters in the input, set the extra
17726             // digits to 64 (padding character).
17727             if (i + 1 >= length) {
17728                 byte3 = byte4 = 64;
17729             }
17730             else if (i + 2 >= length) {
17731                 byte4 = 64;
17732             }
17733             // Write to the output
17734             result += base64Digits.charAt(byte1) + base64Digits.charAt(byte2) + base64Digits.charAt(byte3) + base64Digits.charAt(byte4);
17735             i += 3;
17736         }
17737         return result;
17738     }
17739     ts.convertToBase64 = convertToBase64;
17740     function getStringFromExpandedCharCodes(codes) {
17741         var output = "";
17742         var i = 0;
17743         var length = codes.length;
17744         while (i < length) {
17745             var charCode = codes[i];
17746             if (charCode < 0x80) {
17747                 output += String.fromCharCode(charCode);
17748                 i++;
17749             }
17750             else if ((charCode & 192) === 192) {
17751                 var value = charCode & 63;
17752                 i++;
17753                 var nextCode = codes[i];
17754                 while ((nextCode & 192) === 128) {
17755                     value = (value << 6) | (nextCode & 63);
17756                     i++;
17757                     nextCode = codes[i];
17758                 }
17759                 // `value` may be greater than 10FFFF (the maximum unicode codepoint) - JS will just make this into an invalid character for us
17760                 output += String.fromCharCode(value);
17761             }
17762             else {
17763                 // We don't want to kill the process when decoding fails (due to a following char byte not
17764                 // following a leading char), so we just print the (bad) value
17765                 output += String.fromCharCode(charCode);
17766                 i++;
17767             }
17768         }
17769         return output;
17770     }
17771     function base64encode(host, input) {
17772         if (host && host.base64encode) {
17773             return host.base64encode(input);
17774         }
17775         return convertToBase64(input);
17776     }
17777     ts.base64encode = base64encode;
17778     function base64decode(host, input) {
17779         if (host && host.base64decode) {
17780             return host.base64decode(input);
17781         }
17782         var length = input.length;
17783         var expandedCharCodes = [];
17784         var i = 0;
17785         while (i < length) {
17786             // Stop decoding once padding characters are present
17787             if (input.charCodeAt(i) === base64Digits.charCodeAt(64)) {
17788                 break;
17789             }
17790             // convert 4 input digits into three characters, ignoring padding characters at the end
17791             var ch1 = base64Digits.indexOf(input[i]);
17792             var ch2 = base64Digits.indexOf(input[i + 1]);
17793             var ch3 = base64Digits.indexOf(input[i + 2]);
17794             var ch4 = base64Digits.indexOf(input[i + 3]);
17795             var code1 = ((ch1 & 63) << 2) | ((ch2 >> 4) & 3);
17796             var code2 = ((ch2 & 15) << 4) | ((ch3 >> 2) & 15);
17797             var code3 = ((ch3 & 3) << 6) | (ch4 & 63);
17798             if (code2 === 0 && ch3 !== 0) { // code2 decoded to zero, but ch3 was padding - elide code2 and code3
17799                 expandedCharCodes.push(code1);
17800             }
17801             else if (code3 === 0 && ch4 !== 0) { // code3 decoded to zero, but ch4 was padding, elide code3
17802                 expandedCharCodes.push(code1, code2);
17803             }
17804             else {
17805                 expandedCharCodes.push(code1, code2, code3);
17806             }
17807             i += 4;
17808         }
17809         return getStringFromExpandedCharCodes(expandedCharCodes);
17810     }
17811     ts.base64decode = base64decode;
17812     function readJson(path, host) {
17813         try {
17814             var jsonText = host.readFile(path);
17815             if (!jsonText)
17816                 return {};
17817             var result = ts.parseConfigFileTextToJson(path, jsonText);
17818             if (result.error) {
17819                 return {};
17820             }
17821             return result.config;
17822         }
17823         catch (e) {
17824             // gracefully handle if readFile fails or returns not JSON
17825             return {};
17826         }
17827     }
17828     ts.readJson = readJson;
17829     function directoryProbablyExists(directoryName, host) {
17830         // if host does not support 'directoryExists' assume that directory will exist
17831         return !host.directoryExists || host.directoryExists(directoryName);
17832     }
17833     ts.directoryProbablyExists = directoryProbablyExists;
17834     var carriageReturnLineFeed = "\r\n";
17835     var lineFeed = "\n";
17836     function getNewLineCharacter(options, getNewLine) {
17837         switch (options.newLine) {
17838             case 0 /* CarriageReturnLineFeed */:
17839                 return carriageReturnLineFeed;
17840             case 1 /* LineFeed */:
17841                 return lineFeed;
17842         }
17843         return getNewLine ? getNewLine() : ts.sys ? ts.sys.newLine : carriageReturnLineFeed;
17844     }
17845     ts.getNewLineCharacter = getNewLineCharacter;
17846     /**
17847      * Creates a new TextRange from the provided pos and end.
17848      *
17849      * @param pos The start position.
17850      * @param end The end position.
17851      */
17852     function createRange(pos, end) {
17853         if (end === void 0) { end = pos; }
17854         ts.Debug.assert(end >= pos || end === -1);
17855         return { pos: pos, end: end };
17856     }
17857     ts.createRange = createRange;
17858     /**
17859      * Creates a new TextRange from a provided range with a new end position.
17860      *
17861      * @param range A TextRange.
17862      * @param end The new end position.
17863      */
17864     function moveRangeEnd(range, end) {
17865         return createRange(range.pos, end);
17866     }
17867     ts.moveRangeEnd = moveRangeEnd;
17868     /**
17869      * Creates a new TextRange from a provided range with a new start position.
17870      *
17871      * @param range A TextRange.
17872      * @param pos The new Start position.
17873      */
17874     function moveRangePos(range, pos) {
17875         return createRange(pos, range.end);
17876     }
17877     ts.moveRangePos = moveRangePos;
17878     /**
17879      * Moves the start position of a range past any decorators.
17880      */
17881     function moveRangePastDecorators(node) {
17882         return node.decorators && node.decorators.length > 0
17883             ? moveRangePos(node, node.decorators.end)
17884             : node;
17885     }
17886     ts.moveRangePastDecorators = moveRangePastDecorators;
17887     /**
17888      * Moves the start position of a range past any decorators or modifiers.
17889      */
17890     function moveRangePastModifiers(node) {
17891         return node.modifiers && node.modifiers.length > 0
17892             ? moveRangePos(node, node.modifiers.end)
17893             : moveRangePastDecorators(node);
17894     }
17895     ts.moveRangePastModifiers = moveRangePastModifiers;
17896     /**
17897      * Determines whether a TextRange has the same start and end positions.
17898      *
17899      * @param range A TextRange.
17900      */
17901     function isCollapsedRange(range) {
17902         return range.pos === range.end;
17903     }
17904     ts.isCollapsedRange = isCollapsedRange;
17905     /**
17906      * Creates a new TextRange for a token at the provides start position.
17907      *
17908      * @param pos The start position.
17909      * @param token The token.
17910      */
17911     function createTokenRange(pos, token) {
17912         return createRange(pos, pos + ts.tokenToString(token).length);
17913     }
17914     ts.createTokenRange = createTokenRange;
17915     function rangeIsOnSingleLine(range, sourceFile) {
17916         return rangeStartIsOnSameLineAsRangeEnd(range, range, sourceFile);
17917     }
17918     ts.rangeIsOnSingleLine = rangeIsOnSingleLine;
17919     function rangeStartPositionsAreOnSameLine(range1, range2, sourceFile) {
17920         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17921     }
17922     ts.rangeStartPositionsAreOnSameLine = rangeStartPositionsAreOnSameLine;
17923     function rangeEndPositionsAreOnSameLine(range1, range2, sourceFile) {
17924         return positionsAreOnSameLine(range1.end, range2.end, sourceFile);
17925     }
17926     ts.rangeEndPositionsAreOnSameLine = rangeEndPositionsAreOnSameLine;
17927     function rangeStartIsOnSameLineAsRangeEnd(range1, range2, sourceFile) {
17928         return positionsAreOnSameLine(getStartPositionOfRange(range1, sourceFile, /*includeComments*/ false), range2.end, sourceFile);
17929     }
17930     ts.rangeStartIsOnSameLineAsRangeEnd = rangeStartIsOnSameLineAsRangeEnd;
17931     function rangeEndIsOnSameLineAsRangeStart(range1, range2, sourceFile) {
17932         return positionsAreOnSameLine(range1.end, getStartPositionOfRange(range2, sourceFile, /*includeComments*/ false), sourceFile);
17933     }
17934     ts.rangeEndIsOnSameLineAsRangeStart = rangeEndIsOnSameLineAsRangeStart;
17935     function getLinesBetweenRangeEndAndRangeStart(range1, range2, sourceFile, includeSecondRangeComments) {
17936         var range2Start = getStartPositionOfRange(range2, sourceFile, includeSecondRangeComments);
17937         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2Start);
17938     }
17939     ts.getLinesBetweenRangeEndAndRangeStart = getLinesBetweenRangeEndAndRangeStart;
17940     function getLinesBetweenRangeEndPositions(range1, range2, sourceFile) {
17941         return ts.getLinesBetweenPositions(sourceFile, range1.end, range2.end);
17942     }
17943     ts.getLinesBetweenRangeEndPositions = getLinesBetweenRangeEndPositions;
17944     function isNodeArrayMultiLine(list, sourceFile) {
17945         return !positionsAreOnSameLine(list.pos, list.end, sourceFile);
17946     }
17947     ts.isNodeArrayMultiLine = isNodeArrayMultiLine;
17948     function positionsAreOnSameLine(pos1, pos2, sourceFile) {
17949         return ts.getLinesBetweenPositions(sourceFile, pos1, pos2) === 0;
17950     }
17951     ts.positionsAreOnSameLine = positionsAreOnSameLine;
17952     function getStartPositionOfRange(range, sourceFile, includeComments) {
17953         return positionIsSynthesized(range.pos) ? -1 : ts.skipTrivia(sourceFile.text, range.pos, /*stopAfterLineBreak*/ false, includeComments);
17954     }
17955     ts.getStartPositionOfRange = getStartPositionOfRange;
17956     function getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17957         var startPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17958         var prevPos = getPreviousNonWhitespacePosition(startPos, stopPos, sourceFile);
17959         return ts.getLinesBetweenPositions(sourceFile, prevPos !== null && prevPos !== void 0 ? prevPos : stopPos, startPos);
17960     }
17961     ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter = getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter;
17962     function getLinesBetweenPositionAndNextNonWhitespaceCharacter(pos, stopPos, sourceFile, includeComments) {
17963         var nextPos = ts.skipTrivia(sourceFile.text, pos, /*stopAfterLineBreak*/ false, includeComments);
17964         return ts.getLinesBetweenPositions(sourceFile, pos, Math.min(stopPos, nextPos));
17965     }
17966     ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter = getLinesBetweenPositionAndNextNonWhitespaceCharacter;
17967     function getPreviousNonWhitespacePosition(pos, stopPos, sourceFile) {
17968         if (stopPos === void 0) { stopPos = 0; }
17969         while (pos-- > stopPos) {
17970             if (!ts.isWhiteSpaceLike(sourceFile.text.charCodeAt(pos))) {
17971                 return pos;
17972             }
17973         }
17974     }
17975     /**
17976      * Determines whether a name was originally the declaration name of an enum or namespace
17977      * declaration.
17978      */
17979     function isDeclarationNameOfEnumOrNamespace(node) {
17980         var parseNode = ts.getParseTreeNode(node);
17981         if (parseNode) {
17982             switch (parseNode.parent.kind) {
17983                 case 255 /* EnumDeclaration */:
17984                 case 256 /* ModuleDeclaration */:
17985                     return parseNode === parseNode.parent.name;
17986             }
17987         }
17988         return false;
17989     }
17990     ts.isDeclarationNameOfEnumOrNamespace = isDeclarationNameOfEnumOrNamespace;
17991     function getInitializedVariables(node) {
17992         return ts.filter(node.declarations, isInitializedVariable);
17993     }
17994     ts.getInitializedVariables = getInitializedVariables;
17995     function isInitializedVariable(node) {
17996         return node.initializer !== undefined;
17997     }
17998     function isWatchSet(options) {
17999         // Firefox has Object.prototype.watch
18000         return options.watch && options.hasOwnProperty("watch");
18001     }
18002     ts.isWatchSet = isWatchSet;
18003     function closeFileWatcher(watcher) {
18004         watcher.close();
18005     }
18006     ts.closeFileWatcher = closeFileWatcher;
18007     function getCheckFlags(symbol) {
18008         return symbol.flags & 33554432 /* Transient */ ? symbol.checkFlags : 0;
18009     }
18010     ts.getCheckFlags = getCheckFlags;
18011     function getDeclarationModifierFlagsFromSymbol(s) {
18012         if (s.valueDeclaration) {
18013             var flags = ts.getCombinedModifierFlags(s.valueDeclaration);
18014             return s.parent && s.parent.flags & 32 /* Class */ ? flags : flags & ~28 /* AccessibilityModifier */;
18015         }
18016         if (getCheckFlags(s) & 6 /* Synthetic */) {
18017             var checkFlags = s.checkFlags;
18018             var accessModifier = checkFlags & 1024 /* ContainsPrivate */ ? 8 /* Private */ :
18019                 checkFlags & 256 /* ContainsPublic */ ? 4 /* Public */ :
18020                     16 /* Protected */;
18021             var staticModifier = checkFlags & 2048 /* ContainsStatic */ ? 32 /* Static */ : 0;
18022             return accessModifier | staticModifier;
18023         }
18024         if (s.flags & 4194304 /* Prototype */) {
18025             return 4 /* Public */ | 32 /* Static */;
18026         }
18027         return 0;
18028     }
18029     ts.getDeclarationModifierFlagsFromSymbol = getDeclarationModifierFlagsFromSymbol;
18030     function skipAlias(symbol, checker) {
18031         return symbol.flags & 2097152 /* Alias */ ? checker.getAliasedSymbol(symbol) : symbol;
18032     }
18033     ts.skipAlias = skipAlias;
18034     /** See comment on `declareModuleMember` in `binder.ts`. */
18035     function getCombinedLocalAndExportSymbolFlags(symbol) {
18036         return symbol.exportSymbol ? symbol.exportSymbol.flags | symbol.flags : symbol.flags;
18037     }
18038     ts.getCombinedLocalAndExportSymbolFlags = getCombinedLocalAndExportSymbolFlags;
18039     function isWriteOnlyAccess(node) {
18040         return accessKind(node) === 1 /* Write */;
18041     }
18042     ts.isWriteOnlyAccess = isWriteOnlyAccess;
18043     function isWriteAccess(node) {
18044         return accessKind(node) !== 0 /* Read */;
18045     }
18046     ts.isWriteAccess = isWriteAccess;
18047     var AccessKind;
18048     (function (AccessKind) {
18049         /** Only reads from a variable. */
18050         AccessKind[AccessKind["Read"] = 0] = "Read";
18051         /** Only writes to a variable without using the result. E.g.: `x++;`. */
18052         AccessKind[AccessKind["Write"] = 1] = "Write";
18053         /** Writes to a variable and uses the result as an expression. E.g.: `f(x++);`. */
18054         AccessKind[AccessKind["ReadWrite"] = 2] = "ReadWrite";
18055     })(AccessKind || (AccessKind = {}));
18056     function accessKind(node) {
18057         var parent = node.parent;
18058         if (!parent)
18059             return 0 /* Read */;
18060         switch (parent.kind) {
18061             case 207 /* ParenthesizedExpression */:
18062                 return accessKind(parent);
18063             case 215 /* PostfixUnaryExpression */:
18064             case 214 /* PrefixUnaryExpression */:
18065                 var operator = parent.operator;
18066                 return operator === 45 /* PlusPlusToken */ || operator === 46 /* MinusMinusToken */ ? writeOrReadWrite() : 0 /* Read */;
18067             case 216 /* BinaryExpression */:
18068                 var _a = parent, left = _a.left, operatorToken = _a.operatorToken;
18069                 return left === node && isAssignmentOperator(operatorToken.kind) ?
18070                     operatorToken.kind === 62 /* EqualsToken */ ? 1 /* Write */ : writeOrReadWrite()
18071                     : 0 /* Read */;
18072             case 201 /* PropertyAccessExpression */:
18073                 return parent.name !== node ? 0 /* Read */ : accessKind(parent);
18074             case 288 /* PropertyAssignment */: {
18075                 var parentAccess = accessKind(parent.parent);
18076                 // In `({ x: varname }) = { x: 1 }`, the left `x` is a read, the right `x` is a write.
18077                 return node === parent.name ? reverseAccessKind(parentAccess) : parentAccess;
18078             }
18079             case 289 /* ShorthandPropertyAssignment */:
18080                 // Assume it's the local variable being accessed, since we don't check public properties for --noUnusedLocals.
18081                 return node === parent.objectAssignmentInitializer ? 0 /* Read */ : accessKind(parent.parent);
18082             case 199 /* ArrayLiteralExpression */:
18083                 return accessKind(parent);
18084             default:
18085                 return 0 /* Read */;
18086         }
18087         function writeOrReadWrite() {
18088             // If grandparent is not an ExpressionStatement, this is used as an expression in addition to having a side effect.
18089             return parent.parent && skipParenthesesUp(parent.parent).kind === 233 /* ExpressionStatement */ ? 1 /* Write */ : 2 /* ReadWrite */;
18090         }
18091     }
18092     function reverseAccessKind(a) {
18093         switch (a) {
18094             case 0 /* Read */:
18095                 return 1 /* Write */;
18096             case 1 /* Write */:
18097                 return 0 /* Read */;
18098             case 2 /* ReadWrite */:
18099                 return 2 /* ReadWrite */;
18100             default:
18101                 return ts.Debug.assertNever(a);
18102         }
18103     }
18104     function compareDataObjects(dst, src) {
18105         if (!dst || !src || Object.keys(dst).length !== Object.keys(src).length) {
18106             return false;
18107         }
18108         for (var e in dst) {
18109             if (typeof dst[e] === "object") {
18110                 if (!compareDataObjects(dst[e], src[e])) {
18111                     return false;
18112                 }
18113             }
18114             else if (typeof dst[e] !== "function") {
18115                 if (dst[e] !== src[e]) {
18116                     return false;
18117                 }
18118             }
18119         }
18120         return true;
18121     }
18122     ts.compareDataObjects = compareDataObjects;
18123     /**
18124      * clears already present map by calling onDeleteExistingValue callback before deleting that key/value
18125      */
18126     function clearMap(map, onDeleteValue) {
18127         // Remove all
18128         map.forEach(onDeleteValue);
18129         map.clear();
18130     }
18131     ts.clearMap = clearMap;
18132     /**
18133      * Mutates the map with newMap such that keys in map will be same as newMap.
18134      */
18135     function mutateMapSkippingNewValues(map, newMap, options) {
18136         var onDeleteValue = options.onDeleteValue, onExistingValue = options.onExistingValue;
18137         // Needs update
18138         map.forEach(function (existingValue, key) {
18139             var valueInNewMap = newMap.get(key);
18140             // Not present any more in new map, remove it
18141             if (valueInNewMap === undefined) {
18142                 map.delete(key);
18143                 onDeleteValue(existingValue, key);
18144             }
18145             // If present notify about existing values
18146             else if (onExistingValue) {
18147                 onExistingValue(existingValue, valueInNewMap, key);
18148             }
18149         });
18150     }
18151     ts.mutateMapSkippingNewValues = mutateMapSkippingNewValues;
18152     /**
18153      * Mutates the map with newMap such that keys in map will be same as newMap.
18154      */
18155     function mutateMap(map, newMap, options) {
18156         // Needs update
18157         mutateMapSkippingNewValues(map, newMap, options);
18158         var createNewValue = options.createNewValue;
18159         // Add new values that are not already present
18160         newMap.forEach(function (valueInNewMap, key) {
18161             if (!map.has(key)) {
18162                 // New values
18163                 map.set(key, createNewValue(key, valueInNewMap));
18164             }
18165         });
18166     }
18167     ts.mutateMap = mutateMap;
18168     // Return true if the given type is the constructor type for an abstract class
18169     function isAbstractConstructorType(type) {
18170         return !!(getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isAbstractConstructorSymbol(type.symbol);
18171     }
18172     ts.isAbstractConstructorType = isAbstractConstructorType;
18173     function isAbstractConstructorSymbol(symbol) {
18174         if (symbol.flags & 32 /* Class */) {
18175             var declaration = getClassLikeDeclarationOfSymbol(symbol);
18176             return !!declaration && hasSyntacticModifier(declaration, 128 /* Abstract */);
18177         }
18178         return false;
18179     }
18180     ts.isAbstractConstructorSymbol = isAbstractConstructorSymbol;
18181     function getClassLikeDeclarationOfSymbol(symbol) {
18182         return ts.find(symbol.declarations, ts.isClassLike);
18183     }
18184     ts.getClassLikeDeclarationOfSymbol = getClassLikeDeclarationOfSymbol;
18185     function getObjectFlags(type) {
18186         return type.flags & 3899393 /* ObjectFlagsType */ ? type.objectFlags : 0;
18187     }
18188     ts.getObjectFlags = getObjectFlags;
18189     function typeHasCallOrConstructSignatures(type, checker) {
18190         return checker.getSignaturesOfType(type, 0 /* Call */).length !== 0 || checker.getSignaturesOfType(type, 1 /* Construct */).length !== 0;
18191     }
18192     ts.typeHasCallOrConstructSignatures = typeHasCallOrConstructSignatures;
18193     function forSomeAncestorDirectory(directory, callback) {
18194         return !!ts.forEachAncestorDirectory(directory, function (d) { return callback(d) ? true : undefined; });
18195     }
18196     ts.forSomeAncestorDirectory = forSomeAncestorDirectory;
18197     function isUMDExportSymbol(symbol) {
18198         return !!symbol && !!symbol.declarations && !!symbol.declarations[0] && ts.isNamespaceExportDeclaration(symbol.declarations[0]);
18199     }
18200     ts.isUMDExportSymbol = isUMDExportSymbol;
18201     function showModuleSpecifier(_a) {
18202         var moduleSpecifier = _a.moduleSpecifier;
18203         return ts.isStringLiteral(moduleSpecifier) ? moduleSpecifier.text : getTextOfNode(moduleSpecifier);
18204     }
18205     ts.showModuleSpecifier = showModuleSpecifier;
18206     function getLastChild(node) {
18207         var lastChild;
18208         ts.forEachChild(node, function (child) {
18209             if (nodeIsPresent(child))
18210                 lastChild = child;
18211         }, function (children) {
18212             // As an optimization, jump straight to the end of the list.
18213             for (var i = children.length - 1; i >= 0; i--) {
18214                 if (nodeIsPresent(children[i])) {
18215                     lastChild = children[i];
18216                     break;
18217                 }
18218             }
18219         });
18220         return lastChild;
18221     }
18222     ts.getLastChild = getLastChild;
18223     function addToSeen(seen, key, value) {
18224         if (value === void 0) { value = true; }
18225         key = String(key);
18226         if (seen.has(key)) {
18227             return false;
18228         }
18229         seen.set(key, value);
18230         return true;
18231     }
18232     ts.addToSeen = addToSeen;
18233     function isObjectTypeDeclaration(node) {
18234         return ts.isClassLike(node) || ts.isInterfaceDeclaration(node) || ts.isTypeLiteralNode(node);
18235     }
18236     ts.isObjectTypeDeclaration = isObjectTypeDeclaration;
18237     function isTypeNodeKind(kind) {
18238         return (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */)
18239             || kind === 128 /* AnyKeyword */
18240             || kind === 152 /* UnknownKeyword */
18241             || kind === 144 /* NumberKeyword */
18242             || kind === 155 /* BigIntKeyword */
18243             || kind === 145 /* ObjectKeyword */
18244             || kind === 131 /* BooleanKeyword */
18245             || kind === 147 /* StringKeyword */
18246             || kind === 148 /* SymbolKeyword */
18247             || kind === 113 /* VoidKeyword */
18248             || kind === 150 /* UndefinedKeyword */
18249             || kind === 141 /* NeverKeyword */
18250             || kind === 223 /* ExpressionWithTypeArguments */
18251             || kind === 303 /* JSDocAllType */
18252             || kind === 304 /* JSDocUnknownType */
18253             || kind === 305 /* JSDocNullableType */
18254             || kind === 306 /* JSDocNonNullableType */
18255             || kind === 307 /* JSDocOptionalType */
18256             || kind === 308 /* JSDocFunctionType */
18257             || kind === 309 /* JSDocVariadicType */;
18258     }
18259     ts.isTypeNodeKind = isTypeNodeKind;
18260     function isAccessExpression(node) {
18261         return node.kind === 201 /* PropertyAccessExpression */ || node.kind === 202 /* ElementAccessExpression */;
18262     }
18263     ts.isAccessExpression = isAccessExpression;
18264     function getNameOfAccessExpression(node) {
18265         if (node.kind === 201 /* PropertyAccessExpression */) {
18266             return node.name;
18267         }
18268         ts.Debug.assert(node.kind === 202 /* ElementAccessExpression */);
18269         return node.argumentExpression;
18270     }
18271     ts.getNameOfAccessExpression = getNameOfAccessExpression;
18272     function isBundleFileTextLike(section) {
18273         switch (section.kind) {
18274             case "text" /* Text */:
18275             case "internal" /* Internal */:
18276                 return true;
18277             default:
18278                 return false;
18279         }
18280     }
18281     ts.isBundleFileTextLike = isBundleFileTextLike;
18282     function isNamedImportsOrExports(node) {
18283         return node.kind === 264 /* NamedImports */ || node.kind === 268 /* NamedExports */;
18284     }
18285     ts.isNamedImportsOrExports = isNamedImportsOrExports;
18286     function getLeftmostAccessExpression(expr) {
18287         while (isAccessExpression(expr)) {
18288             expr = expr.expression;
18289         }
18290         return expr;
18291     }
18292     ts.getLeftmostAccessExpression = getLeftmostAccessExpression;
18293     function getLeftmostExpression(node, stopAtCallExpressions) {
18294         while (true) {
18295             switch (node.kind) {
18296                 case 215 /* PostfixUnaryExpression */:
18297                     node = node.operand;
18298                     continue;
18299                 case 216 /* BinaryExpression */:
18300                     node = node.left;
18301                     continue;
18302                 case 217 /* ConditionalExpression */:
18303                     node = node.condition;
18304                     continue;
18305                 case 205 /* TaggedTemplateExpression */:
18306                     node = node.tag;
18307                     continue;
18308                 case 203 /* CallExpression */:
18309                     if (stopAtCallExpressions) {
18310                         return node;
18311                     }
18312                 // falls through
18313                 case 224 /* AsExpression */:
18314                 case 202 /* ElementAccessExpression */:
18315                 case 201 /* PropertyAccessExpression */:
18316                 case 225 /* NonNullExpression */:
18317                 case 336 /* PartiallyEmittedExpression */:
18318                     node = node.expression;
18319                     continue;
18320             }
18321             return node;
18322         }
18323     }
18324     ts.getLeftmostExpression = getLeftmostExpression;
18325     function Symbol(flags, name) {
18326         this.flags = flags;
18327         this.escapedName = name;
18328         this.declarations = undefined;
18329         this.valueDeclaration = undefined;
18330         this.id = undefined;
18331         this.mergeId = undefined;
18332         this.parent = undefined;
18333     }
18334     function Type(checker, flags) {
18335         this.flags = flags;
18336         if (ts.Debug.isDebugging || ts.tracing.isTracing()) {
18337             this.checker = checker;
18338         }
18339     }
18340     function Signature(checker, flags) {
18341         this.flags = flags;
18342         if (ts.Debug.isDebugging) {
18343             this.checker = checker;
18344         }
18345     }
18346     function Node(kind, pos, end) {
18347         this.pos = pos;
18348         this.end = end;
18349         this.kind = kind;
18350         this.id = 0;
18351         this.flags = 0 /* None */;
18352         this.modifierFlagsCache = 0 /* None */;
18353         this.transformFlags = 0 /* None */;
18354         this.parent = undefined;
18355         this.original = undefined;
18356     }
18357     function Token(kind, pos, end) {
18358         this.pos = pos;
18359         this.end = end;
18360         this.kind = kind;
18361         this.id = 0;
18362         this.flags = 0 /* None */;
18363         this.transformFlags = 0 /* None */;
18364         this.parent = undefined;
18365     }
18366     function Identifier(kind, pos, end) {
18367         this.pos = pos;
18368         this.end = end;
18369         this.kind = kind;
18370         this.id = 0;
18371         this.flags = 0 /* None */;
18372         this.transformFlags = 0 /* None */;
18373         this.parent = undefined;
18374         this.original = undefined;
18375         this.flowNode = undefined;
18376     }
18377     function SourceMapSource(fileName, text, skipTrivia) {
18378         this.fileName = fileName;
18379         this.text = text;
18380         this.skipTrivia = skipTrivia || (function (pos) { return pos; });
18381     }
18382     // eslint-disable-next-line prefer-const
18383     ts.objectAllocator = {
18384         getNodeConstructor: function () { return Node; },
18385         getTokenConstructor: function () { return Token; },
18386         getIdentifierConstructor: function () { return Identifier; },
18387         getPrivateIdentifierConstructor: function () { return Node; },
18388         getSourceFileConstructor: function () { return Node; },
18389         getSymbolConstructor: function () { return Symbol; },
18390         getTypeConstructor: function () { return Type; },
18391         getSignatureConstructor: function () { return Signature; },
18392         getSourceMapSourceConstructor: function () { return SourceMapSource; },
18393     };
18394     function setObjectAllocator(alloc) {
18395         ts.objectAllocator = alloc;
18396     }
18397     ts.setObjectAllocator = setObjectAllocator;
18398     function formatStringFromArgs(text, args, baseIndex) {
18399         if (baseIndex === void 0) { baseIndex = 0; }
18400         return text.replace(/{(\d+)}/g, function (_match, index) { return "" + ts.Debug.checkDefined(args[+index + baseIndex]); });
18401     }
18402     ts.formatStringFromArgs = formatStringFromArgs;
18403     /* @internal */
18404     function setLocalizedDiagnosticMessages(messages) {
18405         ts.localizedDiagnosticMessages = messages;
18406     }
18407     ts.setLocalizedDiagnosticMessages = setLocalizedDiagnosticMessages;
18408     function getLocaleSpecificMessage(message) {
18409         return ts.localizedDiagnosticMessages && ts.localizedDiagnosticMessages[message.key] || message.message;
18410     }
18411     ts.getLocaleSpecificMessage = getLocaleSpecificMessage;
18412     function createDetachedDiagnostic(fileName, start, length, message) {
18413         ts.Debug.assertGreaterThanOrEqual(start, 0);
18414         ts.Debug.assertGreaterThanOrEqual(length, 0);
18415         var text = getLocaleSpecificMessage(message);
18416         if (arguments.length > 4) {
18417             text = formatStringFromArgs(text, arguments, 4);
18418         }
18419         return {
18420             file: undefined,
18421             start: start,
18422             length: length,
18423             messageText: text,
18424             category: message.category,
18425             code: message.code,
18426             reportsUnnecessary: message.reportsUnnecessary,
18427             fileName: fileName,
18428         };
18429     }
18430     ts.createDetachedDiagnostic = createDetachedDiagnostic;
18431     function isDiagnosticWithDetachedLocation(diagnostic) {
18432         return diagnostic.file === undefined
18433             && diagnostic.start !== undefined
18434             && diagnostic.length !== undefined
18435             && typeof diagnostic.fileName === "string";
18436     }
18437     function attachFileToDiagnostic(diagnostic, file) {
18438         var fileName = file.fileName || "";
18439         var length = file.text.length;
18440         ts.Debug.assertEqual(diagnostic.fileName, fileName);
18441         ts.Debug.assertLessThanOrEqual(diagnostic.start, length);
18442         ts.Debug.assertLessThanOrEqual(diagnostic.start + diagnostic.length, length);
18443         var diagnosticWithLocation = {
18444             file: file,
18445             start: diagnostic.start,
18446             length: diagnostic.length,
18447             messageText: diagnostic.messageText,
18448             category: diagnostic.category,
18449             code: diagnostic.code,
18450             reportsUnnecessary: diagnostic.reportsUnnecessary
18451         };
18452         if (diagnostic.relatedInformation) {
18453             diagnosticWithLocation.relatedInformation = [];
18454             for (var _i = 0, _a = diagnostic.relatedInformation; _i < _a.length; _i++) {
18455                 var related = _a[_i];
18456                 if (isDiagnosticWithDetachedLocation(related) && related.fileName === fileName) {
18457                     ts.Debug.assertLessThanOrEqual(related.start, length);
18458                     ts.Debug.assertLessThanOrEqual(related.start + related.length, length);
18459                     diagnosticWithLocation.relatedInformation.push(attachFileToDiagnostic(related, file));
18460                 }
18461                 else {
18462                     diagnosticWithLocation.relatedInformation.push(related);
18463                 }
18464             }
18465         }
18466         return diagnosticWithLocation;
18467     }
18468     function attachFileToDiagnostics(diagnostics, file) {
18469         var diagnosticsWithLocation = [];
18470         for (var _i = 0, diagnostics_1 = diagnostics; _i < diagnostics_1.length; _i++) {
18471             var diagnostic = diagnostics_1[_i];
18472             diagnosticsWithLocation.push(attachFileToDiagnostic(diagnostic, file));
18473         }
18474         return diagnosticsWithLocation;
18475     }
18476     ts.attachFileToDiagnostics = attachFileToDiagnostics;
18477     function createFileDiagnostic(file, start, length, message) {
18478         ts.Debug.assertGreaterThanOrEqual(start, 0);
18479         ts.Debug.assertGreaterThanOrEqual(length, 0);
18480         if (file) {
18481             ts.Debug.assertLessThanOrEqual(start, file.text.length);
18482             ts.Debug.assertLessThanOrEqual(start + length, file.text.length);
18483         }
18484         var text = getLocaleSpecificMessage(message);
18485         if (arguments.length > 4) {
18486             text = formatStringFromArgs(text, arguments, 4);
18487         }
18488         return {
18489             file: file,
18490             start: start,
18491             length: length,
18492             messageText: text,
18493             category: message.category,
18494             code: message.code,
18495             reportsUnnecessary: message.reportsUnnecessary,
18496             reportsDeprecated: message.reportsDeprecated
18497         };
18498     }
18499     ts.createFileDiagnostic = createFileDiagnostic;
18500     function formatMessage(_dummy, message) {
18501         var text = getLocaleSpecificMessage(message);
18502         if (arguments.length > 2) {
18503             text = formatStringFromArgs(text, arguments, 2);
18504         }
18505         return text;
18506     }
18507     ts.formatMessage = formatMessage;
18508     function createCompilerDiagnostic(message) {
18509         var text = getLocaleSpecificMessage(message);
18510         if (arguments.length > 1) {
18511             text = formatStringFromArgs(text, arguments, 1);
18512         }
18513         return {
18514             file: undefined,
18515             start: undefined,
18516             length: undefined,
18517             messageText: text,
18518             category: message.category,
18519             code: message.code,
18520             reportsUnnecessary: message.reportsUnnecessary,
18521             reportsDeprecated: message.reportsDeprecated
18522         };
18523     }
18524     ts.createCompilerDiagnostic = createCompilerDiagnostic;
18525     function createCompilerDiagnosticFromMessageChain(chain) {
18526         return {
18527             file: undefined,
18528             start: undefined,
18529             length: undefined,
18530             code: chain.code,
18531             category: chain.category,
18532             messageText: chain.next ? chain : chain.messageText,
18533         };
18534     }
18535     ts.createCompilerDiagnosticFromMessageChain = createCompilerDiagnosticFromMessageChain;
18536     function chainDiagnosticMessages(details, message) {
18537         var text = getLocaleSpecificMessage(message);
18538         if (arguments.length > 2) {
18539             text = formatStringFromArgs(text, arguments, 2);
18540         }
18541         return {
18542             messageText: text,
18543             category: message.category,
18544             code: message.code,
18545             next: details === undefined || Array.isArray(details) ? details : [details]
18546         };
18547     }
18548     ts.chainDiagnosticMessages = chainDiagnosticMessages;
18549     function concatenateDiagnosticMessageChains(headChain, tailChain) {
18550         var lastChain = headChain;
18551         while (lastChain.next) {
18552             lastChain = lastChain.next[0];
18553         }
18554         lastChain.next = [tailChain];
18555     }
18556     ts.concatenateDiagnosticMessageChains = concatenateDiagnosticMessageChains;
18557     function getDiagnosticFilePath(diagnostic) {
18558         return diagnostic.file ? diagnostic.file.path : undefined;
18559     }
18560     function compareDiagnostics(d1, d2) {
18561         return compareDiagnosticsSkipRelatedInformation(d1, d2) ||
18562             compareRelatedInformation(d1, d2) ||
18563             0 /* EqualTo */;
18564     }
18565     ts.compareDiagnostics = compareDiagnostics;
18566     function compareDiagnosticsSkipRelatedInformation(d1, d2) {
18567         return ts.compareStringsCaseSensitive(getDiagnosticFilePath(d1), getDiagnosticFilePath(d2)) ||
18568             ts.compareValues(d1.start, d2.start) ||
18569             ts.compareValues(d1.length, d2.length) ||
18570             ts.compareValues(d1.code, d2.code) ||
18571             compareMessageText(d1.messageText, d2.messageText) ||
18572             0 /* EqualTo */;
18573     }
18574     ts.compareDiagnosticsSkipRelatedInformation = compareDiagnosticsSkipRelatedInformation;
18575     function compareRelatedInformation(d1, d2) {
18576         if (!d1.relatedInformation && !d2.relatedInformation) {
18577             return 0 /* EqualTo */;
18578         }
18579         if (d1.relatedInformation && d2.relatedInformation) {
18580             return ts.compareValues(d1.relatedInformation.length, d2.relatedInformation.length) || ts.forEach(d1.relatedInformation, function (d1i, index) {
18581                 var d2i = d2.relatedInformation[index];
18582                 return compareDiagnostics(d1i, d2i); // EqualTo is 0, so falsy, and will cause the next item to be compared
18583             }) || 0 /* EqualTo */;
18584         }
18585         return d1.relatedInformation ? -1 /* LessThan */ : 1 /* GreaterThan */;
18586     }
18587     function compareMessageText(t1, t2) {
18588         if (typeof t1 === "string" && typeof t2 === "string") {
18589             return ts.compareStringsCaseSensitive(t1, t2);
18590         }
18591         else if (typeof t1 === "string") {
18592             return -1 /* LessThan */;
18593         }
18594         else if (typeof t2 === "string") {
18595             return 1 /* GreaterThan */;
18596         }
18597         var res = ts.compareStringsCaseSensitive(t1.messageText, t2.messageText);
18598         if (res) {
18599             return res;
18600         }
18601         if (!t1.next && !t2.next) {
18602             return 0 /* EqualTo */;
18603         }
18604         if (!t1.next) {
18605             return -1 /* LessThan */;
18606         }
18607         if (!t2.next) {
18608             return 1 /* GreaterThan */;
18609         }
18610         var len = Math.min(t1.next.length, t2.next.length);
18611         for (var i = 0; i < len; i++) {
18612             res = compareMessageText(t1.next[i], t2.next[i]);
18613             if (res) {
18614                 return res;
18615             }
18616         }
18617         if (t1.next.length < t2.next.length) {
18618             return -1 /* LessThan */;
18619         }
18620         else if (t1.next.length > t2.next.length) {
18621             return 1 /* GreaterThan */;
18622         }
18623         return 0 /* EqualTo */;
18624     }
18625     function getLanguageVariant(scriptKind) {
18626         // .tsx and .jsx files are treated as jsx language variant.
18627         return scriptKind === 4 /* TSX */ || scriptKind === 2 /* JSX */ || scriptKind === 1 /* JS */ || scriptKind === 6 /* JSON */ ? 1 /* JSX */ : 0 /* Standard */;
18628     }
18629     ts.getLanguageVariant = getLanguageVariant;
18630     function getEmitScriptTarget(compilerOptions) {
18631         return compilerOptions.target || 0 /* ES3 */;
18632     }
18633     ts.getEmitScriptTarget = getEmitScriptTarget;
18634     function getEmitModuleKind(compilerOptions) {
18635         return typeof compilerOptions.module === "number" ?
18636             compilerOptions.module :
18637             getEmitScriptTarget(compilerOptions) >= 2 /* ES2015 */ ? ts.ModuleKind.ES2015 : ts.ModuleKind.CommonJS;
18638     }
18639     ts.getEmitModuleKind = getEmitModuleKind;
18640     function getEmitModuleResolutionKind(compilerOptions) {
18641         var moduleResolution = compilerOptions.moduleResolution;
18642         if (moduleResolution === undefined) {
18643             moduleResolution = getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
18644         }
18645         return moduleResolution;
18646     }
18647     ts.getEmitModuleResolutionKind = getEmitModuleResolutionKind;
18648     function hasJsonModuleEmitEnabled(options) {
18649         switch (getEmitModuleKind(options)) {
18650             case ts.ModuleKind.CommonJS:
18651             case ts.ModuleKind.AMD:
18652             case ts.ModuleKind.ES2015:
18653             case ts.ModuleKind.ES2020:
18654             case ts.ModuleKind.ESNext:
18655                 return true;
18656             default:
18657                 return false;
18658         }
18659     }
18660     ts.hasJsonModuleEmitEnabled = hasJsonModuleEmitEnabled;
18661     function unreachableCodeIsError(options) {
18662         return options.allowUnreachableCode === false;
18663     }
18664     ts.unreachableCodeIsError = unreachableCodeIsError;
18665     function unusedLabelIsError(options) {
18666         return options.allowUnusedLabels === false;
18667     }
18668     ts.unusedLabelIsError = unusedLabelIsError;
18669     function getAreDeclarationMapsEnabled(options) {
18670         return !!(getEmitDeclarations(options) && options.declarationMap);
18671     }
18672     ts.getAreDeclarationMapsEnabled = getAreDeclarationMapsEnabled;
18673     function getAllowSyntheticDefaultImports(compilerOptions) {
18674         var moduleKind = getEmitModuleKind(compilerOptions);
18675         return compilerOptions.allowSyntheticDefaultImports !== undefined
18676             ? compilerOptions.allowSyntheticDefaultImports
18677             : compilerOptions.esModuleInterop ||
18678                 moduleKind === ts.ModuleKind.System;
18679     }
18680     ts.getAllowSyntheticDefaultImports = getAllowSyntheticDefaultImports;
18681     function getEmitDeclarations(compilerOptions) {
18682         return !!(compilerOptions.declaration || compilerOptions.composite);
18683     }
18684     ts.getEmitDeclarations = getEmitDeclarations;
18685     function isIncrementalCompilation(options) {
18686         return !!(options.incremental || options.composite);
18687     }
18688     ts.isIncrementalCompilation = isIncrementalCompilation;
18689     function getStrictOptionValue(compilerOptions, flag) {
18690         return compilerOptions[flag] === undefined ? !!compilerOptions.strict : !!compilerOptions[flag];
18691     }
18692     ts.getStrictOptionValue = getStrictOptionValue;
18693     function getAllowJSCompilerOption(compilerOptions) {
18694         return compilerOptions.allowJs === undefined ? !!compilerOptions.checkJs : compilerOptions.allowJs;
18695     }
18696     ts.getAllowJSCompilerOption = getAllowJSCompilerOption;
18697     function compilerOptionsAffectSemanticDiagnostics(newOptions, oldOptions) {
18698         return oldOptions !== newOptions &&
18699             ts.semanticDiagnosticsOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18700     }
18701     ts.compilerOptionsAffectSemanticDiagnostics = compilerOptionsAffectSemanticDiagnostics;
18702     function compilerOptionsAffectEmit(newOptions, oldOptions) {
18703         return oldOptions !== newOptions &&
18704             ts.affectsEmitOptionDeclarations.some(function (option) { return !isJsonEqual(getCompilerOptionValue(oldOptions, option), getCompilerOptionValue(newOptions, option)); });
18705     }
18706     ts.compilerOptionsAffectEmit = compilerOptionsAffectEmit;
18707     function getCompilerOptionValue(options, option) {
18708         return option.strictFlag ? getStrictOptionValue(options, option.name) : options[option.name];
18709     }
18710     ts.getCompilerOptionValue = getCompilerOptionValue;
18711     function getJSXTransformEnabled(options) {
18712         var jsx = options.jsx;
18713         return jsx === 2 /* React */ || jsx === 4 /* ReactJSX */ || jsx === 5 /* ReactJSXDev */;
18714     }
18715     ts.getJSXTransformEnabled = getJSXTransformEnabled;
18716     function getJSXImplicitImportBase(compilerOptions, file) {
18717         var jsxImportSourcePragmas = file === null || file === void 0 ? void 0 : file.pragmas.get("jsximportsource");
18718         var jsxImportSourcePragma = ts.isArray(jsxImportSourcePragmas) ? jsxImportSourcePragmas[0] : jsxImportSourcePragmas;
18719         return compilerOptions.jsx === 4 /* ReactJSX */ ||
18720             compilerOptions.jsx === 5 /* ReactJSXDev */ ||
18721             compilerOptions.jsxImportSource ||
18722             jsxImportSourcePragma ?
18723             (jsxImportSourcePragma === null || jsxImportSourcePragma === void 0 ? void 0 : jsxImportSourcePragma.arguments.factory) || compilerOptions.jsxImportSource || "react" :
18724             undefined;
18725     }
18726     ts.getJSXImplicitImportBase = getJSXImplicitImportBase;
18727     function getJSXRuntimeImport(base, options) {
18728         return base ? base + "/" + (options.jsx === 5 /* ReactJSXDev */ ? "jsx-dev-runtime" : "jsx-runtime") : undefined;
18729     }
18730     ts.getJSXRuntimeImport = getJSXRuntimeImport;
18731     function hasZeroOrOneAsteriskCharacter(str) {
18732         var seenAsterisk = false;
18733         for (var i = 0; i < str.length; i++) {
18734             if (str.charCodeAt(i) === 42 /* asterisk */) {
18735                 if (!seenAsterisk) {
18736                     seenAsterisk = true;
18737                 }
18738                 else {
18739                     // have already seen asterisk
18740                     return false;
18741                 }
18742             }
18743         }
18744         return true;
18745     }
18746     ts.hasZeroOrOneAsteriskCharacter = hasZeroOrOneAsteriskCharacter;
18747     function createSymlinkCache() {
18748         var symlinkedDirectories;
18749         var symlinkedFiles;
18750         return {
18751             getSymlinkedFiles: function () { return symlinkedFiles; },
18752             getSymlinkedDirectories: function () { return symlinkedDirectories; },
18753             setSymlinkedFile: function (path, real) { return (symlinkedFiles || (symlinkedFiles = new ts.Map())).set(path, real); },
18754             setSymlinkedDirectory: function (path, directory) { return (symlinkedDirectories || (symlinkedDirectories = new ts.Map())).set(path, directory); },
18755         };
18756     }
18757     ts.createSymlinkCache = createSymlinkCache;
18758     function discoverProbableSymlinks(files, getCanonicalFileName, cwd) {
18759         var cache = createSymlinkCache();
18760         var symlinks = ts.flatten(ts.mapDefined(files, function (sf) {
18761             return sf.resolvedModules && ts.compact(ts.arrayFrom(ts.mapIterator(sf.resolvedModules.values(), function (res) {
18762                 return res && res.originalPath && res.resolvedFileName !== res.originalPath ? [res.resolvedFileName, res.originalPath] : undefined;
18763             })));
18764         }));
18765         for (var _i = 0, symlinks_1 = symlinks; _i < symlinks_1.length; _i++) {
18766             var _a = symlinks_1[_i], resolvedPath = _a[0], originalPath = _a[1];
18767             var _b = guessDirectorySymlink(resolvedPath, originalPath, cwd, getCanonicalFileName) || ts.emptyArray, commonResolved = _b[0], commonOriginal = _b[1];
18768             if (commonResolved && commonOriginal) {
18769                 cache.setSymlinkedDirectory(ts.toPath(commonOriginal, cwd, getCanonicalFileName), { real: commonResolved, realPath: ts.toPath(commonResolved, cwd, getCanonicalFileName) });
18770             }
18771         }
18772         return cache;
18773     }
18774     ts.discoverProbableSymlinks = discoverProbableSymlinks;
18775     function guessDirectorySymlink(a, b, cwd, getCanonicalFileName) {
18776         var aParts = ts.getPathComponents(ts.toPath(a, cwd, getCanonicalFileName));
18777         var bParts = ts.getPathComponents(ts.toPath(b, cwd, getCanonicalFileName));
18778         var isDirectory = false;
18779         while (!isNodeModulesOrScopedPackageDirectory(aParts[aParts.length - 2], getCanonicalFileName) &&
18780             !isNodeModulesOrScopedPackageDirectory(bParts[bParts.length - 2], getCanonicalFileName) &&
18781             getCanonicalFileName(aParts[aParts.length - 1]) === getCanonicalFileName(bParts[bParts.length - 1])) {
18782             aParts.pop();
18783             bParts.pop();
18784             isDirectory = true;
18785         }
18786         return isDirectory ? [ts.getPathFromPathComponents(aParts), ts.getPathFromPathComponents(bParts)] : undefined;
18787     }
18788     // KLUDGE: Don't assume one 'node_modules' links to another. More likely a single directory inside the node_modules is the symlink.
18789     // ALso, don't assume that an `@foo` directory is linked. More likely the contents of that are linked.
18790     function isNodeModulesOrScopedPackageDirectory(s, getCanonicalFileName) {
18791         return getCanonicalFileName(s) === "node_modules" || ts.startsWith(s, "@");
18792     }
18793     function stripLeadingDirectorySeparator(s) {
18794         return ts.isAnyDirectorySeparator(s.charCodeAt(0)) ? s.slice(1) : undefined;
18795     }
18796     function tryRemoveDirectoryPrefix(path, dirPath, getCanonicalFileName) {
18797         var withoutPrefix = ts.tryRemovePrefix(path, dirPath, getCanonicalFileName);
18798         return withoutPrefix === undefined ? undefined : stripLeadingDirectorySeparator(withoutPrefix);
18799     }
18800     ts.tryRemoveDirectoryPrefix = tryRemoveDirectoryPrefix;
18801     // Reserved characters, forces escaping of any non-word (or digit), non-whitespace character.
18802     // It may be inefficient (we could just match (/[-[\]{}()*+?.,\\^$|#\s]/g), but this is future
18803     // proof.
18804     var reservedCharacterPattern = /[^\w\s\/]/g;
18805     function regExpEscape(text) {
18806         return text.replace(reservedCharacterPattern, escapeRegExpCharacter);
18807     }
18808     ts.regExpEscape = regExpEscape;
18809     function escapeRegExpCharacter(match) {
18810         return "\\" + match;
18811     }
18812     var wildcardCharCodes = [42 /* asterisk */, 63 /* question */];
18813     ts.commonPackageFolders = ["node_modules", "bower_components", "jspm_packages"];
18814     var implicitExcludePathRegexPattern = "(?!(" + ts.commonPackageFolders.join("|") + ")(/|$))";
18815     var filesMatcher = {
18816         /**
18817          * Matches any single directory segment unless it is the last segment and a .min.js file
18818          * Breakdown:
18819          *  [^./]                   # matches everything up to the first . character (excluding directory separators)
18820          *  (\\.(?!min\\.js$))?     # matches . characters but not if they are part of the .min.js file extension
18821          */
18822         singleAsteriskRegexFragment: "([^./]|(\\.(?!min\\.js$))?)*",
18823         /**
18824          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18825          * files or directories, does not match subdirectories that start with a . character
18826          */
18827         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18828         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, filesMatcher.singleAsteriskRegexFragment); }
18829     };
18830     var directoriesMatcher = {
18831         singleAsteriskRegexFragment: "[^/]*",
18832         /**
18833          * Regex for the ** wildcard. Matches any number of subdirectories. When used for including
18834          * files or directories, does not match subdirectories that start with a . character
18835          */
18836         doubleAsteriskRegexFragment: "(/" + implicitExcludePathRegexPattern + "[^/.][^/]*)*?",
18837         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, directoriesMatcher.singleAsteriskRegexFragment); }
18838     };
18839     var excludeMatcher = {
18840         singleAsteriskRegexFragment: "[^/]*",
18841         doubleAsteriskRegexFragment: "(/.+?)?",
18842         replaceWildcardCharacter: function (match) { return replaceWildcardCharacter(match, excludeMatcher.singleAsteriskRegexFragment); }
18843     };
18844     var wildcardMatchers = {
18845         files: filesMatcher,
18846         directories: directoriesMatcher,
18847         exclude: excludeMatcher
18848     };
18849     function getRegularExpressionForWildcard(specs, basePath, usage) {
18850         var patterns = getRegularExpressionsForWildcards(specs, basePath, usage);
18851         if (!patterns || !patterns.length) {
18852             return undefined;
18853         }
18854         var pattern = patterns.map(function (pattern) { return "(" + pattern + ")"; }).join("|");
18855         // If excluding, match "foo/bar/baz...", but if including, only allow "foo".
18856         var terminator = usage === "exclude" ? "($|/)" : "$";
18857         return "^(" + pattern + ")" + terminator;
18858     }
18859     ts.getRegularExpressionForWildcard = getRegularExpressionForWildcard;
18860     function getRegularExpressionsForWildcards(specs, basePath, usage) {
18861         if (specs === undefined || specs.length === 0) {
18862             return undefined;
18863         }
18864         return ts.flatMap(specs, function (spec) {
18865             return spec && getSubPatternFromSpec(spec, basePath, usage, wildcardMatchers[usage]);
18866         });
18867     }
18868     ts.getRegularExpressionsForWildcards = getRegularExpressionsForWildcards;
18869     /**
18870      * An "includes" path "foo" is implicitly a glob "foo/** /*" (without the space) if its last component has no extension,
18871      * and does not contain any glob characters itself.
18872      */
18873     function isImplicitGlob(lastPathComponent) {
18874         return !/[.*?]/.test(lastPathComponent);
18875     }
18876     ts.isImplicitGlob = isImplicitGlob;
18877     function getSubPatternFromSpec(spec, basePath, usage, _a) {
18878         var singleAsteriskRegexFragment = _a.singleAsteriskRegexFragment, doubleAsteriskRegexFragment = _a.doubleAsteriskRegexFragment, replaceWildcardCharacter = _a.replaceWildcardCharacter;
18879         var subpattern = "";
18880         var hasWrittenComponent = false;
18881         var components = ts.getNormalizedPathComponents(spec, basePath);
18882         var lastComponent = ts.last(components);
18883         if (usage !== "exclude" && lastComponent === "**") {
18884             return undefined;
18885         }
18886         // getNormalizedPathComponents includes the separator for the root component.
18887         // We need to remove to create our regex correctly.
18888         components[0] = ts.removeTrailingDirectorySeparator(components[0]);
18889         if (isImplicitGlob(lastComponent)) {
18890             components.push("**", "*");
18891         }
18892         var optionalCount = 0;
18893         for (var _i = 0, components_1 = components; _i < components_1.length; _i++) {
18894             var component = components_1[_i];
18895             if (component === "**") {
18896                 subpattern += doubleAsteriskRegexFragment;
18897             }
18898             else {
18899                 if (usage === "directories") {
18900                     subpattern += "(";
18901                     optionalCount++;
18902                 }
18903                 if (hasWrittenComponent) {
18904                     subpattern += ts.directorySeparator;
18905                 }
18906                 if (usage !== "exclude") {
18907                     var componentPattern = "";
18908                     // The * and ? wildcards should not match directories or files that start with . if they
18909                     // appear first in a component. Dotted directories and files can be included explicitly
18910                     // like so: **/.*/.*
18911                     if (component.charCodeAt(0) === 42 /* asterisk */) {
18912                         componentPattern += "([^./]" + singleAsteriskRegexFragment + ")?";
18913                         component = component.substr(1);
18914                     }
18915                     else if (component.charCodeAt(0) === 63 /* question */) {
18916                         componentPattern += "[^./]";
18917                         component = component.substr(1);
18918                     }
18919                     componentPattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18920                     // Patterns should not include subfolders like node_modules unless they are
18921                     // explicitly included as part of the path.
18922                     //
18923                     // As an optimization, if the component pattern is the same as the component,
18924                     // then there definitely were no wildcard characters and we do not need to
18925                     // add the exclusion pattern.
18926                     if (componentPattern !== component) {
18927                         subpattern += implicitExcludePathRegexPattern;
18928                     }
18929                     subpattern += componentPattern;
18930                 }
18931                 else {
18932                     subpattern += component.replace(reservedCharacterPattern, replaceWildcardCharacter);
18933                 }
18934             }
18935             hasWrittenComponent = true;
18936         }
18937         while (optionalCount > 0) {
18938             subpattern += ")?";
18939             optionalCount--;
18940         }
18941         return subpattern;
18942     }
18943     function replaceWildcardCharacter(match, singleAsteriskRegexFragment) {
18944         return match === "*" ? singleAsteriskRegexFragment : match === "?" ? "[^/]" : "\\" + match;
18945     }
18946     /** @param path directory of the tsconfig.json */
18947     function getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory) {
18948         path = ts.normalizePath(path);
18949         currentDirectory = ts.normalizePath(currentDirectory);
18950         var absolutePath = ts.combinePaths(currentDirectory, path);
18951         return {
18952             includeFilePatterns: ts.map(getRegularExpressionsForWildcards(includes, absolutePath, "files"), function (pattern) { return "^" + pattern + "$"; }),
18953             includeFilePattern: getRegularExpressionForWildcard(includes, absolutePath, "files"),
18954             includeDirectoryPattern: getRegularExpressionForWildcard(includes, absolutePath, "directories"),
18955             excludePattern: getRegularExpressionForWildcard(excludes, absolutePath, "exclude"),
18956             basePaths: getBasePaths(path, includes, useCaseSensitiveFileNames)
18957         };
18958     }
18959     ts.getFileMatcherPatterns = getFileMatcherPatterns;
18960     function getRegexFromPattern(pattern, useCaseSensitiveFileNames) {
18961         return new RegExp(pattern, useCaseSensitiveFileNames ? "" : "i");
18962     }
18963     ts.getRegexFromPattern = getRegexFromPattern;
18964     /** @param path directory of the tsconfig.json */
18965     function matchFiles(path, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath) {
18966         path = ts.normalizePath(path);
18967         currentDirectory = ts.normalizePath(currentDirectory);
18968         var patterns = getFileMatcherPatterns(path, excludes, includes, useCaseSensitiveFileNames, currentDirectory);
18969         var includeFileRegexes = patterns.includeFilePatterns && patterns.includeFilePatterns.map(function (pattern) { return getRegexFromPattern(pattern, useCaseSensitiveFileNames); });
18970         var includeDirectoryRegex = patterns.includeDirectoryPattern && getRegexFromPattern(patterns.includeDirectoryPattern, useCaseSensitiveFileNames);
18971         var excludeRegex = patterns.excludePattern && getRegexFromPattern(patterns.excludePattern, useCaseSensitiveFileNames);
18972         // Associate an array of results with each include regex. This keeps results in order of the "include" order.
18973         // If there are no "includes", then just put everything in results[0].
18974         var results = includeFileRegexes ? includeFileRegexes.map(function () { return []; }) : [[]];
18975         var visited = new ts.Map();
18976         var toCanonical = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
18977         for (var _i = 0, _a = patterns.basePaths; _i < _a.length; _i++) {
18978             var basePath = _a[_i];
18979             visitDirectory(basePath, ts.combinePaths(currentDirectory, basePath), depth);
18980         }
18981         return ts.flatten(results);
18982         function visitDirectory(path, absolutePath, depth) {
18983             var canonicalPath = toCanonical(realpath(absolutePath));
18984             if (visited.has(canonicalPath))
18985                 return;
18986             visited.set(canonicalPath, true);
18987             var _a = getFileSystemEntries(path), files = _a.files, directories = _a.directories;
18988             var _loop_1 = function (current) {
18989                 var name = ts.combinePaths(path, current);
18990                 var absoluteName = ts.combinePaths(absolutePath, current);
18991                 if (extensions && !ts.fileExtensionIsOneOf(name, extensions))
18992                     return "continue";
18993                 if (excludeRegex && excludeRegex.test(absoluteName))
18994                     return "continue";
18995                 if (!includeFileRegexes) {
18996                     results[0].push(name);
18997                 }
18998                 else {
18999                     var includeIndex = ts.findIndex(includeFileRegexes, function (re) { return re.test(absoluteName); });
19000                     if (includeIndex !== -1) {
19001                         results[includeIndex].push(name);
19002                     }
19003                 }
19004             };
19005             for (var _i = 0, _b = ts.sort(files, ts.compareStringsCaseSensitive); _i < _b.length; _i++) {
19006                 var current = _b[_i];
19007                 _loop_1(current);
19008             }
19009             if (depth !== undefined) {
19010                 depth--;
19011                 if (depth === 0) {
19012                     return;
19013                 }
19014             }
19015             for (var _c = 0, _d = ts.sort(directories, ts.compareStringsCaseSensitive); _c < _d.length; _c++) {
19016                 var current = _d[_c];
19017                 var name = ts.combinePaths(path, current);
19018                 var absoluteName = ts.combinePaths(absolutePath, current);
19019                 if ((!includeDirectoryRegex || includeDirectoryRegex.test(absoluteName)) &&
19020                     (!excludeRegex || !excludeRegex.test(absoluteName))) {
19021                     visitDirectory(name, absoluteName, depth);
19022                 }
19023             }
19024         }
19025     }
19026     ts.matchFiles = matchFiles;
19027     /**
19028      * Computes the unique non-wildcard base paths amongst the provided include patterns.
19029      */
19030     function getBasePaths(path, includes, useCaseSensitiveFileNames) {
19031         // Storage for our results in the form of literal paths (e.g. the paths as written by the user).
19032         var basePaths = [path];
19033         if (includes) {
19034             // Storage for literal base paths amongst the include patterns.
19035             var includeBasePaths = [];
19036             for (var _i = 0, includes_1 = includes; _i < includes_1.length; _i++) {
19037                 var include = includes_1[_i];
19038                 // We also need to check the relative paths by converting them to absolute and normalizing
19039                 // in case they escape the base path (e.g "..\somedirectory")
19040                 var absolute = ts.isRootedDiskPath(include) ? include : ts.normalizePath(ts.combinePaths(path, include));
19041                 // Append the literal and canonical candidate base paths.
19042                 includeBasePaths.push(getIncludeBasePath(absolute));
19043             }
19044             // Sort the offsets array using either the literal or canonical path representations.
19045             includeBasePaths.sort(ts.getStringComparer(!useCaseSensitiveFileNames));
19046             var _loop_2 = function (includeBasePath) {
19047                 if (ts.every(basePaths, function (basePath) { return !ts.containsPath(basePath, includeBasePath, path, !useCaseSensitiveFileNames); })) {
19048                     basePaths.push(includeBasePath);
19049                 }
19050             };
19051             // Iterate over each include base path and include unique base paths that are not a
19052             // subpath of an existing base path
19053             for (var _a = 0, includeBasePaths_1 = includeBasePaths; _a < includeBasePaths_1.length; _a++) {
19054                 var includeBasePath = includeBasePaths_1[_a];
19055                 _loop_2(includeBasePath);
19056             }
19057         }
19058         return basePaths;
19059     }
19060     function getIncludeBasePath(absolute) {
19061         var wildcardOffset = ts.indexOfAnyCharCode(absolute, wildcardCharCodes);
19062         if (wildcardOffset < 0) {
19063             // No "*" or "?" in the path
19064             return !ts.hasExtension(absolute)
19065                 ? absolute
19066                 : ts.removeTrailingDirectorySeparator(ts.getDirectoryPath(absolute));
19067         }
19068         return absolute.substring(0, absolute.lastIndexOf(ts.directorySeparator, wildcardOffset));
19069     }
19070     function ensureScriptKind(fileName, scriptKind) {
19071         // Using scriptKind as a condition handles both:
19072         // - 'scriptKind' is unspecified and thus it is `undefined`
19073         // - 'scriptKind' is set and it is `Unknown` (0)
19074         // If the 'scriptKind' is 'undefined' or 'Unknown' then we attempt
19075         // to get the ScriptKind from the file name. If it cannot be resolved
19076         // from the file name then the default 'TS' script kind is returned.
19077         return scriptKind || getScriptKindFromFileName(fileName) || 3 /* TS */;
19078     }
19079     ts.ensureScriptKind = ensureScriptKind;
19080     function getScriptKindFromFileName(fileName) {
19081         var ext = fileName.substr(fileName.lastIndexOf("."));
19082         switch (ext.toLowerCase()) {
19083             case ".js" /* Js */:
19084                 return 1 /* JS */;
19085             case ".jsx" /* Jsx */:
19086                 return 2 /* JSX */;
19087             case ".ts" /* Ts */:
19088                 return 3 /* TS */;
19089             case ".tsx" /* Tsx */:
19090                 return 4 /* TSX */;
19091             case ".json" /* Json */:
19092                 return 6 /* JSON */;
19093             default:
19094                 return 0 /* Unknown */;
19095         }
19096     }
19097     ts.getScriptKindFromFileName = getScriptKindFromFileName;
19098     /**
19099      *  List of supported extensions in order of file resolution precedence.
19100      */
19101     ts.supportedTSExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */];
19102     ts.supportedTSExtensionsWithJson = [".ts" /* Ts */, ".tsx" /* Tsx */, ".d.ts" /* Dts */, ".json" /* Json */];
19103     /** Must have ".d.ts" first because if ".ts" goes first, that will be detected as the extension instead of ".d.ts". */
19104     ts.supportedTSExtensionsForExtractExtension = [".d.ts" /* Dts */, ".ts" /* Ts */, ".tsx" /* Tsx */];
19105     ts.supportedJSExtensions = [".js" /* Js */, ".jsx" /* Jsx */];
19106     ts.supportedJSAndJsonExtensions = [".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
19107     var allSupportedExtensions = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions);
19108     var allSupportedExtensionsWithJson = __spreadArrays(ts.supportedTSExtensions, ts.supportedJSExtensions, [".json" /* Json */]);
19109     function getSupportedExtensions(options, extraFileExtensions) {
19110         var needJsExtensions = options && getAllowJSCompilerOption(options);
19111         if (!extraFileExtensions || extraFileExtensions.length === 0) {
19112             return needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions;
19113         }
19114         var extensions = __spreadArrays(needJsExtensions ? allSupportedExtensions : ts.supportedTSExtensions, ts.mapDefined(extraFileExtensions, function (x) { return x.scriptKind === 7 /* Deferred */ || needJsExtensions && isJSLike(x.scriptKind) ? x.extension : undefined; }));
19115         return ts.deduplicate(extensions, ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
19116     }
19117     ts.getSupportedExtensions = getSupportedExtensions;
19118     function getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions) {
19119         if (!options || !options.resolveJsonModule) {
19120             return supportedExtensions;
19121         }
19122         if (supportedExtensions === allSupportedExtensions) {
19123             return allSupportedExtensionsWithJson;
19124         }
19125         if (supportedExtensions === ts.supportedTSExtensions) {
19126             return ts.supportedTSExtensionsWithJson;
19127         }
19128         return __spreadArrays(supportedExtensions, [".json" /* Json */]);
19129     }
19130     ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule = getSuppoertedExtensionsWithJsonIfResolveJsonModule;
19131     function isJSLike(scriptKind) {
19132         return scriptKind === 1 /* JS */ || scriptKind === 2 /* JSX */;
19133     }
19134     function hasJSFileExtension(fileName) {
19135         return ts.some(ts.supportedJSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
19136     }
19137     ts.hasJSFileExtension = hasJSFileExtension;
19138     function hasTSFileExtension(fileName) {
19139         return ts.some(ts.supportedTSExtensions, function (extension) { return ts.fileExtensionIs(fileName, extension); });
19140     }
19141     ts.hasTSFileExtension = hasTSFileExtension;
19142     function isSupportedSourceFileName(fileName, compilerOptions, extraFileExtensions) {
19143         if (!fileName) {
19144             return false;
19145         }
19146         var supportedExtensions = getSupportedExtensions(compilerOptions, extraFileExtensions);
19147         for (var _i = 0, _a = getSuppoertedExtensionsWithJsonIfResolveJsonModule(compilerOptions, supportedExtensions); _i < _a.length; _i++) {
19148             var extension = _a[_i];
19149             if (ts.fileExtensionIs(fileName, extension)) {
19150                 return true;
19151             }
19152         }
19153         return false;
19154     }
19155     ts.isSupportedSourceFileName = isSupportedSourceFileName;
19156     /**
19157      * Extension boundaries by priority. Lower numbers indicate higher priorities, and are
19158      * aligned to the offset of the highest priority extension in the
19159      * allSupportedExtensions array.
19160      */
19161     var ExtensionPriority;
19162     (function (ExtensionPriority) {
19163         ExtensionPriority[ExtensionPriority["TypeScriptFiles"] = 0] = "TypeScriptFiles";
19164         ExtensionPriority[ExtensionPriority["DeclarationAndJavaScriptFiles"] = 2] = "DeclarationAndJavaScriptFiles";
19165         ExtensionPriority[ExtensionPriority["Highest"] = 0] = "Highest";
19166         ExtensionPriority[ExtensionPriority["Lowest"] = 2] = "Lowest";
19167     })(ExtensionPriority = ts.ExtensionPriority || (ts.ExtensionPriority = {}));
19168     function getExtensionPriority(path, supportedExtensions) {
19169         for (var i = supportedExtensions.length - 1; i >= 0; i--) {
19170             if (ts.fileExtensionIs(path, supportedExtensions[i])) {
19171                 return adjustExtensionPriority(i, supportedExtensions);
19172             }
19173         }
19174         // If its not in the list of supported extensions, this is likely a
19175         // TypeScript file with a non-ts extension
19176         return 0 /* Highest */;
19177     }
19178     ts.getExtensionPriority = getExtensionPriority;
19179     /**
19180      * Adjusts an extension priority to be the highest priority within the same range.
19181      */
19182     function adjustExtensionPriority(extensionPriority, supportedExtensions) {
19183         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
19184             return 0 /* TypeScriptFiles */;
19185         }
19186         else if (extensionPriority < supportedExtensions.length) {
19187             return 2 /* DeclarationAndJavaScriptFiles */;
19188         }
19189         else {
19190             return supportedExtensions.length;
19191         }
19192     }
19193     ts.adjustExtensionPriority = adjustExtensionPriority;
19194     /**
19195      * Gets the next lowest extension priority for a given priority.
19196      */
19197     function getNextLowestExtensionPriority(extensionPriority, supportedExtensions) {
19198         if (extensionPriority < 2 /* DeclarationAndJavaScriptFiles */) {
19199             return 2 /* DeclarationAndJavaScriptFiles */;
19200         }
19201         else {
19202             return supportedExtensions.length;
19203         }
19204     }
19205     ts.getNextLowestExtensionPriority = getNextLowestExtensionPriority;
19206     var extensionsToRemove = [".d.ts" /* Dts */, ".ts" /* Ts */, ".js" /* Js */, ".tsx" /* Tsx */, ".jsx" /* Jsx */, ".json" /* Json */];
19207     function removeFileExtension(path) {
19208         for (var _i = 0, extensionsToRemove_1 = extensionsToRemove; _i < extensionsToRemove_1.length; _i++) {
19209             var ext = extensionsToRemove_1[_i];
19210             var extensionless = tryRemoveExtension(path, ext);
19211             if (extensionless !== undefined) {
19212                 return extensionless;
19213             }
19214         }
19215         return path;
19216     }
19217     ts.removeFileExtension = removeFileExtension;
19218     function tryRemoveExtension(path, extension) {
19219         return ts.fileExtensionIs(path, extension) ? removeExtension(path, extension) : undefined;
19220     }
19221     ts.tryRemoveExtension = tryRemoveExtension;
19222     function removeExtension(path, extension) {
19223         return path.substring(0, path.length - extension.length);
19224     }
19225     ts.removeExtension = removeExtension;
19226     function changeExtension(path, newExtension) {
19227         return ts.changeAnyExtension(path, newExtension, extensionsToRemove, /*ignoreCase*/ false);
19228     }
19229     ts.changeExtension = changeExtension;
19230     function tryParsePattern(pattern) {
19231         // This should be verified outside of here and a proper error thrown.
19232         ts.Debug.assert(hasZeroOrOneAsteriskCharacter(pattern));
19233         var indexOfStar = pattern.indexOf("*");
19234         return indexOfStar === -1 ? undefined : {
19235             prefix: pattern.substr(0, indexOfStar),
19236             suffix: pattern.substr(indexOfStar + 1)
19237         };
19238     }
19239     ts.tryParsePattern = tryParsePattern;
19240     function positionIsSynthesized(pos) {
19241         // This is a fast way of testing the following conditions:
19242         //  pos === undefined || pos === null || isNaN(pos) || pos < 0;
19243         return !(pos >= 0);
19244     }
19245     ts.positionIsSynthesized = positionIsSynthesized;
19246     /** True if an extension is one of the supported TypeScript extensions. */
19247     function extensionIsTS(ext) {
19248         return ext === ".ts" /* Ts */ || ext === ".tsx" /* Tsx */ || ext === ".d.ts" /* Dts */;
19249     }
19250     ts.extensionIsTS = extensionIsTS;
19251     function resolutionExtensionIsTSOrJson(ext) {
19252         return extensionIsTS(ext) || ext === ".json" /* Json */;
19253     }
19254     ts.resolutionExtensionIsTSOrJson = resolutionExtensionIsTSOrJson;
19255     /**
19256      * Gets the extension from a path.
19257      * Path must have a valid extension.
19258      */
19259     function extensionFromPath(path) {
19260         var ext = tryGetExtensionFromPath(path);
19261         return ext !== undefined ? ext : ts.Debug.fail("File " + path + " has unknown extension.");
19262     }
19263     ts.extensionFromPath = extensionFromPath;
19264     function isAnySupportedFileExtension(path) {
19265         return tryGetExtensionFromPath(path) !== undefined;
19266     }
19267     ts.isAnySupportedFileExtension = isAnySupportedFileExtension;
19268     function tryGetExtensionFromPath(path) {
19269         return ts.find(extensionsToRemove, function (e) { return ts.fileExtensionIs(path, e); });
19270     }
19271     ts.tryGetExtensionFromPath = tryGetExtensionFromPath;
19272     function isCheckJsEnabledForFile(sourceFile, compilerOptions) {
19273         return sourceFile.checkJsDirective ? sourceFile.checkJsDirective.enabled : compilerOptions.checkJs;
19274     }
19275     ts.isCheckJsEnabledForFile = isCheckJsEnabledForFile;
19276     ts.emptyFileSystemEntries = {
19277         files: ts.emptyArray,
19278         directories: ts.emptyArray
19279     };
19280     /**
19281      * patternStrings contains both pattern strings (containing "*") and regular strings.
19282      * Return an exact match if possible, or a pattern match, or undefined.
19283      * (These are verified by verifyCompilerOptions to have 0 or 1 "*" characters.)
19284      */
19285     function matchPatternOrExact(patternStrings, candidate) {
19286         var patterns = [];
19287         for (var _i = 0, patternStrings_1 = patternStrings; _i < patternStrings_1.length; _i++) {
19288             var patternString = patternStrings_1[_i];
19289             if (!hasZeroOrOneAsteriskCharacter(patternString))
19290                 continue;
19291             var pattern = tryParsePattern(patternString);
19292             if (pattern) {
19293                 patterns.push(pattern);
19294             }
19295             else if (patternString === candidate) {
19296                 // pattern was matched as is - no need to search further
19297                 return patternString;
19298             }
19299         }
19300         return ts.findBestPatternMatch(patterns, function (_) { return _; }, candidate);
19301     }
19302     ts.matchPatternOrExact = matchPatternOrExact;
19303     function sliceAfter(arr, value) {
19304         var index = arr.indexOf(value);
19305         ts.Debug.assert(index !== -1);
19306         return arr.slice(index);
19307     }
19308     ts.sliceAfter = sliceAfter;
19309     function addRelatedInfo(diagnostic) {
19310         var _a;
19311         var relatedInformation = [];
19312         for (var _i = 1; _i < arguments.length; _i++) {
19313             relatedInformation[_i - 1] = arguments[_i];
19314         }
19315         if (!relatedInformation.length) {
19316             return diagnostic;
19317         }
19318         if (!diagnostic.relatedInformation) {
19319             diagnostic.relatedInformation = [];
19320         }
19321         ts.Debug.assert(diagnostic.relatedInformation !== ts.emptyArray, "Diagnostic had empty array singleton for related info, but is still being constructed!");
19322         (_a = diagnostic.relatedInformation).push.apply(_a, relatedInformation);
19323         return diagnostic;
19324     }
19325     ts.addRelatedInfo = addRelatedInfo;
19326     function minAndMax(arr, getValue) {
19327         ts.Debug.assert(arr.length !== 0);
19328         var min = getValue(arr[0]);
19329         var max = min;
19330         for (var i = 1; i < arr.length; i++) {
19331             var value = getValue(arr[i]);
19332             if (value < min) {
19333                 min = value;
19334             }
19335             else if (value > max) {
19336                 max = value;
19337             }
19338         }
19339         return { min: min, max: max };
19340     }
19341     ts.minAndMax = minAndMax;
19342     function rangeOfNode(node) {
19343         return { pos: getTokenPosOfNode(node), end: node.end };
19344     }
19345     ts.rangeOfNode = rangeOfNode;
19346     function rangeOfTypeParameters(typeParameters) {
19347         // Include the `<>`
19348         return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
19349     }
19350     ts.rangeOfTypeParameters = rangeOfTypeParameters;
19351     function skipTypeChecking(sourceFile, options, host) {
19352         // If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
19353         // If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
19354         // '/// <reference no-default-lib="true"/>' directive.
19355         return (options.skipLibCheck && sourceFile.isDeclarationFile ||
19356             options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
19357             host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
19358     }
19359     ts.skipTypeChecking = skipTypeChecking;
19360     function isJsonEqual(a, b) {
19361         // eslint-disable-next-line no-null/no-null
19362         return a === b || typeof a === "object" && a !== null && typeof b === "object" && b !== null && ts.equalOwnProperties(a, b, isJsonEqual);
19363     }
19364     ts.isJsonEqual = isJsonEqual;
19365     /**
19366      * Converts a bigint literal string, e.g. `0x1234n`,
19367      * to its decimal string representation, e.g. `4660`.
19368      */
19369     function parsePseudoBigInt(stringValue) {
19370         var log2Base;
19371         switch (stringValue.charCodeAt(1)) { // "x" in "0x123"
19372             case 98 /* b */:
19373             case 66 /* B */: // 0b or 0B
19374                 log2Base = 1;
19375                 break;
19376             case 111 /* o */:
19377             case 79 /* O */: // 0o or 0O
19378                 log2Base = 3;
19379                 break;
19380             case 120 /* x */:
19381             case 88 /* X */: // 0x or 0X
19382                 log2Base = 4;
19383                 break;
19384             default: // already in decimal; omit trailing "n"
19385                 var nIndex = stringValue.length - 1;
19386                 // Skip leading 0s
19387                 var nonZeroStart = 0;
19388                 while (stringValue.charCodeAt(nonZeroStart) === 48 /* _0 */) {
19389                     nonZeroStart++;
19390                 }
19391                 return stringValue.slice(nonZeroStart, nIndex) || "0";
19392         }
19393         // Omit leading "0b", "0o", or "0x", and trailing "n"
19394         var startIndex = 2, endIndex = stringValue.length - 1;
19395         var bitsNeeded = (endIndex - startIndex) * log2Base;
19396         // Stores the value specified by the string as a LE array of 16-bit integers
19397         // using Uint16 instead of Uint32 so combining steps can use bitwise operators
19398         var segments = new Uint16Array((bitsNeeded >>> 4) + (bitsNeeded & 15 ? 1 : 0));
19399         // Add the digits, one at a time
19400         for (var i = endIndex - 1, bitOffset = 0; i >= startIndex; i--, bitOffset += log2Base) {
19401             var segment = bitOffset >>> 4;
19402             var digitChar = stringValue.charCodeAt(i);
19403             // Find character range: 0-9 < A-F < a-f
19404             var digit = digitChar <= 57 /* _9 */
19405                 ? digitChar - 48 /* _0 */
19406                 : 10 + digitChar -
19407                     (digitChar <= 70 /* F */ ? 65 /* A */ : 97 /* a */);
19408             var shiftedDigit = digit << (bitOffset & 15);
19409             segments[segment] |= shiftedDigit;
19410             var residual = shiftedDigit >>> 16;
19411             if (residual)
19412                 segments[segment + 1] |= residual; // overflows segment
19413         }
19414         // Repeatedly divide segments by 10 and add remainder to base10Value
19415         var base10Value = "";
19416         var firstNonzeroSegment = segments.length - 1;
19417         var segmentsRemaining = true;
19418         while (segmentsRemaining) {
19419             var mod10 = 0;
19420             segmentsRemaining = false;
19421             for (var segment = firstNonzeroSegment; segment >= 0; segment--) {
19422                 var newSegment = mod10 << 16 | segments[segment];
19423                 var segmentValue = (newSegment / 10) | 0;
19424                 segments[segment] = segmentValue;
19425                 mod10 = newSegment - segmentValue * 10;
19426                 if (segmentValue && !segmentsRemaining) {
19427                     firstNonzeroSegment = segment;
19428                     segmentsRemaining = true;
19429                 }
19430             }
19431             base10Value = mod10 + base10Value;
19432         }
19433         return base10Value;
19434     }
19435     ts.parsePseudoBigInt = parsePseudoBigInt;
19436     function pseudoBigIntToString(_a) {
19437         var negative = _a.negative, base10Value = _a.base10Value;
19438         return (negative && base10Value !== "0" ? "-" : "") + base10Value;
19439     }
19440     ts.pseudoBigIntToString = pseudoBigIntToString;
19441     function isValidTypeOnlyAliasUseSite(useSite) {
19442         return !!(useSite.flags & 8388608 /* Ambient */)
19443             || isPartOfTypeQuery(useSite)
19444             || isIdentifierInNonEmittingHeritageClause(useSite)
19445             || isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(useSite)
19446             || !isExpressionNode(useSite);
19447     }
19448     ts.isValidTypeOnlyAliasUseSite = isValidTypeOnlyAliasUseSite;
19449     function typeOnlyDeclarationIsExport(typeOnlyDeclaration) {
19450         return typeOnlyDeclaration.kind === 270 /* ExportSpecifier */;
19451     }
19452     ts.typeOnlyDeclarationIsExport = typeOnlyDeclarationIsExport;
19453     function isPartOfPossiblyValidTypeOrAbstractComputedPropertyName(node) {
19454         while (node.kind === 78 /* Identifier */ || node.kind === 201 /* PropertyAccessExpression */) {
19455             node = node.parent;
19456         }
19457         if (node.kind !== 158 /* ComputedPropertyName */) {
19458             return false;
19459         }
19460         if (hasSyntacticModifier(node.parent, 128 /* Abstract */)) {
19461             return true;
19462         }
19463         var containerKind = node.parent.parent.kind;
19464         return containerKind === 253 /* InterfaceDeclaration */ || containerKind === 177 /* TypeLiteral */;
19465     }
19466     /** Returns true for an identifier in 1) an `implements` clause, and 2) an `extends` clause of an interface. */
19467     function isIdentifierInNonEmittingHeritageClause(node) {
19468         if (node.kind !== 78 /* Identifier */)
19469             return false;
19470         var heritageClause = ts.findAncestor(node.parent, function (parent) {
19471             switch (parent.kind) {
19472                 case 286 /* HeritageClause */:
19473                     return true;
19474                 case 201 /* PropertyAccessExpression */:
19475                 case 223 /* ExpressionWithTypeArguments */:
19476                     return false;
19477                 default:
19478                     return "quit";
19479             }
19480         });
19481         return (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.token) === 116 /* ImplementsKeyword */ || (heritageClause === null || heritageClause === void 0 ? void 0 : heritageClause.parent.kind) === 253 /* InterfaceDeclaration */;
19482     }
19483     function isIdentifierTypeReference(node) {
19484         return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName);
19485     }
19486     ts.isIdentifierTypeReference = isIdentifierTypeReference;
19487     function arrayIsHomogeneous(array, comparer) {
19488         if (comparer === void 0) { comparer = ts.equateValues; }
19489         if (array.length < 2)
19490             return true;
19491         var first = array[0];
19492         for (var i = 1, length_1 = array.length; i < length_1; i++) {
19493             var target = array[i];
19494             if (!comparer(first, target))
19495                 return false;
19496         }
19497         return true;
19498     }
19499     ts.arrayIsHomogeneous = arrayIsHomogeneous;
19500     /**
19501      * Bypasses immutability and directly sets the `pos` property of a `TextRange` or `Node`.
19502      */
19503     /* @internal */
19504     function setTextRangePos(range, pos) {
19505         range.pos = pos;
19506         return range;
19507     }
19508     ts.setTextRangePos = setTextRangePos;
19509     /**
19510      * Bypasses immutability and directly sets the `end` property of a `TextRange` or `Node`.
19511      */
19512     /* @internal */
19513     function setTextRangeEnd(range, end) {
19514         range.end = end;
19515         return range;
19516     }
19517     ts.setTextRangeEnd = setTextRangeEnd;
19518     /**
19519      * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node`.
19520      */
19521     /* @internal */
19522     function setTextRangePosEnd(range, pos, end) {
19523         return setTextRangeEnd(setTextRangePos(range, pos), end);
19524     }
19525     ts.setTextRangePosEnd = setTextRangePosEnd;
19526     /**
19527      * Bypasses immutability and directly sets the `pos` and `end` properties of a `TextRange` or `Node` from the
19528      * provided position and width.
19529      */
19530     /* @internal */
19531     function setTextRangePosWidth(range, pos, width) {
19532         return setTextRangePosEnd(range, pos, pos + width);
19533     }
19534     ts.setTextRangePosWidth = setTextRangePosWidth;
19535     function setNodeFlags(node, newFlags) {
19536         if (node) {
19537             node.flags = newFlags;
19538         }
19539         return node;
19540     }
19541     ts.setNodeFlags = setNodeFlags;
19542     function setParent(child, parent) {
19543         if (child && parent) {
19544             child.parent = parent;
19545         }
19546         return child;
19547     }
19548     ts.setParent = setParent;
19549     function setEachParent(children, parent) {
19550         if (children) {
19551             for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
19552                 var child = children_1[_i];
19553                 setParent(child, parent);
19554             }
19555         }
19556         return children;
19557     }
19558     ts.setEachParent = setEachParent;
19559     function setParentRecursive(rootNode, incremental) {
19560         if (!rootNode)
19561             return rootNode;
19562         ts.forEachChildRecursively(rootNode, ts.isJSDocNode(rootNode) ? bindParentToChildIgnoringJSDoc : bindParentToChild);
19563         return rootNode;
19564         function bindParentToChildIgnoringJSDoc(child, parent) {
19565             if (incremental && child.parent === parent) {
19566                 return "skip";
19567             }
19568             setParent(child, parent);
19569         }
19570         function bindJSDoc(child) {
19571             if (ts.hasJSDocNodes(child)) {
19572                 for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
19573                     var doc = _a[_i];
19574                     bindParentToChildIgnoringJSDoc(doc, child);
19575                     ts.forEachChildRecursively(doc, bindParentToChildIgnoringJSDoc);
19576                 }
19577             }
19578         }
19579         function bindParentToChild(child, parent) {
19580             return bindParentToChildIgnoringJSDoc(child, parent) || bindJSDoc(child);
19581         }
19582     }
19583     ts.setParentRecursive = setParentRecursive;
19584 })(ts || (ts = {}));
19585 /* @internal */
19586 var ts;
19587 (function (ts) {
19588     /**
19589      * Creates a `BaseNodeFactory` which can be used to create `Node` instances from the constructors provided by the object allocator.
19590      */
19591     function createBaseNodeFactory() {
19592         // tslint:disable variable-name
19593         var NodeConstructor;
19594         var TokenConstructor;
19595         var IdentifierConstructor;
19596         var PrivateIdentifierConstructor;
19597         var SourceFileConstructor;
19598         // tslint:enable variable-name
19599         return {
19600             createBaseSourceFileNode: createBaseSourceFileNode,
19601             createBaseIdentifierNode: createBaseIdentifierNode,
19602             createBasePrivateIdentifierNode: createBasePrivateIdentifierNode,
19603             createBaseTokenNode: createBaseTokenNode,
19604             createBaseNode: createBaseNode
19605         };
19606         function createBaseSourceFileNode(kind) {
19607             return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19608         }
19609         function createBaseIdentifierNode(kind) {
19610             return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19611         }
19612         function createBasePrivateIdentifierNode(kind) {
19613             return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19614         }
19615         function createBaseTokenNode(kind) {
19616             return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19617         }
19618         function createBaseNode(kind) {
19619             return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, /*pos*/ -1, /*end*/ -1);
19620         }
19621     }
19622     ts.createBaseNodeFactory = createBaseNodeFactory;
19623 })(ts || (ts = {}));
19624 /* @internal */
19625 var ts;
19626 (function (ts) {
19627     function createParenthesizerRules(factory) {
19628         return {
19629             parenthesizeLeftSideOfBinary: parenthesizeLeftSideOfBinary,
19630             parenthesizeRightSideOfBinary: parenthesizeRightSideOfBinary,
19631             parenthesizeExpressionOfComputedPropertyName: parenthesizeExpressionOfComputedPropertyName,
19632             parenthesizeConditionOfConditionalExpression: parenthesizeConditionOfConditionalExpression,
19633             parenthesizeBranchOfConditionalExpression: parenthesizeBranchOfConditionalExpression,
19634             parenthesizeExpressionOfExportDefault: parenthesizeExpressionOfExportDefault,
19635             parenthesizeExpressionOfNew: parenthesizeExpressionOfNew,
19636             parenthesizeLeftSideOfAccess: parenthesizeLeftSideOfAccess,
19637             parenthesizeOperandOfPostfixUnary: parenthesizeOperandOfPostfixUnary,
19638             parenthesizeOperandOfPrefixUnary: parenthesizeOperandOfPrefixUnary,
19639             parenthesizeExpressionsOfCommaDelimitedList: parenthesizeExpressionsOfCommaDelimitedList,
19640             parenthesizeExpressionForDisallowedComma: parenthesizeExpressionForDisallowedComma,
19641             parenthesizeExpressionOfExpressionStatement: parenthesizeExpressionOfExpressionStatement,
19642             parenthesizeConciseBodyOfArrowFunction: parenthesizeConciseBodyOfArrowFunction,
19643             parenthesizeMemberOfConditionalType: parenthesizeMemberOfConditionalType,
19644             parenthesizeMemberOfElementType: parenthesizeMemberOfElementType,
19645             parenthesizeElementTypeOfArrayType: parenthesizeElementTypeOfArrayType,
19646             parenthesizeConstituentTypesOfUnionOrIntersectionType: parenthesizeConstituentTypesOfUnionOrIntersectionType,
19647             parenthesizeTypeArguments: parenthesizeTypeArguments,
19648         };
19649         /**
19650          * Determines whether the operand to a BinaryExpression needs to be parenthesized.
19651          *
19652          * @param binaryOperator The operator for the BinaryExpression.
19653          * @param operand The operand for the BinaryExpression.
19654          * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
19655          *                           BinaryExpression.
19656          */
19657         function binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
19658             // If the operand has lower precedence, then it needs to be parenthesized to preserve the
19659             // intent of the expression. For example, if the operand is `a + b` and the operator is
19660             // `*`, then we need to parenthesize the operand to preserve the intended order of
19661             // operations: `(a + b) * x`.
19662             //
19663             // If the operand has higher precedence, then it does not need to be parenthesized. For
19664             // example, if the operand is `a * b` and the operator is `+`, then we do not need to
19665             // parenthesize to preserve the intended order of operations: `a * b + x`.
19666             //
19667             // If the operand has the same precedence, then we need to check the associativity of
19668             // the operator based on whether this is the left or right operand of the expression.
19669             //
19670             // For example, if `a / d` is on the right of operator `*`, we need to parenthesize
19671             // to preserve the intended order of operations: `x * (a / d)`
19672             //
19673             // If `a ** d` is on the left of operator `**`, we need to parenthesize to preserve
19674             // the intended order of operations: `(a ** b) ** c`
19675             var binaryOperatorPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, binaryOperator);
19676             var binaryOperatorAssociativity = ts.getOperatorAssociativity(216 /* BinaryExpression */, binaryOperator);
19677             var emittedOperand = ts.skipPartiallyEmittedExpressions(operand);
19678             if (!isLeftSideOfBinary && operand.kind === 209 /* ArrowFunction */ && binaryOperatorPrecedence > 3 /* Assignment */) {
19679                 // We need to parenthesize arrow functions on the right side to avoid it being
19680                 // parsed as parenthesized expression: `a && (() => {})`
19681                 return true;
19682             }
19683             var operandPrecedence = ts.getExpressionPrecedence(emittedOperand);
19684             switch (ts.compareValues(operandPrecedence, binaryOperatorPrecedence)) {
19685                 case -1 /* LessThan */:
19686                     // If the operand is the right side of a right-associative binary operation
19687                     // and is a yield expression, then we do not need parentheses.
19688                     if (!isLeftSideOfBinary
19689                         && binaryOperatorAssociativity === 1 /* Right */
19690                         && operand.kind === 219 /* YieldExpression */) {
19691                         return false;
19692                     }
19693                     return true;
19694                 case 1 /* GreaterThan */:
19695                     return false;
19696                 case 0 /* EqualTo */:
19697                     if (isLeftSideOfBinary) {
19698                         // No need to parenthesize the left operand when the binary operator is
19699                         // left associative:
19700                         //  (a*b)/x    -> a*b/x
19701                         //  (a**b)/x   -> a**b/x
19702                         //
19703                         // Parentheses are needed for the left operand when the binary operator is
19704                         // right associative:
19705                         //  (a/b)**x   -> (a/b)**x
19706                         //  (a**b)**x  -> (a**b)**x
19707                         return binaryOperatorAssociativity === 1 /* Right */;
19708                     }
19709                     else {
19710                         if (ts.isBinaryExpression(emittedOperand)
19711                             && emittedOperand.operatorToken.kind === binaryOperator) {
19712                             // No need to parenthesize the right operand when the binary operator and
19713                             // operand are the same and one of the following:
19714                             //  x*(a*b)     => x*a*b
19715                             //  x|(a|b)     => x|a|b
19716                             //  x&(a&b)     => x&a&b
19717                             //  x^(a^b)     => x^a^b
19718                             if (operatorHasAssociativeProperty(binaryOperator)) {
19719                                 return false;
19720                             }
19721                             // No need to parenthesize the right operand when the binary operator
19722                             // is plus (+) if both the left and right operands consist solely of either
19723                             // literals of the same kind or binary plus (+) expressions for literals of
19724                             // the same kind (recursively).
19725                             //  "a"+(1+2)       => "a"+(1+2)
19726                             //  "a"+("b"+"c")   => "a"+"b"+"c"
19727                             if (binaryOperator === 39 /* PlusToken */) {
19728                                 var leftKind = leftOperand ? getLiteralKindOfBinaryPlusOperand(leftOperand) : 0 /* Unknown */;
19729                                 if (ts.isLiteralKind(leftKind) && leftKind === getLiteralKindOfBinaryPlusOperand(emittedOperand)) {
19730                                     return false;
19731                                 }
19732                             }
19733                         }
19734                         // No need to parenthesize the right operand when the operand is right
19735                         // associative:
19736                         //  x/(a**b)    -> x/a**b
19737                         //  x**(a**b)   -> x**a**b
19738                         //
19739                         // Parentheses are needed for the right operand when the operand is left
19740                         // associative:
19741                         //  x/(a*b)     -> x/(a*b)
19742                         //  x**(a/b)    -> x**(a/b)
19743                         var operandAssociativity = ts.getExpressionAssociativity(emittedOperand);
19744                         return operandAssociativity === 0 /* Left */;
19745                     }
19746             }
19747         }
19748         /**
19749          * Determines whether a binary operator is mathematically associative.
19750          *
19751          * @param binaryOperator The binary operator.
19752          */
19753         function operatorHasAssociativeProperty(binaryOperator) {
19754             // The following operators are associative in JavaScript:
19755             //  (a*b)*c     -> a*(b*c)  -> a*b*c
19756             //  (a|b)|c     -> a|(b|c)  -> a|b|c
19757             //  (a&b)&c     -> a&(b&c)  -> a&b&c
19758             //  (a^b)^c     -> a^(b^c)  -> a^b^c
19759             //
19760             // While addition is associative in mathematics, JavaScript's `+` is not
19761             // guaranteed to be associative as it is overloaded with string concatenation.
19762             return binaryOperator === 41 /* AsteriskToken */
19763                 || binaryOperator === 51 /* BarToken */
19764                 || binaryOperator === 50 /* AmpersandToken */
19765                 || binaryOperator === 52 /* CaretToken */;
19766         }
19767         /**
19768          * This function determines whether an expression consists of a homogeneous set of
19769          * literal expressions or binary plus expressions that all share the same literal kind.
19770          * It is used to determine whether the right-hand operand of a binary plus expression can be
19771          * emitted without parentheses.
19772          */
19773         function getLiteralKindOfBinaryPlusOperand(node) {
19774             node = ts.skipPartiallyEmittedExpressions(node);
19775             if (ts.isLiteralKind(node.kind)) {
19776                 return node.kind;
19777             }
19778             if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 39 /* PlusToken */) {
19779                 if (node.cachedLiteralKind !== undefined) {
19780                     return node.cachedLiteralKind;
19781                 }
19782                 var leftKind = getLiteralKindOfBinaryPlusOperand(node.left);
19783                 var literalKind = ts.isLiteralKind(leftKind)
19784                     && leftKind === getLiteralKindOfBinaryPlusOperand(node.right)
19785                     ? leftKind
19786                     : 0 /* Unknown */;
19787                 node.cachedLiteralKind = literalKind;
19788                 return literalKind;
19789             }
19790             return 0 /* Unknown */;
19791         }
19792         /**
19793          * Wraps the operand to a BinaryExpression in parentheses if they are needed to preserve the intended
19794          * order of operations.
19795          *
19796          * @param binaryOperator The operator for the BinaryExpression.
19797          * @param operand The operand for the BinaryExpression.
19798          * @param isLeftSideOfBinary A value indicating whether the operand is the left side of the
19799          *                           BinaryExpression.
19800          */
19801         function parenthesizeBinaryOperand(binaryOperator, operand, isLeftSideOfBinary, leftOperand) {
19802             var skipped = ts.skipPartiallyEmittedExpressions(operand);
19803             // If the resulting expression is already parenthesized, we do not need to do any further processing.
19804             if (skipped.kind === 207 /* ParenthesizedExpression */) {
19805                 return operand;
19806             }
19807             return binaryOperandNeedsParentheses(binaryOperator, operand, isLeftSideOfBinary, leftOperand)
19808                 ? factory.createParenthesizedExpression(operand)
19809                 : operand;
19810         }
19811         function parenthesizeLeftSideOfBinary(binaryOperator, leftSide) {
19812             return parenthesizeBinaryOperand(binaryOperator, leftSide, /*isLeftSideOfBinary*/ true);
19813         }
19814         function parenthesizeRightSideOfBinary(binaryOperator, leftSide, rightSide) {
19815             return parenthesizeBinaryOperand(binaryOperator, rightSide, /*isLeftSideOfBinary*/ false, leftSide);
19816         }
19817         function parenthesizeExpressionOfComputedPropertyName(expression) {
19818             return ts.isCommaSequence(expression) ? factory.createParenthesizedExpression(expression) : expression;
19819         }
19820         function parenthesizeConditionOfConditionalExpression(condition) {
19821             var conditionalPrecedence = ts.getOperatorPrecedence(217 /* ConditionalExpression */, 57 /* QuestionToken */);
19822             var emittedCondition = ts.skipPartiallyEmittedExpressions(condition);
19823             var conditionPrecedence = ts.getExpressionPrecedence(emittedCondition);
19824             if (ts.compareValues(conditionPrecedence, conditionalPrecedence) !== 1 /* GreaterThan */) {
19825                 return factory.createParenthesizedExpression(condition);
19826             }
19827             return condition;
19828         }
19829         function parenthesizeBranchOfConditionalExpression(branch) {
19830             // per ES grammar both 'whenTrue' and 'whenFalse' parts of conditional expression are assignment expressions
19831             // so in case when comma expression is introduced as a part of previous transformations
19832             // if should be wrapped in parens since comma operator has the lowest precedence
19833             var emittedExpression = ts.skipPartiallyEmittedExpressions(branch);
19834             return ts.isCommaSequence(emittedExpression)
19835                 ? factory.createParenthesizedExpression(branch)
19836                 : branch;
19837         }
19838         /**
19839          *  [Per the spec](https://tc39.github.io/ecma262/#prod-ExportDeclaration), `export default` accepts _AssigmentExpression_ but
19840          *  has a lookahead restriction for `function`, `async function`, and `class`.
19841          *
19842          * Basically, that means we need to parenthesize in the following cases:
19843          *
19844          * - BinaryExpression of CommaToken
19845          * - CommaList (synthetic list of multiple comma expressions)
19846          * - FunctionExpression
19847          * - ClassExpression
19848          */
19849         function parenthesizeExpressionOfExportDefault(expression) {
19850             var check = ts.skipPartiallyEmittedExpressions(expression);
19851             var needsParens = ts.isCommaSequence(check);
19852             if (!needsParens) {
19853                 switch (ts.getLeftmostExpression(check, /*stopAtCallExpression*/ false).kind) {
19854                     case 221 /* ClassExpression */:
19855                     case 208 /* FunctionExpression */:
19856                         needsParens = true;
19857                 }
19858             }
19859             return needsParens ? factory.createParenthesizedExpression(expression) : expression;
19860         }
19861         /**
19862          * Wraps an expression in parentheses if it is needed in order to use the expression
19863          * as the expression of a `NewExpression` node.
19864          */
19865         function parenthesizeExpressionOfNew(expression) {
19866             var leftmostExpr = ts.getLeftmostExpression(expression, /*stopAtCallExpressions*/ true);
19867             switch (leftmostExpr.kind) {
19868                 case 203 /* CallExpression */:
19869                     return factory.createParenthesizedExpression(expression);
19870                 case 204 /* NewExpression */:
19871                     return !leftmostExpr.arguments
19872                         ? factory.createParenthesizedExpression(expression)
19873                         : expression; // TODO(rbuckton): Verify this assertion holds
19874             }
19875             return parenthesizeLeftSideOfAccess(expression);
19876         }
19877         /**
19878          * Wraps an expression in parentheses if it is needed in order to use the expression for
19879          * property or element access.
19880          */
19881         function parenthesizeLeftSideOfAccess(expression) {
19882             // isLeftHandSideExpression is almost the correct criterion for when it is not necessary
19883             // to parenthesize the expression before a dot. The known exception is:
19884             //
19885             //    NewExpression:
19886             //       new C.x        -> not the same as (new C).x
19887             //
19888             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
19889             if (ts.isLeftHandSideExpression(emittedExpression)
19890                 && (emittedExpression.kind !== 204 /* NewExpression */ || emittedExpression.arguments)) {
19891                 // TODO(rbuckton): Verify whether this assertion holds.
19892                 return expression;
19893             }
19894             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19895             return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
19896         }
19897         function parenthesizeOperandOfPostfixUnary(operand) {
19898             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19899             return ts.isLeftHandSideExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
19900         }
19901         function parenthesizeOperandOfPrefixUnary(operand) {
19902             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19903             return ts.isUnaryExpression(operand) ? operand : ts.setTextRange(factory.createParenthesizedExpression(operand), operand);
19904         }
19905         function parenthesizeExpressionsOfCommaDelimitedList(elements) {
19906             var result = ts.sameMap(elements, parenthesizeExpressionForDisallowedComma);
19907             return ts.setTextRange(factory.createNodeArray(result, elements.hasTrailingComma), elements);
19908         }
19909         function parenthesizeExpressionForDisallowedComma(expression) {
19910             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
19911             var expressionPrecedence = ts.getExpressionPrecedence(emittedExpression);
19912             var commaPrecedence = ts.getOperatorPrecedence(216 /* BinaryExpression */, 27 /* CommaToken */);
19913             // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19914             return expressionPrecedence > commaPrecedence ? expression : ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
19915         }
19916         function parenthesizeExpressionOfExpressionStatement(expression) {
19917             var emittedExpression = ts.skipPartiallyEmittedExpressions(expression);
19918             if (ts.isCallExpression(emittedExpression)) {
19919                 var callee = emittedExpression.expression;
19920                 var kind = ts.skipPartiallyEmittedExpressions(callee).kind;
19921                 if (kind === 208 /* FunctionExpression */ || kind === 209 /* ArrowFunction */) {
19922                     // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19923                     var updated = factory.updateCallExpression(emittedExpression, ts.setTextRange(factory.createParenthesizedExpression(callee), callee), emittedExpression.typeArguments, emittedExpression.arguments);
19924                     return factory.restoreOuterExpressions(expression, updated, 8 /* PartiallyEmittedExpressions */);
19925                 }
19926             }
19927             var leftmostExpressionKind = ts.getLeftmostExpression(emittedExpression, /*stopAtCallExpressions*/ false).kind;
19928             if (leftmostExpressionKind === 200 /* ObjectLiteralExpression */ || leftmostExpressionKind === 208 /* FunctionExpression */) {
19929                 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19930                 return ts.setTextRange(factory.createParenthesizedExpression(expression), expression);
19931             }
19932             return expression;
19933         }
19934         function parenthesizeConciseBodyOfArrowFunction(body) {
19935             if (!ts.isBlock(body) && (ts.isCommaSequence(body) || ts.getLeftmostExpression(body, /*stopAtCallExpressions*/ false).kind === 200 /* ObjectLiteralExpression */)) {
19936                 // TODO(rbuckton): Verifiy whether `setTextRange` is needed.
19937                 return ts.setTextRange(factory.createParenthesizedExpression(body), body);
19938             }
19939             return body;
19940         }
19941         function parenthesizeMemberOfConditionalType(member) {
19942             return member.kind === 184 /* ConditionalType */ ? factory.createParenthesizedType(member) : member;
19943         }
19944         function parenthesizeMemberOfElementType(member) {
19945             switch (member.kind) {
19946                 case 182 /* UnionType */:
19947                 case 183 /* IntersectionType */:
19948                 case 174 /* FunctionType */:
19949                 case 175 /* ConstructorType */:
19950                     return factory.createParenthesizedType(member);
19951             }
19952             return parenthesizeMemberOfConditionalType(member);
19953         }
19954         function parenthesizeElementTypeOfArrayType(member) {
19955             switch (member.kind) {
19956                 case 176 /* TypeQuery */:
19957                 case 188 /* TypeOperator */:
19958                 case 185 /* InferType */:
19959                     return factory.createParenthesizedType(member);
19960             }
19961             return parenthesizeMemberOfElementType(member);
19962         }
19963         function parenthesizeConstituentTypesOfUnionOrIntersectionType(members) {
19964             return factory.createNodeArray(ts.sameMap(members, parenthesizeMemberOfElementType));
19965         }
19966         function parenthesizeOrdinalTypeArgument(node, i) {
19967             return i === 0 && ts.isFunctionOrConstructorTypeNode(node) && node.typeParameters ? factory.createParenthesizedType(node) : node;
19968         }
19969         function parenthesizeTypeArguments(typeArguments) {
19970             if (ts.some(typeArguments)) {
19971                 return factory.createNodeArray(ts.sameMap(typeArguments, parenthesizeOrdinalTypeArgument));
19972             }
19973         }
19974     }
19975     ts.createParenthesizerRules = createParenthesizerRules;
19976     ts.nullParenthesizerRules = {
19977         parenthesizeLeftSideOfBinary: function (_binaryOperator, leftSide) { return leftSide; },
19978         parenthesizeRightSideOfBinary: function (_binaryOperator, _leftSide, rightSide) { return rightSide; },
19979         parenthesizeExpressionOfComputedPropertyName: ts.identity,
19980         parenthesizeConditionOfConditionalExpression: ts.identity,
19981         parenthesizeBranchOfConditionalExpression: ts.identity,
19982         parenthesizeExpressionOfExportDefault: ts.identity,
19983         parenthesizeExpressionOfNew: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
19984         parenthesizeLeftSideOfAccess: function (expression) { return ts.cast(expression, ts.isLeftHandSideExpression); },
19985         parenthesizeOperandOfPostfixUnary: function (operand) { return ts.cast(operand, ts.isLeftHandSideExpression); },
19986         parenthesizeOperandOfPrefixUnary: function (operand) { return ts.cast(operand, ts.isUnaryExpression); },
19987         parenthesizeExpressionsOfCommaDelimitedList: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
19988         parenthesizeExpressionForDisallowedComma: ts.identity,
19989         parenthesizeExpressionOfExpressionStatement: ts.identity,
19990         parenthesizeConciseBodyOfArrowFunction: ts.identity,
19991         parenthesizeMemberOfConditionalType: ts.identity,
19992         parenthesizeMemberOfElementType: ts.identity,
19993         parenthesizeElementTypeOfArrayType: ts.identity,
19994         parenthesizeConstituentTypesOfUnionOrIntersectionType: function (nodes) { return ts.cast(nodes, ts.isNodeArray); },
19995         parenthesizeTypeArguments: function (nodes) { return nodes && ts.cast(nodes, ts.isNodeArray); },
19996     };
19997 })(ts || (ts = {}));
19998 /* @internal */
19999 var ts;
20000 (function (ts) {
20001     function createNodeConverters(factory) {
20002         return {
20003             convertToFunctionBlock: convertToFunctionBlock,
20004             convertToFunctionExpression: convertToFunctionExpression,
20005             convertToArrayAssignmentElement: convertToArrayAssignmentElement,
20006             convertToObjectAssignmentElement: convertToObjectAssignmentElement,
20007             convertToAssignmentPattern: convertToAssignmentPattern,
20008             convertToObjectAssignmentPattern: convertToObjectAssignmentPattern,
20009             convertToArrayAssignmentPattern: convertToArrayAssignmentPattern,
20010             convertToAssignmentElementTarget: convertToAssignmentElementTarget,
20011         };
20012         function convertToFunctionBlock(node, multiLine) {
20013             if (ts.isBlock(node))
20014                 return node;
20015             var returnStatement = factory.createReturnStatement(node);
20016             ts.setTextRange(returnStatement, node);
20017             var body = factory.createBlock([returnStatement], multiLine);
20018             ts.setTextRange(body, node);
20019             return body;
20020         }
20021         function convertToFunctionExpression(node) {
20022             if (!node.body)
20023                 return ts.Debug.fail("Cannot convert a FunctionDeclaration without a body");
20024             var updated = factory.createFunctionExpression(node.modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body);
20025             ts.setOriginalNode(updated, node);
20026             ts.setTextRange(updated, node);
20027             if (ts.getStartsOnNewLine(node)) {
20028                 ts.setStartsOnNewLine(updated, /*newLine*/ true);
20029             }
20030             return updated;
20031         }
20032         function convertToArrayAssignmentElement(element) {
20033             if (ts.isBindingElement(element)) {
20034                 if (element.dotDotDotToken) {
20035                     ts.Debug.assertNode(element.name, ts.isIdentifier);
20036                     return ts.setOriginalNode(ts.setTextRange(factory.createSpreadElement(element.name), element), element);
20037                 }
20038                 var expression = convertToAssignmentElementTarget(element.name);
20039                 return element.initializer
20040                     ? ts.setOriginalNode(ts.setTextRange(factory.createAssignment(expression, element.initializer), element), element)
20041                     : expression;
20042             }
20043             return ts.cast(element, ts.isExpression);
20044         }
20045         function convertToObjectAssignmentElement(element) {
20046             if (ts.isBindingElement(element)) {
20047                 if (element.dotDotDotToken) {
20048                     ts.Debug.assertNode(element.name, ts.isIdentifier);
20049                     return ts.setOriginalNode(ts.setTextRange(factory.createSpreadAssignment(element.name), element), element);
20050                 }
20051                 if (element.propertyName) {
20052                     var expression = convertToAssignmentElementTarget(element.name);
20053                     return ts.setOriginalNode(ts.setTextRange(factory.createPropertyAssignment(element.propertyName, element.initializer ? factory.createAssignment(expression, element.initializer) : expression), element), element);
20054                 }
20055                 ts.Debug.assertNode(element.name, ts.isIdentifier);
20056                 return ts.setOriginalNode(ts.setTextRange(factory.createShorthandPropertyAssignment(element.name, element.initializer), element), element);
20057             }
20058             return ts.cast(element, ts.isObjectLiteralElementLike);
20059         }
20060         function convertToAssignmentPattern(node) {
20061             switch (node.kind) {
20062                 case 197 /* ArrayBindingPattern */:
20063                 case 199 /* ArrayLiteralExpression */:
20064                     return convertToArrayAssignmentPattern(node);
20065                 case 196 /* ObjectBindingPattern */:
20066                 case 200 /* ObjectLiteralExpression */:
20067                     return convertToObjectAssignmentPattern(node);
20068             }
20069         }
20070         function convertToObjectAssignmentPattern(node) {
20071             if (ts.isObjectBindingPattern(node)) {
20072                 return ts.setOriginalNode(ts.setTextRange(factory.createObjectLiteralExpression(ts.map(node.elements, convertToObjectAssignmentElement)), node), node);
20073             }
20074             return ts.cast(node, ts.isObjectLiteralExpression);
20075         }
20076         function convertToArrayAssignmentPattern(node) {
20077             if (ts.isArrayBindingPattern(node)) {
20078                 return ts.setOriginalNode(ts.setTextRange(factory.createArrayLiteralExpression(ts.map(node.elements, convertToArrayAssignmentElement)), node), node);
20079             }
20080             return ts.cast(node, ts.isArrayLiteralExpression);
20081         }
20082         function convertToAssignmentElementTarget(node) {
20083             if (ts.isBindingPattern(node)) {
20084                 return convertToAssignmentPattern(node);
20085             }
20086             return ts.cast(node, ts.isExpression);
20087         }
20088     }
20089     ts.createNodeConverters = createNodeConverters;
20090     ts.nullNodeConverters = {
20091         convertToFunctionBlock: ts.notImplemented,
20092         convertToFunctionExpression: ts.notImplemented,
20093         convertToArrayAssignmentElement: ts.notImplemented,
20094         convertToObjectAssignmentElement: ts.notImplemented,
20095         convertToAssignmentPattern: ts.notImplemented,
20096         convertToObjectAssignmentPattern: ts.notImplemented,
20097         convertToArrayAssignmentPattern: ts.notImplemented,
20098         convertToAssignmentElementTarget: ts.notImplemented,
20099     };
20100 })(ts || (ts = {}));
20101 var ts;
20102 (function (ts) {
20103     var nextAutoGenerateId = 0;
20104     /* @internal */
20105     var NodeFactoryFlags;
20106     (function (NodeFactoryFlags) {
20107         NodeFactoryFlags[NodeFactoryFlags["None"] = 0] = "None";
20108         // Disables the parenthesizer rules for the factory.
20109         NodeFactoryFlags[NodeFactoryFlags["NoParenthesizerRules"] = 1] = "NoParenthesizerRules";
20110         // Disables the node converters for the factory.
20111         NodeFactoryFlags[NodeFactoryFlags["NoNodeConverters"] = 2] = "NoNodeConverters";
20112         // Ensures new `PropertyAccessExpression` nodes are created with the `NoIndentation` emit flag set.
20113         NodeFactoryFlags[NodeFactoryFlags["NoIndentationOnFreshPropertyAccess"] = 4] = "NoIndentationOnFreshPropertyAccess";
20114         // Do not set an `original` pointer when updating a node.
20115         NodeFactoryFlags[NodeFactoryFlags["NoOriginalNode"] = 8] = "NoOriginalNode";
20116     })(NodeFactoryFlags = ts.NodeFactoryFlags || (ts.NodeFactoryFlags = {}));
20117     /**
20118      * Creates a `NodeFactory` that can be used to create and update a syntax tree.
20119      * @param flags Flags that control factory behavior.
20120      * @param baseFactory A `BaseNodeFactory` used to create the base `Node` objects.
20121      */
20122     /* @internal */
20123     function createNodeFactory(flags, baseFactory) {
20124         var update = flags & 8 /* NoOriginalNode */ ? updateWithoutOriginal : updateWithOriginal;
20125         // Lazily load the parenthesizer, node converters, and some factory methods until they are used.
20126         var parenthesizerRules = ts.memoize(function () { return flags & 1 /* NoParenthesizerRules */ ? ts.nullParenthesizerRules : ts.createParenthesizerRules(factory); });
20127         var converters = ts.memoize(function () { return flags & 2 /* NoNodeConverters */ ? ts.nullNodeConverters : ts.createNodeConverters(factory); });
20128         // lazy initializaton of common operator factories
20129         var getBinaryCreateFunction = ts.memoizeOne(function (operator) { return function (left, right) { return createBinaryExpression(left, operator, right); }; });
20130         var getPrefixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPrefixUnaryExpression(operator, operand); }; });
20131         var getPostfixUnaryCreateFunction = ts.memoizeOne(function (operator) { return function (operand) { return createPostfixUnaryExpression(operand, operator); }; });
20132         var getJSDocPrimaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function () { return createJSDocPrimaryTypeWorker(kind); }; });
20133         var getJSDocUnaryTypeCreateFunction = ts.memoizeOne(function (kind) { return function (type) { return createJSDocUnaryTypeWorker(kind, type); }; });
20134         var getJSDocUnaryTypeUpdateFunction = ts.memoizeOne(function (kind) { return function (node, type) { return updateJSDocUnaryTypeWorker(kind, node, type); }; });
20135         var getJSDocSimpleTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, comment) { return createJSDocSimpleTagWorker(kind, tagName, comment); }; });
20136         var getJSDocSimpleTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, comment) { return updateJSDocSimpleTagWorker(kind, node, tagName, comment); }; });
20137         var getJSDocTypeLikeTagCreateFunction = ts.memoizeOne(function (kind) { return function (tagName, typeExpression, comment) { return createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment); }; });
20138         var getJSDocTypeLikeTagUpdateFunction = ts.memoizeOne(function (kind) { return function (node, tagName, typeExpression, comment) { return updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment); }; });
20139         var factory = {
20140             get parenthesizer() { return parenthesizerRules(); },
20141             get converters() { return converters(); },
20142             createNodeArray: createNodeArray,
20143             createNumericLiteral: createNumericLiteral,
20144             createBigIntLiteral: createBigIntLiteral,
20145             createStringLiteral: createStringLiteral,
20146             createStringLiteralFromNode: createStringLiteralFromNode,
20147             createRegularExpressionLiteral: createRegularExpressionLiteral,
20148             createLiteralLikeNode: createLiteralLikeNode,
20149             createIdentifier: createIdentifier,
20150             updateIdentifier: updateIdentifier,
20151             createTempVariable: createTempVariable,
20152             createLoopVariable: createLoopVariable,
20153             createUniqueName: createUniqueName,
20154             getGeneratedNameForNode: getGeneratedNameForNode,
20155             createPrivateIdentifier: createPrivateIdentifier,
20156             createToken: createToken,
20157             createSuper: createSuper,
20158             createThis: createThis,
20159             createNull: createNull,
20160             createTrue: createTrue,
20161             createFalse: createFalse,
20162             createModifier: createModifier,
20163             createModifiersFromModifierFlags: createModifiersFromModifierFlags,
20164             createQualifiedName: createQualifiedName,
20165             updateQualifiedName: updateQualifiedName,
20166             createComputedPropertyName: createComputedPropertyName,
20167             updateComputedPropertyName: updateComputedPropertyName,
20168             createTypeParameterDeclaration: createTypeParameterDeclaration,
20169             updateTypeParameterDeclaration: updateTypeParameterDeclaration,
20170             createParameterDeclaration: createParameterDeclaration,
20171             updateParameterDeclaration: updateParameterDeclaration,
20172             createDecorator: createDecorator,
20173             updateDecorator: updateDecorator,
20174             createPropertySignature: createPropertySignature,
20175             updatePropertySignature: updatePropertySignature,
20176             createPropertyDeclaration: createPropertyDeclaration,
20177             updatePropertyDeclaration: updatePropertyDeclaration,
20178             createMethodSignature: createMethodSignature,
20179             updateMethodSignature: updateMethodSignature,
20180             createMethodDeclaration: createMethodDeclaration,
20181             updateMethodDeclaration: updateMethodDeclaration,
20182             createConstructorDeclaration: createConstructorDeclaration,
20183             updateConstructorDeclaration: updateConstructorDeclaration,
20184             createGetAccessorDeclaration: createGetAccessorDeclaration,
20185             updateGetAccessorDeclaration: updateGetAccessorDeclaration,
20186             createSetAccessorDeclaration: createSetAccessorDeclaration,
20187             updateSetAccessorDeclaration: updateSetAccessorDeclaration,
20188             createCallSignature: createCallSignature,
20189             updateCallSignature: updateCallSignature,
20190             createConstructSignature: createConstructSignature,
20191             updateConstructSignature: updateConstructSignature,
20192             createIndexSignature: createIndexSignature,
20193             updateIndexSignature: updateIndexSignature,
20194             createTemplateLiteralTypeSpan: createTemplateLiteralTypeSpan,
20195             updateTemplateLiteralTypeSpan: updateTemplateLiteralTypeSpan,
20196             createKeywordTypeNode: createKeywordTypeNode,
20197             createTypePredicateNode: createTypePredicateNode,
20198             updateTypePredicateNode: updateTypePredicateNode,
20199             createTypeReferenceNode: createTypeReferenceNode,
20200             updateTypeReferenceNode: updateTypeReferenceNode,
20201             createFunctionTypeNode: createFunctionTypeNode,
20202             updateFunctionTypeNode: updateFunctionTypeNode,
20203             createConstructorTypeNode: createConstructorTypeNode,
20204             updateConstructorTypeNode: updateConstructorTypeNode,
20205             createTypeQueryNode: createTypeQueryNode,
20206             updateTypeQueryNode: updateTypeQueryNode,
20207             createTypeLiteralNode: createTypeLiteralNode,
20208             updateTypeLiteralNode: updateTypeLiteralNode,
20209             createArrayTypeNode: createArrayTypeNode,
20210             updateArrayTypeNode: updateArrayTypeNode,
20211             createTupleTypeNode: createTupleTypeNode,
20212             updateTupleTypeNode: updateTupleTypeNode,
20213             createNamedTupleMember: createNamedTupleMember,
20214             updateNamedTupleMember: updateNamedTupleMember,
20215             createOptionalTypeNode: createOptionalTypeNode,
20216             updateOptionalTypeNode: updateOptionalTypeNode,
20217             createRestTypeNode: createRestTypeNode,
20218             updateRestTypeNode: updateRestTypeNode,
20219             createUnionTypeNode: createUnionTypeNode,
20220             updateUnionTypeNode: updateUnionTypeNode,
20221             createIntersectionTypeNode: createIntersectionTypeNode,
20222             updateIntersectionTypeNode: updateIntersectionTypeNode,
20223             createConditionalTypeNode: createConditionalTypeNode,
20224             updateConditionalTypeNode: updateConditionalTypeNode,
20225             createInferTypeNode: createInferTypeNode,
20226             updateInferTypeNode: updateInferTypeNode,
20227             createImportTypeNode: createImportTypeNode,
20228             updateImportTypeNode: updateImportTypeNode,
20229             createParenthesizedType: createParenthesizedType,
20230             updateParenthesizedType: updateParenthesizedType,
20231             createThisTypeNode: createThisTypeNode,
20232             createTypeOperatorNode: createTypeOperatorNode,
20233             updateTypeOperatorNode: updateTypeOperatorNode,
20234             createIndexedAccessTypeNode: createIndexedAccessTypeNode,
20235             updateIndexedAccessTypeNode: updateIndexedAccessTypeNode,
20236             createMappedTypeNode: createMappedTypeNode,
20237             updateMappedTypeNode: updateMappedTypeNode,
20238             createLiteralTypeNode: createLiteralTypeNode,
20239             updateLiteralTypeNode: updateLiteralTypeNode,
20240             createTemplateLiteralType: createTemplateLiteralType,
20241             updateTemplateLiteralType: updateTemplateLiteralType,
20242             createObjectBindingPattern: createObjectBindingPattern,
20243             updateObjectBindingPattern: updateObjectBindingPattern,
20244             createArrayBindingPattern: createArrayBindingPattern,
20245             updateArrayBindingPattern: updateArrayBindingPattern,
20246             createBindingElement: createBindingElement,
20247             updateBindingElement: updateBindingElement,
20248             createArrayLiteralExpression: createArrayLiteralExpression,
20249             updateArrayLiteralExpression: updateArrayLiteralExpression,
20250             createObjectLiteralExpression: createObjectLiteralExpression,
20251             updateObjectLiteralExpression: updateObjectLiteralExpression,
20252             createPropertyAccessExpression: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
20253                 function (expression, name) { return ts.setEmitFlags(createPropertyAccessExpression(expression, name), 131072 /* NoIndentation */); } :
20254                 createPropertyAccessExpression,
20255             updatePropertyAccessExpression: updatePropertyAccessExpression,
20256             createPropertyAccessChain: flags & 4 /* NoIndentationOnFreshPropertyAccess */ ?
20257                 function (expression, questionDotToken, name) { return ts.setEmitFlags(createPropertyAccessChain(expression, questionDotToken, name), 131072 /* NoIndentation */); } :
20258                 createPropertyAccessChain,
20259             updatePropertyAccessChain: updatePropertyAccessChain,
20260             createElementAccessExpression: createElementAccessExpression,
20261             updateElementAccessExpression: updateElementAccessExpression,
20262             createElementAccessChain: createElementAccessChain,
20263             updateElementAccessChain: updateElementAccessChain,
20264             createCallExpression: createCallExpression,
20265             updateCallExpression: updateCallExpression,
20266             createCallChain: createCallChain,
20267             updateCallChain: updateCallChain,
20268             createNewExpression: createNewExpression,
20269             updateNewExpression: updateNewExpression,
20270             createTaggedTemplateExpression: createTaggedTemplateExpression,
20271             updateTaggedTemplateExpression: updateTaggedTemplateExpression,
20272             createTypeAssertion: createTypeAssertion,
20273             updateTypeAssertion: updateTypeAssertion,
20274             createParenthesizedExpression: createParenthesizedExpression,
20275             updateParenthesizedExpression: updateParenthesizedExpression,
20276             createFunctionExpression: createFunctionExpression,
20277             updateFunctionExpression: updateFunctionExpression,
20278             createArrowFunction: createArrowFunction,
20279             updateArrowFunction: updateArrowFunction,
20280             createDeleteExpression: createDeleteExpression,
20281             updateDeleteExpression: updateDeleteExpression,
20282             createTypeOfExpression: createTypeOfExpression,
20283             updateTypeOfExpression: updateTypeOfExpression,
20284             createVoidExpression: createVoidExpression,
20285             updateVoidExpression: updateVoidExpression,
20286             createAwaitExpression: createAwaitExpression,
20287             updateAwaitExpression: updateAwaitExpression,
20288             createPrefixUnaryExpression: createPrefixUnaryExpression,
20289             updatePrefixUnaryExpression: updatePrefixUnaryExpression,
20290             createPostfixUnaryExpression: createPostfixUnaryExpression,
20291             updatePostfixUnaryExpression: updatePostfixUnaryExpression,
20292             createBinaryExpression: createBinaryExpression,
20293             updateBinaryExpression: updateBinaryExpression,
20294             createConditionalExpression: createConditionalExpression,
20295             updateConditionalExpression: updateConditionalExpression,
20296             createTemplateExpression: createTemplateExpression,
20297             updateTemplateExpression: updateTemplateExpression,
20298             createTemplateHead: createTemplateHead,
20299             createTemplateMiddle: createTemplateMiddle,
20300             createTemplateTail: createTemplateTail,
20301             createNoSubstitutionTemplateLiteral: createNoSubstitutionTemplateLiteral,
20302             createTemplateLiteralLikeNode: createTemplateLiteralLikeNode,
20303             createYieldExpression: createYieldExpression,
20304             updateYieldExpression: updateYieldExpression,
20305             createSpreadElement: createSpreadElement,
20306             updateSpreadElement: updateSpreadElement,
20307             createClassExpression: createClassExpression,
20308             updateClassExpression: updateClassExpression,
20309             createOmittedExpression: createOmittedExpression,
20310             createExpressionWithTypeArguments: createExpressionWithTypeArguments,
20311             updateExpressionWithTypeArguments: updateExpressionWithTypeArguments,
20312             createAsExpression: createAsExpression,
20313             updateAsExpression: updateAsExpression,
20314             createNonNullExpression: createNonNullExpression,
20315             updateNonNullExpression: updateNonNullExpression,
20316             createNonNullChain: createNonNullChain,
20317             updateNonNullChain: updateNonNullChain,
20318             createMetaProperty: createMetaProperty,
20319             updateMetaProperty: updateMetaProperty,
20320             createTemplateSpan: createTemplateSpan,
20321             updateTemplateSpan: updateTemplateSpan,
20322             createSemicolonClassElement: createSemicolonClassElement,
20323             createBlock: createBlock,
20324             updateBlock: updateBlock,
20325             createVariableStatement: createVariableStatement,
20326             updateVariableStatement: updateVariableStatement,
20327             createEmptyStatement: createEmptyStatement,
20328             createExpressionStatement: createExpressionStatement,
20329             updateExpressionStatement: updateExpressionStatement,
20330             createIfStatement: createIfStatement,
20331             updateIfStatement: updateIfStatement,
20332             createDoStatement: createDoStatement,
20333             updateDoStatement: updateDoStatement,
20334             createWhileStatement: createWhileStatement,
20335             updateWhileStatement: updateWhileStatement,
20336             createForStatement: createForStatement,
20337             updateForStatement: updateForStatement,
20338             createForInStatement: createForInStatement,
20339             updateForInStatement: updateForInStatement,
20340             createForOfStatement: createForOfStatement,
20341             updateForOfStatement: updateForOfStatement,
20342             createContinueStatement: createContinueStatement,
20343             updateContinueStatement: updateContinueStatement,
20344             createBreakStatement: createBreakStatement,
20345             updateBreakStatement: updateBreakStatement,
20346             createReturnStatement: createReturnStatement,
20347             updateReturnStatement: updateReturnStatement,
20348             createWithStatement: createWithStatement,
20349             updateWithStatement: updateWithStatement,
20350             createSwitchStatement: createSwitchStatement,
20351             updateSwitchStatement: updateSwitchStatement,
20352             createLabeledStatement: createLabeledStatement,
20353             updateLabeledStatement: updateLabeledStatement,
20354             createThrowStatement: createThrowStatement,
20355             updateThrowStatement: updateThrowStatement,
20356             createTryStatement: createTryStatement,
20357             updateTryStatement: updateTryStatement,
20358             createDebuggerStatement: createDebuggerStatement,
20359             createVariableDeclaration: createVariableDeclaration,
20360             updateVariableDeclaration: updateVariableDeclaration,
20361             createVariableDeclarationList: createVariableDeclarationList,
20362             updateVariableDeclarationList: updateVariableDeclarationList,
20363             createFunctionDeclaration: createFunctionDeclaration,
20364             updateFunctionDeclaration: updateFunctionDeclaration,
20365             createClassDeclaration: createClassDeclaration,
20366             updateClassDeclaration: updateClassDeclaration,
20367             createInterfaceDeclaration: createInterfaceDeclaration,
20368             updateInterfaceDeclaration: updateInterfaceDeclaration,
20369             createTypeAliasDeclaration: createTypeAliasDeclaration,
20370             updateTypeAliasDeclaration: updateTypeAliasDeclaration,
20371             createEnumDeclaration: createEnumDeclaration,
20372             updateEnumDeclaration: updateEnumDeclaration,
20373             createModuleDeclaration: createModuleDeclaration,
20374             updateModuleDeclaration: updateModuleDeclaration,
20375             createModuleBlock: createModuleBlock,
20376             updateModuleBlock: updateModuleBlock,
20377             createCaseBlock: createCaseBlock,
20378             updateCaseBlock: updateCaseBlock,
20379             createNamespaceExportDeclaration: createNamespaceExportDeclaration,
20380             updateNamespaceExportDeclaration: updateNamespaceExportDeclaration,
20381             createImportEqualsDeclaration: createImportEqualsDeclaration,
20382             updateImportEqualsDeclaration: updateImportEqualsDeclaration,
20383             createImportDeclaration: createImportDeclaration,
20384             updateImportDeclaration: updateImportDeclaration,
20385             createImportClause: createImportClause,
20386             updateImportClause: updateImportClause,
20387             createNamespaceImport: createNamespaceImport,
20388             updateNamespaceImport: updateNamespaceImport,
20389             createNamespaceExport: createNamespaceExport,
20390             updateNamespaceExport: updateNamespaceExport,
20391             createNamedImports: createNamedImports,
20392             updateNamedImports: updateNamedImports,
20393             createImportSpecifier: createImportSpecifier,
20394             updateImportSpecifier: updateImportSpecifier,
20395             createExportAssignment: createExportAssignment,
20396             updateExportAssignment: updateExportAssignment,
20397             createExportDeclaration: createExportDeclaration,
20398             updateExportDeclaration: updateExportDeclaration,
20399             createNamedExports: createNamedExports,
20400             updateNamedExports: updateNamedExports,
20401             createExportSpecifier: createExportSpecifier,
20402             updateExportSpecifier: updateExportSpecifier,
20403             createMissingDeclaration: createMissingDeclaration,
20404             createExternalModuleReference: createExternalModuleReference,
20405             updateExternalModuleReference: updateExternalModuleReference,
20406             // lazily load factory members for JSDoc types with similar structure
20407             get createJSDocAllType() { return getJSDocPrimaryTypeCreateFunction(303 /* JSDocAllType */); },
20408             get createJSDocUnknownType() { return getJSDocPrimaryTypeCreateFunction(304 /* JSDocUnknownType */); },
20409             get createJSDocNonNullableType() { return getJSDocUnaryTypeCreateFunction(306 /* JSDocNonNullableType */); },
20410             get updateJSDocNonNullableType() { return getJSDocUnaryTypeUpdateFunction(306 /* JSDocNonNullableType */); },
20411             get createJSDocNullableType() { return getJSDocUnaryTypeCreateFunction(305 /* JSDocNullableType */); },
20412             get updateJSDocNullableType() { return getJSDocUnaryTypeUpdateFunction(305 /* JSDocNullableType */); },
20413             get createJSDocOptionalType() { return getJSDocUnaryTypeCreateFunction(307 /* JSDocOptionalType */); },
20414             get updateJSDocOptionalType() { return getJSDocUnaryTypeUpdateFunction(307 /* JSDocOptionalType */); },
20415             get createJSDocVariadicType() { return getJSDocUnaryTypeCreateFunction(309 /* JSDocVariadicType */); },
20416             get updateJSDocVariadicType() { return getJSDocUnaryTypeUpdateFunction(309 /* JSDocVariadicType */); },
20417             get createJSDocNamepathType() { return getJSDocUnaryTypeCreateFunction(310 /* JSDocNamepathType */); },
20418             get updateJSDocNamepathType() { return getJSDocUnaryTypeUpdateFunction(310 /* JSDocNamepathType */); },
20419             createJSDocFunctionType: createJSDocFunctionType,
20420             updateJSDocFunctionType: updateJSDocFunctionType,
20421             createJSDocTypeLiteral: createJSDocTypeLiteral,
20422             updateJSDocTypeLiteral: updateJSDocTypeLiteral,
20423             createJSDocTypeExpression: createJSDocTypeExpression,
20424             updateJSDocTypeExpression: updateJSDocTypeExpression,
20425             createJSDocSignature: createJSDocSignature,
20426             updateJSDocSignature: updateJSDocSignature,
20427             createJSDocTemplateTag: createJSDocTemplateTag,
20428             updateJSDocTemplateTag: updateJSDocTemplateTag,
20429             createJSDocTypedefTag: createJSDocTypedefTag,
20430             updateJSDocTypedefTag: updateJSDocTypedefTag,
20431             createJSDocParameterTag: createJSDocParameterTag,
20432             updateJSDocParameterTag: updateJSDocParameterTag,
20433             createJSDocPropertyTag: createJSDocPropertyTag,
20434             updateJSDocPropertyTag: updateJSDocPropertyTag,
20435             createJSDocCallbackTag: createJSDocCallbackTag,
20436             updateJSDocCallbackTag: updateJSDocCallbackTag,
20437             createJSDocAugmentsTag: createJSDocAugmentsTag,
20438             updateJSDocAugmentsTag: updateJSDocAugmentsTag,
20439             createJSDocImplementsTag: createJSDocImplementsTag,
20440             updateJSDocImplementsTag: updateJSDocImplementsTag,
20441             createJSDocSeeTag: createJSDocSeeTag,
20442             updateJSDocSeeTag: updateJSDocSeeTag,
20443             createJSDocNameReference: createJSDocNameReference,
20444             updateJSDocNameReference: updateJSDocNameReference,
20445             // lazily load factory members for JSDoc tags with similar structure
20446             get createJSDocTypeTag() { return getJSDocTypeLikeTagCreateFunction(329 /* JSDocTypeTag */); },
20447             get updateJSDocTypeTag() { return getJSDocTypeLikeTagUpdateFunction(329 /* JSDocTypeTag */); },
20448             get createJSDocReturnTag() { return getJSDocTypeLikeTagCreateFunction(327 /* JSDocReturnTag */); },
20449             get updateJSDocReturnTag() { return getJSDocTypeLikeTagUpdateFunction(327 /* JSDocReturnTag */); },
20450             get createJSDocThisTag() { return getJSDocTypeLikeTagCreateFunction(328 /* JSDocThisTag */); },
20451             get updateJSDocThisTag() { return getJSDocTypeLikeTagUpdateFunction(328 /* JSDocThisTag */); },
20452             get createJSDocEnumTag() { return getJSDocTypeLikeTagCreateFunction(325 /* JSDocEnumTag */); },
20453             get updateJSDocEnumTag() { return getJSDocTypeLikeTagUpdateFunction(325 /* JSDocEnumTag */); },
20454             get createJSDocAuthorTag() { return getJSDocSimpleTagCreateFunction(317 /* JSDocAuthorTag */); },
20455             get updateJSDocAuthorTag() { return getJSDocSimpleTagUpdateFunction(317 /* JSDocAuthorTag */); },
20456             get createJSDocClassTag() { return getJSDocSimpleTagCreateFunction(319 /* JSDocClassTag */); },
20457             get updateJSDocClassTag() { return getJSDocSimpleTagUpdateFunction(319 /* JSDocClassTag */); },
20458             get createJSDocPublicTag() { return getJSDocSimpleTagCreateFunction(320 /* JSDocPublicTag */); },
20459             get updateJSDocPublicTag() { return getJSDocSimpleTagUpdateFunction(320 /* JSDocPublicTag */); },
20460             get createJSDocPrivateTag() { return getJSDocSimpleTagCreateFunction(321 /* JSDocPrivateTag */); },
20461             get updateJSDocPrivateTag() { return getJSDocSimpleTagUpdateFunction(321 /* JSDocPrivateTag */); },
20462             get createJSDocProtectedTag() { return getJSDocSimpleTagCreateFunction(322 /* JSDocProtectedTag */); },
20463             get updateJSDocProtectedTag() { return getJSDocSimpleTagUpdateFunction(322 /* JSDocProtectedTag */); },
20464             get createJSDocReadonlyTag() { return getJSDocSimpleTagCreateFunction(323 /* JSDocReadonlyTag */); },
20465             get updateJSDocReadonlyTag() { return getJSDocSimpleTagUpdateFunction(323 /* JSDocReadonlyTag */); },
20466             get createJSDocDeprecatedTag() { return getJSDocSimpleTagCreateFunction(318 /* JSDocDeprecatedTag */); },
20467             get updateJSDocDeprecatedTag() { return getJSDocSimpleTagUpdateFunction(318 /* JSDocDeprecatedTag */); },
20468             createJSDocUnknownTag: createJSDocUnknownTag,
20469             updateJSDocUnknownTag: updateJSDocUnknownTag,
20470             createJSDocComment: createJSDocComment,
20471             updateJSDocComment: updateJSDocComment,
20472             createJsxElement: createJsxElement,
20473             updateJsxElement: updateJsxElement,
20474             createJsxSelfClosingElement: createJsxSelfClosingElement,
20475             updateJsxSelfClosingElement: updateJsxSelfClosingElement,
20476             createJsxOpeningElement: createJsxOpeningElement,
20477             updateJsxOpeningElement: updateJsxOpeningElement,
20478             createJsxClosingElement: createJsxClosingElement,
20479             updateJsxClosingElement: updateJsxClosingElement,
20480             createJsxFragment: createJsxFragment,
20481             createJsxText: createJsxText,
20482             updateJsxText: updateJsxText,
20483             createJsxOpeningFragment: createJsxOpeningFragment,
20484             createJsxJsxClosingFragment: createJsxJsxClosingFragment,
20485             updateJsxFragment: updateJsxFragment,
20486             createJsxAttribute: createJsxAttribute,
20487             updateJsxAttribute: updateJsxAttribute,
20488             createJsxAttributes: createJsxAttributes,
20489             updateJsxAttributes: updateJsxAttributes,
20490             createJsxSpreadAttribute: createJsxSpreadAttribute,
20491             updateJsxSpreadAttribute: updateJsxSpreadAttribute,
20492             createJsxExpression: createJsxExpression,
20493             updateJsxExpression: updateJsxExpression,
20494             createCaseClause: createCaseClause,
20495             updateCaseClause: updateCaseClause,
20496             createDefaultClause: createDefaultClause,
20497             updateDefaultClause: updateDefaultClause,
20498             createHeritageClause: createHeritageClause,
20499             updateHeritageClause: updateHeritageClause,
20500             createCatchClause: createCatchClause,
20501             updateCatchClause: updateCatchClause,
20502             createPropertyAssignment: createPropertyAssignment,
20503             updatePropertyAssignment: updatePropertyAssignment,
20504             createShorthandPropertyAssignment: createShorthandPropertyAssignment,
20505             updateShorthandPropertyAssignment: updateShorthandPropertyAssignment,
20506             createSpreadAssignment: createSpreadAssignment,
20507             updateSpreadAssignment: updateSpreadAssignment,
20508             createEnumMember: createEnumMember,
20509             updateEnumMember: updateEnumMember,
20510             createSourceFile: createSourceFile,
20511             updateSourceFile: updateSourceFile,
20512             createBundle: createBundle,
20513             updateBundle: updateBundle,
20514             createUnparsedSource: createUnparsedSource,
20515             createUnparsedPrologue: createUnparsedPrologue,
20516             createUnparsedPrepend: createUnparsedPrepend,
20517             createUnparsedTextLike: createUnparsedTextLike,
20518             createUnparsedSyntheticReference: createUnparsedSyntheticReference,
20519             createInputFiles: createInputFiles,
20520             createSyntheticExpression: createSyntheticExpression,
20521             createSyntaxList: createSyntaxList,
20522             createNotEmittedStatement: createNotEmittedStatement,
20523             createPartiallyEmittedExpression: createPartiallyEmittedExpression,
20524             updatePartiallyEmittedExpression: updatePartiallyEmittedExpression,
20525             createCommaListExpression: createCommaListExpression,
20526             updateCommaListExpression: updateCommaListExpression,
20527             createEndOfDeclarationMarker: createEndOfDeclarationMarker,
20528             createMergeDeclarationMarker: createMergeDeclarationMarker,
20529             createSyntheticReferenceExpression: createSyntheticReferenceExpression,
20530             updateSyntheticReferenceExpression: updateSyntheticReferenceExpression,
20531             cloneNode: cloneNode,
20532             // Lazily load factory methods for common operator factories and utilities
20533             get createComma() { return getBinaryCreateFunction(27 /* CommaToken */); },
20534             get createAssignment() { return getBinaryCreateFunction(62 /* EqualsToken */); },
20535             get createLogicalOr() { return getBinaryCreateFunction(56 /* BarBarToken */); },
20536             get createLogicalAnd() { return getBinaryCreateFunction(55 /* AmpersandAmpersandToken */); },
20537             get createBitwiseOr() { return getBinaryCreateFunction(51 /* BarToken */); },
20538             get createBitwiseXor() { return getBinaryCreateFunction(52 /* CaretToken */); },
20539             get createBitwiseAnd() { return getBinaryCreateFunction(50 /* AmpersandToken */); },
20540             get createStrictEquality() { return getBinaryCreateFunction(36 /* EqualsEqualsEqualsToken */); },
20541             get createStrictInequality() { return getBinaryCreateFunction(37 /* ExclamationEqualsEqualsToken */); },
20542             get createEquality() { return getBinaryCreateFunction(34 /* EqualsEqualsToken */); },
20543             get createInequality() { return getBinaryCreateFunction(35 /* ExclamationEqualsToken */); },
20544             get createLessThan() { return getBinaryCreateFunction(29 /* LessThanToken */); },
20545             get createLessThanEquals() { return getBinaryCreateFunction(32 /* LessThanEqualsToken */); },
20546             get createGreaterThan() { return getBinaryCreateFunction(31 /* GreaterThanToken */); },
20547             get createGreaterThanEquals() { return getBinaryCreateFunction(33 /* GreaterThanEqualsToken */); },
20548             get createLeftShift() { return getBinaryCreateFunction(47 /* LessThanLessThanToken */); },
20549             get createRightShift() { return getBinaryCreateFunction(48 /* GreaterThanGreaterThanToken */); },
20550             get createUnsignedRightShift() { return getBinaryCreateFunction(49 /* GreaterThanGreaterThanGreaterThanToken */); },
20551             get createAdd() { return getBinaryCreateFunction(39 /* PlusToken */); },
20552             get createSubtract() { return getBinaryCreateFunction(40 /* MinusToken */); },
20553             get createMultiply() { return getBinaryCreateFunction(41 /* AsteriskToken */); },
20554             get createDivide() { return getBinaryCreateFunction(43 /* SlashToken */); },
20555             get createModulo() { return getBinaryCreateFunction(44 /* PercentToken */); },
20556             get createExponent() { return getBinaryCreateFunction(42 /* AsteriskAsteriskToken */); },
20557             get createPrefixPlus() { return getPrefixUnaryCreateFunction(39 /* PlusToken */); },
20558             get createPrefixMinus() { return getPrefixUnaryCreateFunction(40 /* MinusToken */); },
20559             get createPrefixIncrement() { return getPrefixUnaryCreateFunction(45 /* PlusPlusToken */); },
20560             get createPrefixDecrement() { return getPrefixUnaryCreateFunction(46 /* MinusMinusToken */); },
20561             get createBitwiseNot() { return getPrefixUnaryCreateFunction(54 /* TildeToken */); },
20562             get createLogicalNot() { return getPrefixUnaryCreateFunction(53 /* ExclamationToken */); },
20563             get createPostfixIncrement() { return getPostfixUnaryCreateFunction(45 /* PlusPlusToken */); },
20564             get createPostfixDecrement() { return getPostfixUnaryCreateFunction(46 /* MinusMinusToken */); },
20565             // Compound nodes
20566             createImmediatelyInvokedFunctionExpression: createImmediatelyInvokedFunctionExpression,
20567             createImmediatelyInvokedArrowFunction: createImmediatelyInvokedArrowFunction,
20568             createVoidZero: createVoidZero,
20569             createExportDefault: createExportDefault,
20570             createExternalModuleExport: createExternalModuleExport,
20571             createTypeCheck: createTypeCheck,
20572             createMethodCall: createMethodCall,
20573             createGlobalMethodCall: createGlobalMethodCall,
20574             createFunctionBindCall: createFunctionBindCall,
20575             createFunctionCallCall: createFunctionCallCall,
20576             createFunctionApplyCall: createFunctionApplyCall,
20577             createArraySliceCall: createArraySliceCall,
20578             createArrayConcatCall: createArrayConcatCall,
20579             createObjectDefinePropertyCall: createObjectDefinePropertyCall,
20580             createPropertyDescriptor: createPropertyDescriptor,
20581             createCallBinding: createCallBinding,
20582             // Utilities
20583             inlineExpressions: inlineExpressions,
20584             getInternalName: getInternalName,
20585             getLocalName: getLocalName,
20586             getExportName: getExportName,
20587             getDeclarationName: getDeclarationName,
20588             getNamespaceMemberName: getNamespaceMemberName,
20589             getExternalModuleOrNamespaceExportName: getExternalModuleOrNamespaceExportName,
20590             restoreOuterExpressions: restoreOuterExpressions,
20591             restoreEnclosingLabel: restoreEnclosingLabel,
20592             createUseStrictPrologue: createUseStrictPrologue,
20593             copyPrologue: copyPrologue,
20594             copyStandardPrologue: copyStandardPrologue,
20595             copyCustomPrologue: copyCustomPrologue,
20596             ensureUseStrict: ensureUseStrict,
20597             liftToBlock: liftToBlock,
20598             mergeLexicalEnvironment: mergeLexicalEnvironment,
20599             updateModifiers: updateModifiers,
20600         };
20601         return factory;
20602         // @api
20603         function createNodeArray(elements, hasTrailingComma) {
20604             if (elements === undefined || elements === ts.emptyArray) {
20605                 elements = [];
20606             }
20607             else if (ts.isNodeArray(elements)) {
20608                 // Ensure the transform flags have been aggregated for this NodeArray
20609                 if (elements.transformFlags === undefined) {
20610                     aggregateChildrenFlags(elements);
20611                 }
20612                 ts.Debug.attachNodeArrayDebugInfo(elements);
20613                 return elements;
20614             }
20615             // Since the element list of a node array is typically created by starting with an empty array and
20616             // repeatedly calling push(), the list may not have the optimal memory layout. We invoke slice() for
20617             // small arrays (1 to 4 elements) to give the VM a chance to allocate an optimal representation.
20618             var length = elements.length;
20619             var array = (length >= 1 && length <= 4 ? elements.slice() : elements);
20620             ts.setTextRangePosEnd(array, -1, -1);
20621             array.hasTrailingComma = !!hasTrailingComma;
20622             aggregateChildrenFlags(array);
20623             ts.Debug.attachNodeArrayDebugInfo(array);
20624             return array;
20625         }
20626         function createBaseNode(kind) {
20627             return baseFactory.createBaseNode(kind);
20628         }
20629         function createBaseDeclaration(kind, decorators, modifiers) {
20630             var node = createBaseNode(kind);
20631             node.decorators = asNodeArray(decorators);
20632             node.modifiers = asNodeArray(modifiers);
20633             node.transformFlags |=
20634                 propagateChildrenFlags(node.decorators) |
20635                     propagateChildrenFlags(node.modifiers);
20636             // NOTE: The following properties are commonly set by the binder and are added here to
20637             // ensure declarations have a stable shape.
20638             node.symbol = undefined; // initialized by binder
20639             node.localSymbol = undefined; // initialized by binder
20640             node.locals = undefined; // initialized by binder
20641             node.nextContainer = undefined; // initialized by binder
20642             return node;
20643         }
20644         function createBaseNamedDeclaration(kind, decorators, modifiers, name) {
20645             var node = createBaseDeclaration(kind, decorators, modifiers);
20646             name = asName(name);
20647             node.name = name;
20648             // The PropertyName of a member is allowed to be `await`.
20649             // We don't need to exclude `await` for type signatures since types
20650             // don't propagate child flags.
20651             if (name) {
20652                 switch (node.kind) {
20653                     case 165 /* MethodDeclaration */:
20654                     case 167 /* GetAccessor */:
20655                     case 168 /* SetAccessor */:
20656                     case 163 /* PropertyDeclaration */:
20657                     case 288 /* PropertyAssignment */:
20658                         if (ts.isIdentifier(name)) {
20659                             node.transformFlags |= propagateIdentifierNameFlags(name);
20660                             break;
20661                         }
20662                     // fall through
20663                     default:
20664                         node.transformFlags |= propagateChildFlags(name);
20665                         break;
20666                 }
20667             }
20668             return node;
20669         }
20670         function createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters) {
20671             var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
20672             node.typeParameters = asNodeArray(typeParameters);
20673             node.transformFlags |= propagateChildrenFlags(node.typeParameters);
20674             if (typeParameters)
20675                 node.transformFlags |= 1 /* ContainsTypeScript */;
20676             return node;
20677         }
20678         function createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type) {
20679             var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
20680             node.parameters = createNodeArray(parameters);
20681             node.type = type;
20682             node.transformFlags |=
20683                 propagateChildrenFlags(node.parameters) |
20684                     propagateChildFlags(node.type);
20685             if (type)
20686                 node.transformFlags |= 1 /* ContainsTypeScript */;
20687             return node;
20688         }
20689         function updateBaseSignatureDeclaration(updated, original) {
20690             // copy children used only for error reporting
20691             if (original.typeArguments)
20692                 updated.typeArguments = original.typeArguments;
20693             return update(updated, original);
20694         }
20695         function createBaseFunctionLikeDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type, body) {
20696             var node = createBaseSignatureDeclaration(kind, decorators, modifiers, name, typeParameters, parameters, type);
20697             node.body = body;
20698             node.transformFlags |= propagateChildFlags(node.body) & ~8388608 /* ContainsPossibleTopLevelAwait */;
20699             if (!body)
20700                 node.transformFlags |= 1 /* ContainsTypeScript */;
20701             return node;
20702         }
20703         function updateBaseFunctionLikeDeclaration(updated, original) {
20704             // copy children used only for error reporting
20705             if (original.exclamationToken)
20706                 updated.exclamationToken = original.exclamationToken;
20707             if (original.typeArguments)
20708                 updated.typeArguments = original.typeArguments;
20709             return updateBaseSignatureDeclaration(updated, original);
20710         }
20711         function createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses) {
20712             var node = createBaseGenericNamedDeclaration(kind, decorators, modifiers, name, typeParameters);
20713             node.heritageClauses = asNodeArray(heritageClauses);
20714             node.transformFlags |= propagateChildrenFlags(node.heritageClauses);
20715             return node;
20716         }
20717         function createBaseClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses, members) {
20718             var node = createBaseInterfaceOrClassLikeDeclaration(kind, decorators, modifiers, name, typeParameters, heritageClauses);
20719             node.members = createNodeArray(members);
20720             node.transformFlags |= propagateChildrenFlags(node.members);
20721             return node;
20722         }
20723         function createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer) {
20724             var node = createBaseNamedDeclaration(kind, decorators, modifiers, name);
20725             node.initializer = initializer;
20726             node.transformFlags |= propagateChildFlags(node.initializer);
20727             return node;
20728         }
20729         function createBaseVariableLikeDeclaration(kind, decorators, modifiers, name, type, initializer) {
20730             var node = createBaseBindingLikeDeclaration(kind, decorators, modifiers, name, initializer);
20731             node.type = type;
20732             node.transformFlags |= propagateChildFlags(type);
20733             if (type)
20734                 node.transformFlags |= 1 /* ContainsTypeScript */;
20735             return node;
20736         }
20737         //
20738         // Literals
20739         //
20740         function createBaseLiteral(kind, text) {
20741             var node = createBaseToken(kind);
20742             node.text = text;
20743             return node;
20744         }
20745         // @api
20746         function createNumericLiteral(value, numericLiteralFlags) {
20747             if (numericLiteralFlags === void 0) { numericLiteralFlags = 0 /* None */; }
20748             var node = createBaseLiteral(8 /* NumericLiteral */, typeof value === "number" ? value + "" : value);
20749             node.numericLiteralFlags = numericLiteralFlags;
20750             if (numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */)
20751                 node.transformFlags |= 256 /* ContainsES2015 */;
20752             return node;
20753         }
20754         // @api
20755         function createBigIntLiteral(value) {
20756             var node = createBaseLiteral(9 /* BigIntLiteral */, typeof value === "string" ? value : ts.pseudoBigIntToString(value) + "n");
20757             node.transformFlags |= 4 /* ContainsESNext */;
20758             return node;
20759         }
20760         function createBaseStringLiteral(text, isSingleQuote) {
20761             var node = createBaseLiteral(10 /* StringLiteral */, text);
20762             node.singleQuote = isSingleQuote;
20763             return node;
20764         }
20765         // @api
20766         function createStringLiteral(text, isSingleQuote, hasExtendedUnicodeEscape) {
20767             var node = createBaseStringLiteral(text, isSingleQuote);
20768             node.hasExtendedUnicodeEscape = hasExtendedUnicodeEscape;
20769             if (hasExtendedUnicodeEscape)
20770                 node.transformFlags |= 256 /* ContainsES2015 */;
20771             return node;
20772         }
20773         // @api
20774         function createStringLiteralFromNode(sourceNode) {
20775             var node = createBaseStringLiteral(ts.getTextOfIdentifierOrLiteral(sourceNode), /*isSingleQuote*/ undefined);
20776             node.textSourceNode = sourceNode;
20777             return node;
20778         }
20779         // @api
20780         function createRegularExpressionLiteral(text) {
20781             var node = createBaseLiteral(13 /* RegularExpressionLiteral */, text);
20782             return node;
20783         }
20784         // @api
20785         function createLiteralLikeNode(kind, text) {
20786             switch (kind) {
20787                 case 8 /* NumericLiteral */: return createNumericLiteral(text, /*numericLiteralFlags*/ 0);
20788                 case 9 /* BigIntLiteral */: return createBigIntLiteral(text);
20789                 case 10 /* StringLiteral */: return createStringLiteral(text, /*isSingleQuote*/ undefined);
20790                 case 11 /* JsxText */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ false);
20791                 case 12 /* JsxTextAllWhiteSpaces */: return createJsxText(text, /*containsOnlyTriviaWhiteSpaces*/ true);
20792                 case 13 /* RegularExpressionLiteral */: return createRegularExpressionLiteral(text);
20793                 case 14 /* NoSubstitutionTemplateLiteral */: return createTemplateLiteralLikeNode(kind, text, /*rawText*/ undefined, /*templateFlags*/ 0);
20794             }
20795         }
20796         //
20797         // Identifiers
20798         //
20799         function createBaseIdentifier(text, originalKeywordKind) {
20800             if (originalKeywordKind === undefined && text) {
20801                 originalKeywordKind = ts.stringToToken(text);
20802             }
20803             if (originalKeywordKind === 78 /* Identifier */) {
20804                 originalKeywordKind = undefined;
20805             }
20806             var node = baseFactory.createBaseIdentifierNode(78 /* Identifier */);
20807             node.originalKeywordKind = originalKeywordKind;
20808             node.escapedText = ts.escapeLeadingUnderscores(text);
20809             return node;
20810         }
20811         function createBaseGeneratedIdentifier(text, autoGenerateFlags) {
20812             var node = createBaseIdentifier(text, /*originalKeywordKind*/ undefined);
20813             node.autoGenerateFlags = autoGenerateFlags;
20814             node.autoGenerateId = nextAutoGenerateId;
20815             nextAutoGenerateId++;
20816             return node;
20817         }
20818         // @api
20819         function createIdentifier(text, typeArguments, originalKeywordKind) {
20820             var node = createBaseIdentifier(text, originalKeywordKind);
20821             if (typeArguments) {
20822                 // NOTE: we do not use `setChildren` here because typeArguments in an identifier do not contribute to transformations
20823                 node.typeArguments = createNodeArray(typeArguments);
20824             }
20825             if (node.originalKeywordKind === 130 /* AwaitKeyword */) {
20826                 node.transformFlags |= 8388608 /* ContainsPossibleTopLevelAwait */;
20827             }
20828             return node;
20829         }
20830         // @api
20831         function updateIdentifier(node, typeArguments) {
20832             return node.typeArguments !== typeArguments
20833                 ? update(createIdentifier(ts.idText(node), typeArguments), node)
20834                 : node;
20835         }
20836         // @api
20837         function createTempVariable(recordTempVariable, reservedInNestedScopes) {
20838             var flags = 1 /* Auto */;
20839             if (reservedInNestedScopes)
20840                 flags |= 8 /* ReservedInNestedScopes */;
20841             var name = createBaseGeneratedIdentifier("", flags);
20842             if (recordTempVariable) {
20843                 recordTempVariable(name);
20844             }
20845             return name;
20846         }
20847         /** Create a unique temporary variable for use in a loop. */
20848         // @api
20849         function createLoopVariable() {
20850             return createBaseGeneratedIdentifier("", 2 /* Loop */);
20851         }
20852         /** Create a unique name based on the supplied text. */
20853         // @api
20854         function createUniqueName(text, flags) {
20855             if (flags === void 0) { flags = 0 /* None */; }
20856             ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
20857             ts.Debug.assert((flags & (16 /* Optimistic */ | 32 /* FileLevel */)) !== 32 /* FileLevel */, "GeneratedIdentifierFlags.FileLevel cannot be set without also setting GeneratedIdentifierFlags.Optimistic");
20858             return createBaseGeneratedIdentifier(text, 3 /* Unique */ | flags);
20859         }
20860         /** Create a unique name generated for a node. */
20861         // @api
20862         function getGeneratedNameForNode(node, flags) {
20863             if (flags === void 0) { flags = 0; }
20864             ts.Debug.assert(!(flags & 7 /* KindMask */), "Argument out of range: flags");
20865             var name = createBaseGeneratedIdentifier(node && ts.isIdentifier(node) ? ts.idText(node) : "", 4 /* Node */ | flags);
20866             name.original = node;
20867             return name;
20868         }
20869         // @api
20870         function createPrivateIdentifier(text) {
20871             if (!ts.startsWith(text, "#"))
20872                 ts.Debug.fail("First character of private identifier must be #: " + text);
20873             var node = baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */);
20874             node.escapedText = ts.escapeLeadingUnderscores(text);
20875             node.transformFlags |= 4194304 /* ContainsClassFields */;
20876             return node;
20877         }
20878         //
20879         // Punctuation
20880         //
20881         function createBaseToken(kind) {
20882             return baseFactory.createBaseTokenNode(kind);
20883         }
20884         function createToken(token) {
20885             ts.Debug.assert(token >= 0 /* FirstToken */ && token <= 156 /* LastToken */, "Invalid token");
20886             ts.Debug.assert(token <= 14 /* FirstTemplateToken */ || token >= 17 /* LastTemplateToken */, "Invalid token. Use 'createTemplateLiteralLikeNode' to create template literals.");
20887             ts.Debug.assert(token <= 8 /* FirstLiteralToken */ || token >= 14 /* LastLiteralToken */, "Invalid token. Use 'createLiteralLikeNode' to create literals.");
20888             ts.Debug.assert(token !== 78 /* Identifier */, "Invalid token. Use 'createIdentifier' to create identifiers");
20889             var node = createBaseToken(token);
20890             var transformFlags = 0 /* None */;
20891             switch (token) {
20892                 case 129 /* AsyncKeyword */:
20893                     // 'async' modifier is ES2017 (async functions) or ES2018 (async generators)
20894                     transformFlags =
20895                         64 /* ContainsES2017 */ |
20896                             32 /* ContainsES2018 */;
20897                     break;
20898                 case 122 /* PublicKeyword */:
20899                 case 120 /* PrivateKeyword */:
20900                 case 121 /* ProtectedKeyword */:
20901                 case 142 /* ReadonlyKeyword */:
20902                 case 125 /* AbstractKeyword */:
20903                 case 133 /* DeclareKeyword */:
20904                 case 84 /* ConstKeyword */:
20905                 case 128 /* AnyKeyword */:
20906                 case 144 /* NumberKeyword */:
20907                 case 155 /* BigIntKeyword */:
20908                 case 141 /* NeverKeyword */:
20909                 case 145 /* ObjectKeyword */:
20910                 case 147 /* StringKeyword */:
20911                 case 131 /* BooleanKeyword */:
20912                 case 148 /* SymbolKeyword */:
20913                 case 113 /* VoidKeyword */:
20914                 case 152 /* UnknownKeyword */:
20915                 case 150 /* UndefinedKeyword */: // `undefined` is an Identifier in the expression case.
20916                     transformFlags = 1 /* ContainsTypeScript */;
20917                     break;
20918                 case 123 /* StaticKeyword */:
20919                 case 105 /* SuperKeyword */:
20920                     transformFlags = 256 /* ContainsES2015 */;
20921                     break;
20922                 case 107 /* ThisKeyword */:
20923                     // 'this' indicates a lexical 'this'
20924                     transformFlags = 4096 /* ContainsLexicalThis */;
20925                     break;
20926             }
20927             if (transformFlags) {
20928                 node.transformFlags |= transformFlags;
20929             }
20930             return node;
20931         }
20932         //
20933         // Reserved words
20934         //
20935         // @api
20936         function createSuper() {
20937             return createToken(105 /* SuperKeyword */);
20938         }
20939         // @api
20940         function createThis() {
20941             return createToken(107 /* ThisKeyword */);
20942         }
20943         // @api
20944         function createNull() {
20945             return createToken(103 /* NullKeyword */);
20946         }
20947         // @api
20948         function createTrue() {
20949             return createToken(109 /* TrueKeyword */);
20950         }
20951         // @api
20952         function createFalse() {
20953             return createToken(94 /* FalseKeyword */);
20954         }
20955         //
20956         // Modifiers
20957         //
20958         // @api
20959         function createModifier(kind) {
20960             return createToken(kind);
20961         }
20962         // @api
20963         function createModifiersFromModifierFlags(flags) {
20964             var result = [];
20965             if (flags & 1 /* Export */) {
20966                 result.push(createModifier(92 /* ExportKeyword */));
20967             }
20968             if (flags & 2 /* Ambient */) {
20969                 result.push(createModifier(133 /* DeclareKeyword */));
20970             }
20971             if (flags & 512 /* Default */) {
20972                 result.push(createModifier(87 /* DefaultKeyword */));
20973             }
20974             if (flags & 2048 /* Const */) {
20975                 result.push(createModifier(84 /* ConstKeyword */));
20976             }
20977             if (flags & 4 /* Public */) {
20978                 result.push(createModifier(122 /* PublicKeyword */));
20979             }
20980             if (flags & 8 /* Private */) {
20981                 result.push(createModifier(120 /* PrivateKeyword */));
20982             }
20983             if (flags & 16 /* Protected */) {
20984                 result.push(createModifier(121 /* ProtectedKeyword */));
20985             }
20986             if (flags & 128 /* Abstract */) {
20987                 result.push(createModifier(125 /* AbstractKeyword */));
20988             }
20989             if (flags & 32 /* Static */) {
20990                 result.push(createModifier(123 /* StaticKeyword */));
20991             }
20992             if (flags & 64 /* Readonly */) {
20993                 result.push(createModifier(142 /* ReadonlyKeyword */));
20994             }
20995             if (flags & 256 /* Async */) {
20996                 result.push(createModifier(129 /* AsyncKeyword */));
20997             }
20998             return result;
20999         }
21000         //
21001         // Names
21002         //
21003         // @api
21004         function createQualifiedName(left, right) {
21005             var node = createBaseNode(157 /* QualifiedName */);
21006             node.left = left;
21007             node.right = asName(right);
21008             node.transformFlags |=
21009                 propagateChildFlags(node.left) |
21010                     propagateIdentifierNameFlags(node.right);
21011             return node;
21012         }
21013         // @api
21014         function updateQualifiedName(node, left, right) {
21015             return node.left !== left
21016                 || node.right !== right
21017                 ? update(createQualifiedName(left, right), node)
21018                 : node;
21019         }
21020         // @api
21021         function createComputedPropertyName(expression) {
21022             var node = createBaseNode(158 /* ComputedPropertyName */);
21023             node.expression = parenthesizerRules().parenthesizeExpressionOfComputedPropertyName(expression);
21024             node.transformFlags |=
21025                 propagateChildFlags(node.expression) |
21026                     256 /* ContainsES2015 */ |
21027                     32768 /* ContainsComputedPropertyName */;
21028             return node;
21029         }
21030         // @api
21031         function updateComputedPropertyName(node, expression) {
21032             return node.expression !== expression
21033                 ? update(createComputedPropertyName(expression), node)
21034                 : node;
21035         }
21036         //
21037         // Signature elements
21038         //
21039         // @api
21040         function createTypeParameterDeclaration(name, constraint, defaultType) {
21041             var node = createBaseNamedDeclaration(159 /* TypeParameter */, 
21042             /*decorators*/ undefined, 
21043             /*modifiers*/ undefined, name);
21044             node.constraint = constraint;
21045             node.default = defaultType;
21046             node.transformFlags = 1 /* ContainsTypeScript */;
21047             return node;
21048         }
21049         // @api
21050         function updateTypeParameterDeclaration(node, name, constraint, defaultType) {
21051             return node.name !== name
21052                 || node.constraint !== constraint
21053                 || node.default !== defaultType
21054                 ? update(createTypeParameterDeclaration(name, constraint, defaultType), node)
21055                 : node;
21056         }
21057         // @api
21058         function createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
21059             var node = createBaseVariableLikeDeclaration(160 /* Parameter */, decorators, modifiers, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
21060             node.dotDotDotToken = dotDotDotToken;
21061             node.questionToken = questionToken;
21062             if (ts.isThisIdentifier(node.name)) {
21063                 node.transformFlags = 1 /* ContainsTypeScript */;
21064             }
21065             else {
21066                 node.transformFlags |=
21067                     propagateChildFlags(node.dotDotDotToken) |
21068                         propagateChildFlags(node.questionToken);
21069                 if (questionToken)
21070                     node.transformFlags |= 1 /* ContainsTypeScript */;
21071                 if (ts.modifiersToFlags(node.modifiers) & 92 /* ParameterPropertyModifier */)
21072                     node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
21073                 if (initializer || dotDotDotToken)
21074                     node.transformFlags |= 256 /* ContainsES2015 */;
21075             }
21076             return node;
21077         }
21078         // @api
21079         function updateParameterDeclaration(node, decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer) {
21080             return node.decorators !== decorators
21081                 || node.modifiers !== modifiers
21082                 || node.dotDotDotToken !== dotDotDotToken
21083                 || node.name !== name
21084                 || node.questionToken !== questionToken
21085                 || node.type !== type
21086                 || node.initializer !== initializer
21087                 ? update(createParameterDeclaration(decorators, modifiers, dotDotDotToken, name, questionToken, type, initializer), node)
21088                 : node;
21089         }
21090         // @api
21091         function createDecorator(expression) {
21092             var node = createBaseNode(161 /* Decorator */);
21093             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21094             node.transformFlags |=
21095                 propagateChildFlags(node.expression) |
21096                     1 /* ContainsTypeScript */ |
21097                     2048 /* ContainsTypeScriptClassSyntax */;
21098             return node;
21099         }
21100         // @api
21101         function updateDecorator(node, expression) {
21102             return node.expression !== expression
21103                 ? update(createDecorator(expression), node)
21104                 : node;
21105         }
21106         //
21107         // Type Elements
21108         //
21109         // @api
21110         function createPropertySignature(modifiers, name, questionToken, type) {
21111             var node = createBaseNamedDeclaration(162 /* PropertySignature */, 
21112             /*decorators*/ undefined, modifiers, name);
21113             node.type = type;
21114             node.questionToken = questionToken;
21115             node.transformFlags = 1 /* ContainsTypeScript */;
21116             return node;
21117         }
21118         // @api
21119         function updatePropertySignature(node, modifiers, name, questionToken, type) {
21120             return node.modifiers !== modifiers
21121                 || node.name !== name
21122                 || node.questionToken !== questionToken
21123                 || node.type !== type
21124                 ? update(createPropertySignature(modifiers, name, questionToken, type), node)
21125                 : node;
21126         }
21127         // @api
21128         function createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
21129             var node = createBaseVariableLikeDeclaration(163 /* PropertyDeclaration */, decorators, modifiers, name, type, initializer);
21130             node.questionToken = questionOrExclamationToken && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
21131             node.exclamationToken = questionOrExclamationToken && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined;
21132             node.transformFlags |=
21133                 propagateChildFlags(node.questionToken) |
21134                     propagateChildFlags(node.exclamationToken) |
21135                     4194304 /* ContainsClassFields */;
21136             if (ts.isComputedPropertyName(node.name) || (ts.hasStaticModifier(node) && node.initializer)) {
21137                 node.transformFlags |= 2048 /* ContainsTypeScriptClassSyntax */;
21138             }
21139             if (questionOrExclamationToken || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
21140                 node.transformFlags |= 1 /* ContainsTypeScript */;
21141             }
21142             return node;
21143         }
21144         // @api
21145         function updatePropertyDeclaration(node, decorators, modifiers, name, questionOrExclamationToken, type, initializer) {
21146             return node.decorators !== decorators
21147                 || node.modifiers !== modifiers
21148                 || node.name !== name
21149                 || node.questionToken !== (questionOrExclamationToken !== undefined && ts.isQuestionToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
21150                 || node.exclamationToken !== (questionOrExclamationToken !== undefined && ts.isExclamationToken(questionOrExclamationToken) ? questionOrExclamationToken : undefined)
21151                 || node.type !== type
21152                 || node.initializer !== initializer
21153                 ? update(createPropertyDeclaration(decorators, modifiers, name, questionOrExclamationToken, type, initializer), node)
21154                 : node;
21155         }
21156         // @api
21157         function createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type) {
21158             var node = createBaseSignatureDeclaration(164 /* MethodSignature */, 
21159             /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type);
21160             node.questionToken = questionToken;
21161             node.transformFlags = 1 /* ContainsTypeScript */;
21162             return node;
21163         }
21164         // @api
21165         function updateMethodSignature(node, modifiers, name, questionToken, typeParameters, parameters, type) {
21166             return node.modifiers !== modifiers
21167                 || node.name !== name
21168                 || node.questionToken !== questionToken
21169                 || node.typeParameters !== typeParameters
21170                 || node.parameters !== parameters
21171                 || node.type !== type
21172                 ? updateBaseSignatureDeclaration(createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type), node)
21173                 : node;
21174         }
21175         // @api
21176         function createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
21177             var node = createBaseFunctionLikeDeclaration(165 /* MethodDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
21178             node.asteriskToken = asteriskToken;
21179             node.questionToken = questionToken;
21180             node.transformFlags |=
21181                 propagateChildFlags(node.asteriskToken) |
21182                     propagateChildFlags(node.questionToken) |
21183                     256 /* ContainsES2015 */;
21184             if (questionToken) {
21185                 node.transformFlags |= 1 /* ContainsTypeScript */;
21186             }
21187             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
21188                 if (asteriskToken) {
21189                     node.transformFlags |= 32 /* ContainsES2018 */;
21190                 }
21191                 else {
21192                     node.transformFlags |= 64 /* ContainsES2017 */;
21193                 }
21194             }
21195             else if (asteriskToken) {
21196                 node.transformFlags |= 512 /* ContainsGenerator */;
21197             }
21198             return node;
21199         }
21200         // @api
21201         function updateMethodDeclaration(node, decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body) {
21202             return node.decorators !== decorators
21203                 || node.modifiers !== modifiers
21204                 || node.asteriskToken !== asteriskToken
21205                 || node.name !== name
21206                 || node.questionToken !== questionToken
21207                 || node.typeParameters !== typeParameters
21208                 || node.parameters !== parameters
21209                 || node.type !== type
21210                 || node.body !== body
21211                 ? updateBaseFunctionLikeDeclaration(createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body), node)
21212                 : node;
21213         }
21214         // @api
21215         function createConstructorDeclaration(decorators, modifiers, parameters, body) {
21216             var node = createBaseFunctionLikeDeclaration(166 /* Constructor */, decorators, modifiers, 
21217             /*name*/ undefined, 
21218             /*typeParameters*/ undefined, parameters, 
21219             /*type*/ undefined, body);
21220             node.transformFlags |= 256 /* ContainsES2015 */;
21221             return node;
21222         }
21223         // @api
21224         function updateConstructorDeclaration(node, decorators, modifiers, parameters, body) {
21225             return node.decorators !== decorators
21226                 || node.modifiers !== modifiers
21227                 || node.parameters !== parameters
21228                 || node.body !== body
21229                 ? updateBaseFunctionLikeDeclaration(createConstructorDeclaration(decorators, modifiers, parameters, body), node)
21230                 : node;
21231         }
21232         // @api
21233         function createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body) {
21234             return createBaseFunctionLikeDeclaration(167 /* GetAccessor */, decorators, modifiers, name, 
21235             /*typeParameters*/ undefined, parameters, type, body);
21236         }
21237         // @api
21238         function updateGetAccessorDeclaration(node, decorators, modifiers, name, parameters, type, body) {
21239             return node.decorators !== decorators
21240                 || node.modifiers !== modifiers
21241                 || node.name !== name
21242                 || node.parameters !== parameters
21243                 || node.type !== type
21244                 || node.body !== body
21245                 ? updateBaseFunctionLikeDeclaration(createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body), node)
21246                 : node;
21247         }
21248         // @api
21249         function createSetAccessorDeclaration(decorators, modifiers, name, parameters, body) {
21250             return createBaseFunctionLikeDeclaration(168 /* SetAccessor */, decorators, modifiers, name, 
21251             /*typeParameters*/ undefined, parameters, 
21252             /*type*/ undefined, body);
21253         }
21254         // @api
21255         function updateSetAccessorDeclaration(node, decorators, modifiers, name, parameters, body) {
21256             return node.decorators !== decorators
21257                 || node.modifiers !== modifiers
21258                 || node.name !== name
21259                 || node.parameters !== parameters
21260                 || node.body !== body
21261                 ? updateBaseFunctionLikeDeclaration(createSetAccessorDeclaration(decorators, modifiers, name, parameters, body), node)
21262                 : node;
21263         }
21264         // @api
21265         function createCallSignature(typeParameters, parameters, type) {
21266             var node = createBaseSignatureDeclaration(169 /* CallSignature */, 
21267             /*decorators*/ undefined, 
21268             /*modifiers*/ undefined, 
21269             /*name*/ undefined, typeParameters, parameters, type);
21270             node.transformFlags = 1 /* ContainsTypeScript */;
21271             return node;
21272         }
21273         // @api
21274         function updateCallSignature(node, typeParameters, parameters, type) {
21275             return node.typeParameters !== typeParameters
21276                 || node.parameters !== parameters
21277                 || node.type !== type
21278                 ? updateBaseSignatureDeclaration(createCallSignature(typeParameters, parameters, type), node)
21279                 : node;
21280         }
21281         // @api
21282         function createConstructSignature(typeParameters, parameters, type) {
21283             var node = createBaseSignatureDeclaration(170 /* ConstructSignature */, 
21284             /*decorators*/ undefined, 
21285             /*modifiers*/ undefined, 
21286             /*name*/ undefined, typeParameters, parameters, type);
21287             node.transformFlags = 1 /* ContainsTypeScript */;
21288             return node;
21289         }
21290         // @api
21291         function updateConstructSignature(node, typeParameters, parameters, type) {
21292             return node.typeParameters !== typeParameters
21293                 || node.parameters !== parameters
21294                 || node.type !== type
21295                 ? updateBaseSignatureDeclaration(createConstructSignature(typeParameters, parameters, type), node)
21296                 : node;
21297         }
21298         // @api
21299         function createIndexSignature(decorators, modifiers, parameters, type) {
21300             var node = createBaseSignatureDeclaration(171 /* IndexSignature */, decorators, modifiers, 
21301             /*name*/ undefined, 
21302             /*typeParameters*/ undefined, parameters, type);
21303             node.transformFlags = 1 /* ContainsTypeScript */;
21304             return node;
21305         }
21306         // @api
21307         function updateIndexSignature(node, decorators, modifiers, parameters, type) {
21308             return node.parameters !== parameters
21309                 || node.type !== type
21310                 || node.decorators !== decorators
21311                 || node.modifiers !== modifiers
21312                 ? updateBaseSignatureDeclaration(createIndexSignature(decorators, modifiers, parameters, type), node)
21313                 : node;
21314         }
21315         // @api
21316         function createTemplateLiteralTypeSpan(type, literal) {
21317             var node = createBaseNode(194 /* TemplateLiteralTypeSpan */);
21318             node.type = type;
21319             node.literal = literal;
21320             node.transformFlags = 1 /* ContainsTypeScript */;
21321             return node;
21322         }
21323         // @api
21324         function updateTemplateLiteralTypeSpan(node, type, literal) {
21325             return node.type !== type
21326                 || node.literal !== literal
21327                 ? update(createTemplateLiteralTypeSpan(type, literal), node)
21328                 : node;
21329         }
21330         //
21331         // Types
21332         //
21333         // @api
21334         function createKeywordTypeNode(kind) {
21335             return createToken(kind);
21336         }
21337         // @api
21338         function createTypePredicateNode(assertsModifier, parameterName, type) {
21339             var node = createBaseNode(172 /* TypePredicate */);
21340             node.assertsModifier = assertsModifier;
21341             node.parameterName = asName(parameterName);
21342             node.type = type;
21343             node.transformFlags = 1 /* ContainsTypeScript */;
21344             return node;
21345         }
21346         // @api
21347         function updateTypePredicateNode(node, assertsModifier, parameterName, type) {
21348             return node.assertsModifier !== assertsModifier
21349                 || node.parameterName !== parameterName
21350                 || node.type !== type
21351                 ? update(createTypePredicateNode(assertsModifier, parameterName, type), node)
21352                 : node;
21353         }
21354         // @api
21355         function createTypeReferenceNode(typeName, typeArguments) {
21356             var node = createBaseNode(173 /* TypeReference */);
21357             node.typeName = asName(typeName);
21358             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(createNodeArray(typeArguments));
21359             node.transformFlags = 1 /* ContainsTypeScript */;
21360             return node;
21361         }
21362         // @api
21363         function updateTypeReferenceNode(node, typeName, typeArguments) {
21364             return node.typeName !== typeName
21365                 || node.typeArguments !== typeArguments
21366                 ? update(createTypeReferenceNode(typeName, typeArguments), node)
21367                 : node;
21368         }
21369         // @api
21370         function createFunctionTypeNode(typeParameters, parameters, type) {
21371             var node = createBaseSignatureDeclaration(174 /* FunctionType */, 
21372             /*decorators*/ undefined, 
21373             /*modifiers*/ undefined, 
21374             /*name*/ undefined, typeParameters, parameters, type);
21375             node.transformFlags = 1 /* ContainsTypeScript */;
21376             return node;
21377         }
21378         // @api
21379         function updateFunctionTypeNode(node, typeParameters, parameters, type) {
21380             return node.typeParameters !== typeParameters
21381                 || node.parameters !== parameters
21382                 || node.type !== type
21383                 ? updateBaseSignatureDeclaration(createFunctionTypeNode(typeParameters, parameters, type), node)
21384                 : node;
21385         }
21386         // @api
21387         function createConstructorTypeNode(typeParameters, parameters, type) {
21388             var node = createBaseSignatureDeclaration(175 /* ConstructorType */, 
21389             /*decorators*/ undefined, 
21390             /*modifiers*/ undefined, 
21391             /*name*/ undefined, typeParameters, parameters, type);
21392             node.transformFlags = 1 /* ContainsTypeScript */;
21393             return node;
21394         }
21395         // @api
21396         function updateConstructorTypeNode(node, typeParameters, parameters, type) {
21397             return node.typeParameters !== typeParameters
21398                 || node.parameters !== parameters
21399                 || node.type !== type
21400                 ? updateBaseSignatureDeclaration(createConstructorTypeNode(typeParameters, parameters, type), node)
21401                 : node;
21402         }
21403         // @api
21404         function createTypeQueryNode(exprName) {
21405             var node = createBaseNode(176 /* TypeQuery */);
21406             node.exprName = exprName;
21407             node.transformFlags = 1 /* ContainsTypeScript */;
21408             return node;
21409         }
21410         // @api
21411         function updateTypeQueryNode(node, exprName) {
21412             return node.exprName !== exprName
21413                 ? update(createTypeQueryNode(exprName), node)
21414                 : node;
21415         }
21416         // @api
21417         function createTypeLiteralNode(members) {
21418             var node = createBaseNode(177 /* TypeLiteral */);
21419             node.members = createNodeArray(members);
21420             node.transformFlags = 1 /* ContainsTypeScript */;
21421             return node;
21422         }
21423         // @api
21424         function updateTypeLiteralNode(node, members) {
21425             return node.members !== members
21426                 ? update(createTypeLiteralNode(members), node)
21427                 : node;
21428         }
21429         // @api
21430         function createArrayTypeNode(elementType) {
21431             var node = createBaseNode(178 /* ArrayType */);
21432             node.elementType = parenthesizerRules().parenthesizeElementTypeOfArrayType(elementType);
21433             node.transformFlags = 1 /* ContainsTypeScript */;
21434             return node;
21435         }
21436         // @api
21437         function updateArrayTypeNode(node, elementType) {
21438             return node.elementType !== elementType
21439                 ? update(createArrayTypeNode(elementType), node)
21440                 : node;
21441         }
21442         // @api
21443         function createTupleTypeNode(elements) {
21444             var node = createBaseNode(179 /* TupleType */);
21445             node.elements = createNodeArray(elements);
21446             node.transformFlags = 1 /* ContainsTypeScript */;
21447             return node;
21448         }
21449         // @api
21450         function updateTupleTypeNode(node, elements) {
21451             return node.elements !== elements
21452                 ? update(createTupleTypeNode(elements), node)
21453                 : node;
21454         }
21455         // @api
21456         function createNamedTupleMember(dotDotDotToken, name, questionToken, type) {
21457             var node = createBaseNode(192 /* NamedTupleMember */);
21458             node.dotDotDotToken = dotDotDotToken;
21459             node.name = name;
21460             node.questionToken = questionToken;
21461             node.type = type;
21462             node.transformFlags = 1 /* ContainsTypeScript */;
21463             return node;
21464         }
21465         // @api
21466         function updateNamedTupleMember(node, dotDotDotToken, name, questionToken, type) {
21467             return node.dotDotDotToken !== dotDotDotToken
21468                 || node.name !== name
21469                 || node.questionToken !== questionToken
21470                 || node.type !== type
21471                 ? update(createNamedTupleMember(dotDotDotToken, name, questionToken, type), node)
21472                 : node;
21473         }
21474         // @api
21475         function createOptionalTypeNode(type) {
21476             var node = createBaseNode(180 /* OptionalType */);
21477             node.type = parenthesizerRules().parenthesizeElementTypeOfArrayType(type);
21478             node.transformFlags = 1 /* ContainsTypeScript */;
21479             return node;
21480         }
21481         // @api
21482         function updateOptionalTypeNode(node, type) {
21483             return node.type !== type
21484                 ? update(createOptionalTypeNode(type), node)
21485                 : node;
21486         }
21487         // @api
21488         function createRestTypeNode(type) {
21489             var node = createBaseNode(181 /* RestType */);
21490             node.type = type;
21491             node.transformFlags = 1 /* ContainsTypeScript */;
21492             return node;
21493         }
21494         // @api
21495         function updateRestTypeNode(node, type) {
21496             return node.type !== type
21497                 ? update(createRestTypeNode(type), node)
21498                 : node;
21499         }
21500         function createUnionOrIntersectionTypeNode(kind, types) {
21501             var node = createBaseNode(kind);
21502             node.types = parenthesizerRules().parenthesizeConstituentTypesOfUnionOrIntersectionType(types);
21503             node.transformFlags = 1 /* ContainsTypeScript */;
21504             return node;
21505         }
21506         function updateUnionOrIntersectionTypeNode(node, types) {
21507             return node.types !== types
21508                 ? update(createUnionOrIntersectionTypeNode(node.kind, types), node)
21509                 : node;
21510         }
21511         // @api
21512         function createUnionTypeNode(types) {
21513             return createUnionOrIntersectionTypeNode(182 /* UnionType */, types);
21514         }
21515         // @api
21516         function updateUnionTypeNode(node, types) {
21517             return updateUnionOrIntersectionTypeNode(node, types);
21518         }
21519         // @api
21520         function createIntersectionTypeNode(types) {
21521             return createUnionOrIntersectionTypeNode(183 /* IntersectionType */, types);
21522         }
21523         // @api
21524         function updateIntersectionTypeNode(node, types) {
21525             return updateUnionOrIntersectionTypeNode(node, types);
21526         }
21527         // @api
21528         function createConditionalTypeNode(checkType, extendsType, trueType, falseType) {
21529             var node = createBaseNode(184 /* ConditionalType */);
21530             node.checkType = parenthesizerRules().parenthesizeMemberOfConditionalType(checkType);
21531             node.extendsType = parenthesizerRules().parenthesizeMemberOfConditionalType(extendsType);
21532             node.trueType = trueType;
21533             node.falseType = falseType;
21534             node.transformFlags = 1 /* ContainsTypeScript */;
21535             return node;
21536         }
21537         // @api
21538         function updateConditionalTypeNode(node, checkType, extendsType, trueType, falseType) {
21539             return node.checkType !== checkType
21540                 || node.extendsType !== extendsType
21541                 || node.trueType !== trueType
21542                 || node.falseType !== falseType
21543                 ? update(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
21544                 : node;
21545         }
21546         // @api
21547         function createInferTypeNode(typeParameter) {
21548             var node = createBaseNode(185 /* InferType */);
21549             node.typeParameter = typeParameter;
21550             node.transformFlags = 1 /* ContainsTypeScript */;
21551             return node;
21552         }
21553         // @api
21554         function updateInferTypeNode(node, typeParameter) {
21555             return node.typeParameter !== typeParameter
21556                 ? update(createInferTypeNode(typeParameter), node)
21557                 : node;
21558         }
21559         // @api
21560         function createTemplateLiteralType(head, templateSpans) {
21561             var node = createBaseNode(193 /* TemplateLiteralType */);
21562             node.head = head;
21563             node.templateSpans = createNodeArray(templateSpans);
21564             node.transformFlags = 1 /* ContainsTypeScript */;
21565             return node;
21566         }
21567         // @api
21568         function updateTemplateLiteralType(node, head, templateSpans) {
21569             return node.head !== head
21570                 || node.templateSpans !== templateSpans
21571                 ? update(createTemplateLiteralType(head, templateSpans), node)
21572                 : node;
21573         }
21574         // @api
21575         function createImportTypeNode(argument, qualifier, typeArguments, isTypeOf) {
21576             if (isTypeOf === void 0) { isTypeOf = false; }
21577             var node = createBaseNode(195 /* ImportType */);
21578             node.argument = argument;
21579             node.qualifier = qualifier;
21580             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
21581             node.isTypeOf = isTypeOf;
21582             node.transformFlags = 1 /* ContainsTypeScript */;
21583             return node;
21584         }
21585         // @api
21586         function updateImportTypeNode(node, argument, qualifier, typeArguments, isTypeOf) {
21587             if (isTypeOf === void 0) { isTypeOf = node.isTypeOf; }
21588             return node.argument !== argument
21589                 || node.qualifier !== qualifier
21590                 || node.typeArguments !== typeArguments
21591                 || node.isTypeOf !== isTypeOf
21592                 ? update(createImportTypeNode(argument, qualifier, typeArguments, isTypeOf), node)
21593                 : node;
21594         }
21595         // @api
21596         function createParenthesizedType(type) {
21597             var node = createBaseNode(186 /* ParenthesizedType */);
21598             node.type = type;
21599             node.transformFlags = 1 /* ContainsTypeScript */;
21600             return node;
21601         }
21602         // @api
21603         function updateParenthesizedType(node, type) {
21604             return node.type !== type
21605                 ? update(createParenthesizedType(type), node)
21606                 : node;
21607         }
21608         // @api
21609         function createThisTypeNode() {
21610             var node = createBaseNode(187 /* ThisType */);
21611             node.transformFlags = 1 /* ContainsTypeScript */;
21612             return node;
21613         }
21614         // @api
21615         function createTypeOperatorNode(operator, type) {
21616             var node = createBaseNode(188 /* TypeOperator */);
21617             node.operator = operator;
21618             node.type = parenthesizerRules().parenthesizeMemberOfElementType(type);
21619             node.transformFlags = 1 /* ContainsTypeScript */;
21620             return node;
21621         }
21622         // @api
21623         function updateTypeOperatorNode(node, type) {
21624             return node.type !== type
21625                 ? update(createTypeOperatorNode(node.operator, type), node)
21626                 : node;
21627         }
21628         // @api
21629         function createIndexedAccessTypeNode(objectType, indexType) {
21630             var node = createBaseNode(189 /* IndexedAccessType */);
21631             node.objectType = parenthesizerRules().parenthesizeMemberOfElementType(objectType);
21632             node.indexType = indexType;
21633             node.transformFlags = 1 /* ContainsTypeScript */;
21634             return node;
21635         }
21636         // @api
21637         function updateIndexedAccessTypeNode(node, objectType, indexType) {
21638             return node.objectType !== objectType
21639                 || node.indexType !== indexType
21640                 ? update(createIndexedAccessTypeNode(objectType, indexType), node)
21641                 : node;
21642         }
21643         // @api
21644         function createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type) {
21645             var node = createBaseNode(190 /* MappedType */);
21646             node.readonlyToken = readonlyToken;
21647             node.typeParameter = typeParameter;
21648             node.nameType = nameType;
21649             node.questionToken = questionToken;
21650             node.type = type;
21651             node.transformFlags = 1 /* ContainsTypeScript */;
21652             return node;
21653         }
21654         // @api
21655         function updateMappedTypeNode(node, readonlyToken, typeParameter, nameType, questionToken, type) {
21656             return node.readonlyToken !== readonlyToken
21657                 || node.typeParameter !== typeParameter
21658                 || node.nameType !== nameType
21659                 || node.questionToken !== questionToken
21660                 || node.type !== type
21661                 ? update(createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), node)
21662                 : node;
21663         }
21664         // @api
21665         function createLiteralTypeNode(literal) {
21666             var node = createBaseNode(191 /* LiteralType */);
21667             node.literal = literal;
21668             node.transformFlags = 1 /* ContainsTypeScript */;
21669             return node;
21670         }
21671         // @api
21672         function updateLiteralTypeNode(node, literal) {
21673             return node.literal !== literal
21674                 ? update(createLiteralTypeNode(literal), node)
21675                 : node;
21676         }
21677         //
21678         // Binding Patterns
21679         //
21680         // @api
21681         function createObjectBindingPattern(elements) {
21682             var node = createBaseNode(196 /* ObjectBindingPattern */);
21683             node.elements = createNodeArray(elements);
21684             node.transformFlags |=
21685                 propagateChildrenFlags(node.elements) |
21686                     256 /* ContainsES2015 */ |
21687                     131072 /* ContainsBindingPattern */;
21688             if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
21689                 node.transformFlags |=
21690                     32 /* ContainsES2018 */ |
21691                         16384 /* ContainsObjectRestOrSpread */;
21692             }
21693             return node;
21694         }
21695         // @api
21696         function updateObjectBindingPattern(node, elements) {
21697             return node.elements !== elements
21698                 ? update(createObjectBindingPattern(elements), node)
21699                 : node;
21700         }
21701         // @api
21702         function createArrayBindingPattern(elements) {
21703             var node = createBaseNode(197 /* ArrayBindingPattern */);
21704             node.elements = createNodeArray(elements);
21705             node.transformFlags |=
21706                 propagateChildrenFlags(node.elements) |
21707                     256 /* ContainsES2015 */ |
21708                     131072 /* ContainsBindingPattern */;
21709             return node;
21710         }
21711         // @api
21712         function updateArrayBindingPattern(node, elements) {
21713             return node.elements !== elements
21714                 ? update(createArrayBindingPattern(elements), node)
21715                 : node;
21716         }
21717         // @api
21718         function createBindingElement(dotDotDotToken, propertyName, name, initializer) {
21719             var node = createBaseBindingLikeDeclaration(198 /* BindingElement */, 
21720             /*decorators*/ undefined, 
21721             /*modifiers*/ undefined, name, initializer);
21722             node.propertyName = asName(propertyName);
21723             node.dotDotDotToken = dotDotDotToken;
21724             node.transformFlags |=
21725                 propagateChildFlags(node.dotDotDotToken) |
21726                     256 /* ContainsES2015 */;
21727             if (node.propertyName) {
21728                 node.transformFlags |= ts.isIdentifier(node.propertyName) ?
21729                     propagateIdentifierNameFlags(node.propertyName) :
21730                     propagateChildFlags(node.propertyName);
21731             }
21732             if (dotDotDotToken)
21733                 node.transformFlags |= 8192 /* ContainsRestOrSpread */;
21734             return node;
21735         }
21736         // @api
21737         function updateBindingElement(node, dotDotDotToken, propertyName, name, initializer) {
21738             return node.propertyName !== propertyName
21739                 || node.dotDotDotToken !== dotDotDotToken
21740                 || node.name !== name
21741                 || node.initializer !== initializer
21742                 ? update(createBindingElement(dotDotDotToken, propertyName, name, initializer), node)
21743                 : node;
21744         }
21745         //
21746         // Expression
21747         //
21748         function createBaseExpression(kind) {
21749             var node = createBaseNode(kind);
21750             // the following properties are commonly set by the checker/binder
21751             return node;
21752         }
21753         // @api
21754         function createArrayLiteralExpression(elements, multiLine) {
21755             var node = createBaseExpression(199 /* ArrayLiteralExpression */);
21756             node.elements = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(elements));
21757             node.multiLine = multiLine;
21758             node.transformFlags |= propagateChildrenFlags(node.elements);
21759             return node;
21760         }
21761         // @api
21762         function updateArrayLiteralExpression(node, elements) {
21763             return node.elements !== elements
21764                 ? update(createArrayLiteralExpression(elements, node.multiLine), node)
21765                 : node;
21766         }
21767         // @api
21768         function createObjectLiteralExpression(properties, multiLine) {
21769             var node = createBaseExpression(200 /* ObjectLiteralExpression */);
21770             node.properties = createNodeArray(properties);
21771             node.multiLine = multiLine;
21772             node.transformFlags |= propagateChildrenFlags(node.properties);
21773             return node;
21774         }
21775         // @api
21776         function updateObjectLiteralExpression(node, properties) {
21777             return node.properties !== properties
21778                 ? update(createObjectLiteralExpression(properties, node.multiLine), node)
21779                 : node;
21780         }
21781         // @api
21782         function createPropertyAccessExpression(expression, name) {
21783             var node = createBaseExpression(201 /* PropertyAccessExpression */);
21784             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21785             node.name = asName(name);
21786             node.transformFlags =
21787                 propagateChildFlags(node.expression) |
21788                     (ts.isIdentifier(node.name) ?
21789                         propagateIdentifierNameFlags(node.name) :
21790                         propagateChildFlags(node.name));
21791             if (ts.isSuperKeyword(expression)) {
21792                 // super method calls require a lexical 'this'
21793                 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
21794                 node.transformFlags |=
21795                     64 /* ContainsES2017 */ |
21796                         32 /* ContainsES2018 */;
21797             }
21798             return node;
21799         }
21800         // @api
21801         function updatePropertyAccessExpression(node, expression, name) {
21802             if (ts.isPropertyAccessChain(node)) {
21803                 return updatePropertyAccessChain(node, expression, node.questionDotToken, ts.cast(name, ts.isIdentifier));
21804             }
21805             return node.expression !== expression
21806                 || node.name !== name
21807                 ? update(createPropertyAccessExpression(expression, name), node)
21808                 : node;
21809         }
21810         // @api
21811         function createPropertyAccessChain(expression, questionDotToken, name) {
21812             var node = createBaseExpression(201 /* PropertyAccessExpression */);
21813             node.flags |= 32 /* OptionalChain */;
21814             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21815             node.questionDotToken = questionDotToken;
21816             node.name = asName(name);
21817             node.transformFlags |=
21818                 8 /* ContainsES2020 */ |
21819                     propagateChildFlags(node.expression) |
21820                     propagateChildFlags(node.questionDotToken) |
21821                     (ts.isIdentifier(node.name) ?
21822                         propagateIdentifierNameFlags(node.name) :
21823                         propagateChildFlags(node.name));
21824             return node;
21825         }
21826         // @api
21827         function updatePropertyAccessChain(node, expression, questionDotToken, name) {
21828             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a PropertyAccessExpression using updatePropertyAccessChain. Use updatePropertyAccess instead.");
21829             // Because we are updating an existing PropertyAccessChain we want to inherit its emitFlags
21830             // instead of using the default from createPropertyAccess
21831             return node.expression !== expression
21832                 || node.questionDotToken !== questionDotToken
21833                 || node.name !== name
21834                 ? update(createPropertyAccessChain(expression, questionDotToken, name), node)
21835                 : node;
21836         }
21837         // @api
21838         function createElementAccessExpression(expression, index) {
21839             var node = createBaseExpression(202 /* ElementAccessExpression */);
21840             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21841             node.argumentExpression = asExpression(index);
21842             node.transformFlags |=
21843                 propagateChildFlags(node.expression) |
21844                     propagateChildFlags(node.argumentExpression);
21845             if (ts.isSuperKeyword(expression)) {
21846                 // super method calls require a lexical 'this'
21847                 // super method calls require 'super' hoisting in ES2017 and ES2018 async functions and async generators
21848                 node.transformFlags |=
21849                     64 /* ContainsES2017 */ |
21850                         32 /* ContainsES2018 */;
21851             }
21852             return node;
21853         }
21854         // @api
21855         function updateElementAccessExpression(node, expression, argumentExpression) {
21856             if (ts.isElementAccessChain(node)) {
21857                 return updateElementAccessChain(node, expression, node.questionDotToken, argumentExpression);
21858             }
21859             return node.expression !== expression
21860                 || node.argumentExpression !== argumentExpression
21861                 ? update(createElementAccessExpression(expression, argumentExpression), node)
21862                 : node;
21863         }
21864         // @api
21865         function createElementAccessChain(expression, questionDotToken, index) {
21866             var node = createBaseExpression(202 /* ElementAccessExpression */);
21867             node.flags |= 32 /* OptionalChain */;
21868             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21869             node.questionDotToken = questionDotToken;
21870             node.argumentExpression = asExpression(index);
21871             node.transformFlags |=
21872                 propagateChildFlags(node.expression) |
21873                     propagateChildFlags(node.questionDotToken) |
21874                     propagateChildFlags(node.argumentExpression) |
21875                     8 /* ContainsES2020 */;
21876             return node;
21877         }
21878         // @api
21879         function updateElementAccessChain(node, expression, questionDotToken, argumentExpression) {
21880             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a ElementAccessExpression using updateElementAccessChain. Use updateElementAccess instead.");
21881             // Because we are updating an existing ElementAccessChain we want to inherit its emitFlags
21882             // instead of using the default from createElementAccess
21883             return node.expression !== expression
21884                 || node.questionDotToken !== questionDotToken
21885                 || node.argumentExpression !== argumentExpression
21886                 ? update(createElementAccessChain(expression, questionDotToken, argumentExpression), node)
21887                 : node;
21888         }
21889         // @api
21890         function createCallExpression(expression, typeArguments, argumentsArray) {
21891             var node = createBaseExpression(203 /* CallExpression */);
21892             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21893             node.typeArguments = asNodeArray(typeArguments);
21894             node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
21895             node.transformFlags |=
21896                 propagateChildFlags(node.expression) |
21897                     propagateChildrenFlags(node.typeArguments) |
21898                     propagateChildrenFlags(node.arguments);
21899             if (node.typeArguments) {
21900                 node.transformFlags |= 1 /* ContainsTypeScript */;
21901             }
21902             if (ts.isImportKeyword(node.expression)) {
21903                 node.transformFlags |= 2097152 /* ContainsDynamicImport */;
21904             }
21905             else if (ts.isSuperProperty(node.expression)) {
21906                 node.transformFlags |= 4096 /* ContainsLexicalThis */;
21907             }
21908             return node;
21909         }
21910         // @api
21911         function updateCallExpression(node, expression, typeArguments, argumentsArray) {
21912             if (ts.isCallChain(node)) {
21913                 return updateCallChain(node, expression, node.questionDotToken, typeArguments, argumentsArray);
21914             }
21915             return node.expression !== expression
21916                 || node.typeArguments !== typeArguments
21917                 || node.arguments !== argumentsArray
21918                 ? update(createCallExpression(expression, typeArguments, argumentsArray), node)
21919                 : node;
21920         }
21921         // @api
21922         function createCallChain(expression, questionDotToken, typeArguments, argumentsArray) {
21923             var node = createBaseExpression(203 /* CallExpression */);
21924             node.flags |= 32 /* OptionalChain */;
21925             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
21926             node.questionDotToken = questionDotToken;
21927             node.typeArguments = asNodeArray(typeArguments);
21928             node.arguments = parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(createNodeArray(argumentsArray));
21929             node.transformFlags |=
21930                 propagateChildFlags(node.expression) |
21931                     propagateChildFlags(node.questionDotToken) |
21932                     propagateChildrenFlags(node.typeArguments) |
21933                     propagateChildrenFlags(node.arguments) |
21934                     8 /* ContainsES2020 */;
21935             if (node.typeArguments) {
21936                 node.transformFlags |= 1 /* ContainsTypeScript */;
21937             }
21938             if (ts.isSuperProperty(node.expression)) {
21939                 node.transformFlags |= 4096 /* ContainsLexicalThis */;
21940             }
21941             return node;
21942         }
21943         // @api
21944         function updateCallChain(node, expression, questionDotToken, typeArguments, argumentsArray) {
21945             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a CallExpression using updateCallChain. Use updateCall instead.");
21946             return node.expression !== expression
21947                 || node.questionDotToken !== questionDotToken
21948                 || node.typeArguments !== typeArguments
21949                 || node.arguments !== argumentsArray
21950                 ? update(createCallChain(expression, questionDotToken, typeArguments, argumentsArray), node)
21951                 : node;
21952         }
21953         // @api
21954         function createNewExpression(expression, typeArguments, argumentsArray) {
21955             var node = createBaseExpression(204 /* NewExpression */);
21956             node.expression = parenthesizerRules().parenthesizeExpressionOfNew(expression);
21957             node.typeArguments = asNodeArray(typeArguments);
21958             node.arguments = argumentsArray ? parenthesizerRules().parenthesizeExpressionsOfCommaDelimitedList(argumentsArray) : undefined;
21959             node.transformFlags |=
21960                 propagateChildFlags(node.expression) |
21961                     propagateChildrenFlags(node.typeArguments) |
21962                     propagateChildrenFlags(node.arguments) |
21963                     8 /* ContainsES2020 */;
21964             if (node.typeArguments) {
21965                 node.transformFlags |= 1 /* ContainsTypeScript */;
21966             }
21967             return node;
21968         }
21969         // @api
21970         function updateNewExpression(node, expression, typeArguments, argumentsArray) {
21971             return node.expression !== expression
21972                 || node.typeArguments !== typeArguments
21973                 || node.arguments !== argumentsArray
21974                 ? update(createNewExpression(expression, typeArguments, argumentsArray), node)
21975                 : node;
21976         }
21977         // @api
21978         function createTaggedTemplateExpression(tag, typeArguments, template) {
21979             var node = createBaseExpression(205 /* TaggedTemplateExpression */);
21980             node.tag = parenthesizerRules().parenthesizeLeftSideOfAccess(tag);
21981             node.typeArguments = asNodeArray(typeArguments);
21982             node.template = template;
21983             node.transformFlags |=
21984                 propagateChildFlags(node.tag) |
21985                     propagateChildrenFlags(node.typeArguments) |
21986                     propagateChildFlags(node.template) |
21987                     256 /* ContainsES2015 */;
21988             if (node.typeArguments) {
21989                 node.transformFlags |= 1 /* ContainsTypeScript */;
21990             }
21991             if (ts.hasInvalidEscape(node.template)) {
21992                 node.transformFlags |= 32 /* ContainsES2018 */;
21993             }
21994             return node;
21995         }
21996         // @api
21997         function updateTaggedTemplateExpression(node, tag, typeArguments, template) {
21998             return node.tag !== tag
21999                 || node.typeArguments !== typeArguments
22000                 || node.template !== template
22001                 ? update(createTaggedTemplateExpression(tag, typeArguments, template), node)
22002                 : node;
22003         }
22004         // @api
22005         function createTypeAssertion(type, expression) {
22006             var node = createBaseExpression(206 /* TypeAssertionExpression */);
22007             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22008             node.type = type;
22009             node.transformFlags |=
22010                 propagateChildFlags(node.expression) |
22011                     propagateChildFlags(node.type) |
22012                     1 /* ContainsTypeScript */;
22013             return node;
22014         }
22015         // @api
22016         function updateTypeAssertion(node, type, expression) {
22017             return node.type !== type
22018                 || node.expression !== expression
22019                 ? update(createTypeAssertion(type, expression), node)
22020                 : node;
22021         }
22022         // @api
22023         function createParenthesizedExpression(expression) {
22024             var node = createBaseExpression(207 /* ParenthesizedExpression */);
22025             node.expression = expression;
22026             node.transformFlags = propagateChildFlags(node.expression);
22027             return node;
22028         }
22029         // @api
22030         function updateParenthesizedExpression(node, expression) {
22031             return node.expression !== expression
22032                 ? update(createParenthesizedExpression(expression), node)
22033                 : node;
22034         }
22035         // @api
22036         function createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22037             var node = createBaseFunctionLikeDeclaration(208 /* FunctionExpression */, 
22038             /*decorators*/ undefined, modifiers, name, typeParameters, parameters, type, body);
22039             node.asteriskToken = asteriskToken;
22040             node.transformFlags |= propagateChildFlags(node.asteriskToken);
22041             if (node.typeParameters) {
22042                 node.transformFlags |= 1 /* ContainsTypeScript */;
22043             }
22044             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22045                 if (node.asteriskToken) {
22046                     node.transformFlags |= 32 /* ContainsES2018 */;
22047                 }
22048                 else {
22049                     node.transformFlags |= 64 /* ContainsES2017 */;
22050                 }
22051             }
22052             else if (node.asteriskToken) {
22053                 node.transformFlags |= 512 /* ContainsGenerator */;
22054             }
22055             return node;
22056         }
22057         // @api
22058         function updateFunctionExpression(node, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22059             return node.name !== name
22060                 || node.modifiers !== modifiers
22061                 || node.asteriskToken !== asteriskToken
22062                 || node.typeParameters !== typeParameters
22063                 || node.parameters !== parameters
22064                 || node.type !== type
22065                 || node.body !== body
22066                 ? updateBaseFunctionLikeDeclaration(createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
22067                 : node;
22068         }
22069         // @api
22070         function createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
22071             var node = createBaseFunctionLikeDeclaration(209 /* ArrowFunction */, 
22072             /*decorators*/ undefined, modifiers, 
22073             /*name*/ undefined, typeParameters, parameters, type, parenthesizerRules().parenthesizeConciseBodyOfArrowFunction(body));
22074             node.equalsGreaterThanToken = equalsGreaterThanToken !== null && equalsGreaterThanToken !== void 0 ? equalsGreaterThanToken : createToken(38 /* EqualsGreaterThanToken */);
22075             node.transformFlags |=
22076                 propagateChildFlags(node.equalsGreaterThanToken) |
22077                     256 /* ContainsES2015 */;
22078             if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22079                 node.transformFlags |= 64 /* ContainsES2017 */;
22080             }
22081             return node;
22082         }
22083         // @api
22084         function updateArrowFunction(node, modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body) {
22085             return node.modifiers !== modifiers
22086                 || node.typeParameters !== typeParameters
22087                 || node.parameters !== parameters
22088                 || node.type !== type
22089                 || node.equalsGreaterThanToken !== equalsGreaterThanToken
22090                 || node.body !== body
22091                 ? updateBaseFunctionLikeDeclaration(createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body), node)
22092                 : node;
22093         }
22094         // @api
22095         function createDeleteExpression(expression) {
22096             var node = createBaseExpression(210 /* DeleteExpression */);
22097             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22098             node.transformFlags |= propagateChildFlags(node.expression);
22099             return node;
22100         }
22101         // @api
22102         function updateDeleteExpression(node, expression) {
22103             return node.expression !== expression
22104                 ? update(createDeleteExpression(expression), node)
22105                 : node;
22106         }
22107         // @api
22108         function createTypeOfExpression(expression) {
22109             var node = createBaseExpression(211 /* TypeOfExpression */);
22110             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22111             node.transformFlags |= propagateChildFlags(node.expression);
22112             return node;
22113         }
22114         // @api
22115         function updateTypeOfExpression(node, expression) {
22116             return node.expression !== expression
22117                 ? update(createTypeOfExpression(expression), node)
22118                 : node;
22119         }
22120         // @api
22121         function createVoidExpression(expression) {
22122             var node = createBaseExpression(212 /* VoidExpression */);
22123             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22124             node.transformFlags |= propagateChildFlags(node.expression);
22125             return node;
22126         }
22127         // @api
22128         function updateVoidExpression(node, expression) {
22129             return node.expression !== expression
22130                 ? update(createVoidExpression(expression), node)
22131                 : node;
22132         }
22133         // @api
22134         function createAwaitExpression(expression) {
22135             var node = createBaseExpression(213 /* AwaitExpression */);
22136             node.expression = parenthesizerRules().parenthesizeOperandOfPrefixUnary(expression);
22137             node.transformFlags |=
22138                 propagateChildFlags(node.expression) |
22139                     64 /* ContainsES2017 */ |
22140                     32 /* ContainsES2018 */ |
22141                     524288 /* ContainsAwait */;
22142             return node;
22143         }
22144         // @api
22145         function updateAwaitExpression(node, expression) {
22146             return node.expression !== expression
22147                 ? update(createAwaitExpression(expression), node)
22148                 : node;
22149         }
22150         // @api
22151         function createPrefixUnaryExpression(operator, operand) {
22152             var node = createBaseExpression(214 /* PrefixUnaryExpression */);
22153             node.operator = operator;
22154             node.operand = parenthesizerRules().parenthesizeOperandOfPrefixUnary(operand);
22155             node.transformFlags |= propagateChildFlags(node.operand);
22156             return node;
22157         }
22158         // @api
22159         function updatePrefixUnaryExpression(node, operand) {
22160             return node.operand !== operand
22161                 ? update(createPrefixUnaryExpression(node.operator, operand), node)
22162                 : node;
22163         }
22164         // @api
22165         function createPostfixUnaryExpression(operand, operator) {
22166             var node = createBaseExpression(215 /* PostfixUnaryExpression */);
22167             node.operator = operator;
22168             node.operand = parenthesizerRules().parenthesizeOperandOfPostfixUnary(operand);
22169             node.transformFlags = propagateChildFlags(node.operand);
22170             return node;
22171         }
22172         // @api
22173         function updatePostfixUnaryExpression(node, operand) {
22174             return node.operand !== operand
22175                 ? update(createPostfixUnaryExpression(operand, node.operator), node)
22176                 : node;
22177         }
22178         // @api
22179         function createBinaryExpression(left, operator, right) {
22180             var node = createBaseExpression(216 /* BinaryExpression */);
22181             var operatorToken = asToken(operator);
22182             var operatorKind = operatorToken.kind;
22183             node.left = parenthesizerRules().parenthesizeLeftSideOfBinary(operatorKind, left);
22184             node.operatorToken = operatorToken;
22185             node.right = parenthesizerRules().parenthesizeRightSideOfBinary(operatorKind, node.left, right);
22186             node.transformFlags |=
22187                 propagateChildFlags(node.left) |
22188                     propagateChildFlags(node.operatorToken) |
22189                     propagateChildFlags(node.right);
22190             if (operatorKind === 60 /* QuestionQuestionToken */) {
22191                 node.transformFlags |= 8 /* ContainsES2020 */;
22192             }
22193             else if (operatorKind === 62 /* EqualsToken */) {
22194                 if (ts.isObjectLiteralExpression(node.left)) {
22195                     node.transformFlags |=
22196                         256 /* ContainsES2015 */ |
22197                             32 /* ContainsES2018 */ |
22198                             1024 /* ContainsDestructuringAssignment */ |
22199                             propagateAssignmentPatternFlags(node.left);
22200                 }
22201                 else if (ts.isArrayLiteralExpression(node.left)) {
22202                     node.transformFlags |=
22203                         256 /* ContainsES2015 */ |
22204                             1024 /* ContainsDestructuringAssignment */ |
22205                             propagateAssignmentPatternFlags(node.left);
22206                 }
22207             }
22208             else if (operatorKind === 42 /* AsteriskAsteriskToken */ || operatorKind === 66 /* AsteriskAsteriskEqualsToken */) {
22209                 node.transformFlags |= 128 /* ContainsES2016 */;
22210             }
22211             else if (ts.isLogicalOrCoalescingAssignmentOperator(operatorKind)) {
22212                 node.transformFlags |= 4 /* ContainsESNext */;
22213             }
22214             return node;
22215         }
22216         function propagateAssignmentPatternFlags(node) {
22217             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */)
22218                 return 16384 /* ContainsObjectRestOrSpread */;
22219             if (node.transformFlags & 32 /* ContainsES2018 */) {
22220                 // check for nested spread assignments, otherwise '{ x: { a, ...b } = foo } = c'
22221                 // will not be correctly interpreted by the ES2018 transformer
22222                 for (var _i = 0, _a = ts.getElementsOfBindingOrAssignmentPattern(node); _i < _a.length; _i++) {
22223                     var element = _a[_i];
22224                     var target = ts.getTargetOfBindingOrAssignmentElement(element);
22225                     if (target && ts.isAssignmentPattern(target)) {
22226                         if (target.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
22227                             return 16384 /* ContainsObjectRestOrSpread */;
22228                         }
22229                         if (target.transformFlags & 32 /* ContainsES2018 */) {
22230                             var flags_1 = propagateAssignmentPatternFlags(target);
22231                             if (flags_1)
22232                                 return flags_1;
22233                         }
22234                     }
22235                 }
22236             }
22237             return 0 /* None */;
22238         }
22239         // @api
22240         function updateBinaryExpression(node, left, operator, right) {
22241             return node.left !== left
22242                 || node.operatorToken !== operator
22243                 || node.right !== right
22244                 ? update(createBinaryExpression(left, operator, right), node)
22245                 : node;
22246         }
22247         // @api
22248         function createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse) {
22249             var node = createBaseExpression(217 /* ConditionalExpression */);
22250             node.condition = parenthesizerRules().parenthesizeConditionOfConditionalExpression(condition);
22251             node.questionToken = questionToken !== null && questionToken !== void 0 ? questionToken : createToken(57 /* QuestionToken */);
22252             node.whenTrue = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenTrue);
22253             node.colonToken = colonToken !== null && colonToken !== void 0 ? colonToken : createToken(58 /* ColonToken */);
22254             node.whenFalse = parenthesizerRules().parenthesizeBranchOfConditionalExpression(whenFalse);
22255             node.transformFlags |=
22256                 propagateChildFlags(node.condition) |
22257                     propagateChildFlags(node.questionToken) |
22258                     propagateChildFlags(node.whenTrue) |
22259                     propagateChildFlags(node.colonToken) |
22260                     propagateChildFlags(node.whenFalse);
22261             return node;
22262         }
22263         // @api
22264         function updateConditionalExpression(node, condition, questionToken, whenTrue, colonToken, whenFalse) {
22265             return node.condition !== condition
22266                 || node.questionToken !== questionToken
22267                 || node.whenTrue !== whenTrue
22268                 || node.colonToken !== colonToken
22269                 || node.whenFalse !== whenFalse
22270                 ? update(createConditionalExpression(condition, questionToken, whenTrue, colonToken, whenFalse), node)
22271                 : node;
22272         }
22273         // @api
22274         function createTemplateExpression(head, templateSpans) {
22275             var node = createBaseExpression(218 /* TemplateExpression */);
22276             node.head = head;
22277             node.templateSpans = createNodeArray(templateSpans);
22278             node.transformFlags |=
22279                 propagateChildFlags(node.head) |
22280                     propagateChildrenFlags(node.templateSpans) |
22281                     256 /* ContainsES2015 */;
22282             return node;
22283         }
22284         // @api
22285         function updateTemplateExpression(node, head, templateSpans) {
22286             return node.head !== head
22287                 || node.templateSpans !== templateSpans
22288                 ? update(createTemplateExpression(head, templateSpans), node)
22289                 : node;
22290         }
22291         function createTemplateLiteralLikeNodeChecked(kind, text, rawText, templateFlags) {
22292             if (templateFlags === void 0) { templateFlags = 0 /* None */; }
22293             ts.Debug.assert(!(templateFlags & ~2048 /* TemplateLiteralLikeFlags */), "Unsupported template flags.");
22294             // NOTE: without the assignment to `undefined`, we don't narrow the initial type of `cooked`.
22295             // eslint-disable-next-line no-undef-init
22296             var cooked = undefined;
22297             if (rawText !== undefined && rawText !== text) {
22298                 cooked = getCookedText(kind, rawText);
22299                 if (typeof cooked === "object") {
22300                     return ts.Debug.fail("Invalid raw text");
22301                 }
22302             }
22303             if (text === undefined) {
22304                 if (cooked === undefined) {
22305                     return ts.Debug.fail("Arguments 'text' and 'rawText' may not both be undefined.");
22306                 }
22307                 text = cooked;
22308             }
22309             else if (cooked !== undefined) {
22310                 ts.Debug.assert(text === cooked, "Expected argument 'text' to be the normalized (i.e. 'cooked') version of argument 'rawText'.");
22311             }
22312             return createTemplateLiteralLikeNode(kind, text, rawText, templateFlags);
22313         }
22314         // @api
22315         function createTemplateLiteralLikeNode(kind, text, rawText, templateFlags) {
22316             var node = createBaseToken(kind);
22317             node.text = text;
22318             node.rawText = rawText;
22319             node.templateFlags = templateFlags & 2048 /* TemplateLiteralLikeFlags */;
22320             node.transformFlags |= 256 /* ContainsES2015 */;
22321             if (node.templateFlags) {
22322                 node.transformFlags |= 32 /* ContainsES2018 */;
22323             }
22324             return node;
22325         }
22326         // @api
22327         function createTemplateHead(text, rawText, templateFlags) {
22328             return createTemplateLiteralLikeNodeChecked(15 /* TemplateHead */, text, rawText, templateFlags);
22329         }
22330         // @api
22331         function createTemplateMiddle(text, rawText, templateFlags) {
22332             return createTemplateLiteralLikeNodeChecked(16 /* TemplateMiddle */, text, rawText, templateFlags);
22333         }
22334         // @api
22335         function createTemplateTail(text, rawText, templateFlags) {
22336             return createTemplateLiteralLikeNodeChecked(17 /* TemplateTail */, text, rawText, templateFlags);
22337         }
22338         // @api
22339         function createNoSubstitutionTemplateLiteral(text, rawText, templateFlags) {
22340             return createTemplateLiteralLikeNodeChecked(14 /* NoSubstitutionTemplateLiteral */, text, rawText, templateFlags);
22341         }
22342         // @api
22343         function createYieldExpression(asteriskToken, expression) {
22344             ts.Debug.assert(!asteriskToken || !!expression, "A `YieldExpression` with an asteriskToken must have an expression.");
22345             var node = createBaseExpression(219 /* YieldExpression */);
22346             node.expression = expression && parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22347             node.asteriskToken = asteriskToken;
22348             node.transformFlags |=
22349                 propagateChildFlags(node.expression) |
22350                     propagateChildFlags(node.asteriskToken) |
22351                     256 /* ContainsES2015 */ |
22352                     32 /* ContainsES2018 */ |
22353                     262144 /* ContainsYield */;
22354             return node;
22355         }
22356         // @api
22357         function updateYieldExpression(node, asteriskToken, expression) {
22358             return node.expression !== expression
22359                 || node.asteriskToken !== asteriskToken
22360                 ? update(createYieldExpression(asteriskToken, expression), node)
22361                 : node;
22362         }
22363         // @api
22364         function createSpreadElement(expression) {
22365             var node = createBaseExpression(220 /* SpreadElement */);
22366             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22367             node.transformFlags |=
22368                 propagateChildFlags(node.expression) |
22369                     256 /* ContainsES2015 */ |
22370                     8192 /* ContainsRestOrSpread */;
22371             return node;
22372         }
22373         // @api
22374         function updateSpreadElement(node, expression) {
22375             return node.expression !== expression
22376                 ? update(createSpreadElement(expression), node)
22377                 : node;
22378         }
22379         // @api
22380         function createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members) {
22381             var node = createBaseClassLikeDeclaration(221 /* ClassExpression */, decorators, modifiers, name, typeParameters, heritageClauses, members);
22382             node.transformFlags |= 256 /* ContainsES2015 */;
22383             return node;
22384         }
22385         // @api
22386         function updateClassExpression(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
22387             return node.decorators !== decorators
22388                 || node.modifiers !== modifiers
22389                 || node.name !== name
22390                 || node.typeParameters !== typeParameters
22391                 || node.heritageClauses !== heritageClauses
22392                 || node.members !== members
22393                 ? update(createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
22394                 : node;
22395         }
22396         // @api
22397         function createOmittedExpression() {
22398             return createBaseExpression(222 /* OmittedExpression */);
22399         }
22400         // @api
22401         function createExpressionWithTypeArguments(expression, typeArguments) {
22402             var node = createBaseNode(223 /* ExpressionWithTypeArguments */);
22403             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22404             node.typeArguments = typeArguments && parenthesizerRules().parenthesizeTypeArguments(typeArguments);
22405             node.transformFlags |=
22406                 propagateChildFlags(node.expression) |
22407                     propagateChildrenFlags(node.typeArguments) |
22408                     256 /* ContainsES2015 */;
22409             return node;
22410         }
22411         // @api
22412         function updateExpressionWithTypeArguments(node, expression, typeArguments) {
22413             return node.expression !== expression
22414                 || node.typeArguments !== typeArguments
22415                 ? update(createExpressionWithTypeArguments(expression, typeArguments), node)
22416                 : node;
22417         }
22418         // @api
22419         function createAsExpression(expression, type) {
22420             var node = createBaseExpression(224 /* AsExpression */);
22421             node.expression = expression;
22422             node.type = type;
22423             node.transformFlags |=
22424                 propagateChildFlags(node.expression) |
22425                     propagateChildFlags(node.type) |
22426                     1 /* ContainsTypeScript */;
22427             return node;
22428         }
22429         // @api
22430         function updateAsExpression(node, expression, type) {
22431             return node.expression !== expression
22432                 || node.type !== type
22433                 ? update(createAsExpression(expression, type), node)
22434                 : node;
22435         }
22436         // @api
22437         function createNonNullExpression(expression) {
22438             var node = createBaseExpression(225 /* NonNullExpression */);
22439             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22440             node.transformFlags |=
22441                 propagateChildFlags(node.expression) |
22442                     1 /* ContainsTypeScript */;
22443             return node;
22444         }
22445         // @api
22446         function updateNonNullExpression(node, expression) {
22447             if (ts.isNonNullChain(node)) {
22448                 return updateNonNullChain(node, expression);
22449             }
22450             return node.expression !== expression
22451                 ? update(createNonNullExpression(expression), node)
22452                 : node;
22453         }
22454         // @api
22455         function createNonNullChain(expression) {
22456             var node = createBaseExpression(225 /* NonNullExpression */);
22457             node.flags |= 32 /* OptionalChain */;
22458             node.expression = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
22459             node.transformFlags |=
22460                 propagateChildFlags(node.expression) |
22461                     1 /* ContainsTypeScript */;
22462             return node;
22463         }
22464         // @api
22465         function updateNonNullChain(node, expression) {
22466             ts.Debug.assert(!!(node.flags & 32 /* OptionalChain */), "Cannot update a NonNullExpression using updateNonNullChain. Use updateNonNullExpression instead.");
22467             return node.expression !== expression
22468                 ? update(createNonNullChain(expression), node)
22469                 : node;
22470         }
22471         // @api
22472         function createMetaProperty(keywordToken, name) {
22473             var node = createBaseExpression(226 /* MetaProperty */);
22474             node.keywordToken = keywordToken;
22475             node.name = name;
22476             node.transformFlags |= propagateChildFlags(node.name);
22477             switch (keywordToken) {
22478                 case 102 /* NewKeyword */:
22479                     node.transformFlags |= 256 /* ContainsES2015 */;
22480                     break;
22481                 case 99 /* ImportKeyword */:
22482                     node.transformFlags |= 4 /* ContainsESNext */;
22483                     break;
22484                 default:
22485                     return ts.Debug.assertNever(keywordToken);
22486             }
22487             return node;
22488         }
22489         // @api
22490         function updateMetaProperty(node, name) {
22491             return node.name !== name
22492                 ? update(createMetaProperty(node.keywordToken, name), node)
22493                 : node;
22494         }
22495         //
22496         // Misc
22497         //
22498         // @api
22499         function createTemplateSpan(expression, literal) {
22500             var node = createBaseNode(228 /* TemplateSpan */);
22501             node.expression = expression;
22502             node.literal = literal;
22503             node.transformFlags |=
22504                 propagateChildFlags(node.expression) |
22505                     propagateChildFlags(node.literal) |
22506                     256 /* ContainsES2015 */;
22507             return node;
22508         }
22509         // @api
22510         function updateTemplateSpan(node, expression, literal) {
22511             return node.expression !== expression
22512                 || node.literal !== literal
22513                 ? update(createTemplateSpan(expression, literal), node)
22514                 : node;
22515         }
22516         // @api
22517         function createSemicolonClassElement() {
22518             var node = createBaseNode(229 /* SemicolonClassElement */);
22519             node.transformFlags |= 256 /* ContainsES2015 */;
22520             return node;
22521         }
22522         //
22523         // Element
22524         //
22525         // @api
22526         function createBlock(statements, multiLine) {
22527             var node = createBaseNode(230 /* Block */);
22528             node.statements = createNodeArray(statements);
22529             node.multiLine = multiLine;
22530             node.transformFlags |= propagateChildrenFlags(node.statements);
22531             return node;
22532         }
22533         // @api
22534         function updateBlock(node, statements) {
22535             return node.statements !== statements
22536                 ? update(createBlock(statements, node.multiLine), node)
22537                 : node;
22538         }
22539         // @api
22540         function createVariableStatement(modifiers, declarationList) {
22541             var node = createBaseDeclaration(232 /* VariableStatement */, /*decorators*/ undefined, modifiers);
22542             node.declarationList = ts.isArray(declarationList) ? createVariableDeclarationList(declarationList) : declarationList;
22543             node.transformFlags |=
22544                 propagateChildFlags(node.declarationList);
22545             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22546                 node.transformFlags = 1 /* ContainsTypeScript */;
22547             }
22548             return node;
22549         }
22550         // @api
22551         function updateVariableStatement(node, modifiers, declarationList) {
22552             return node.modifiers !== modifiers
22553                 || node.declarationList !== declarationList
22554                 ? update(createVariableStatement(modifiers, declarationList), node)
22555                 : node;
22556         }
22557         // @api
22558         function createEmptyStatement() {
22559             return createBaseNode(231 /* EmptyStatement */);
22560         }
22561         // @api
22562         function createExpressionStatement(expression) {
22563             var node = createBaseNode(233 /* ExpressionStatement */);
22564             node.expression = parenthesizerRules().parenthesizeExpressionOfExpressionStatement(expression);
22565             node.transformFlags |= propagateChildFlags(node.expression);
22566             return node;
22567         }
22568         // @api
22569         function updateExpressionStatement(node, expression) {
22570             return node.expression !== expression
22571                 ? update(createExpressionStatement(expression), node)
22572                 : node;
22573         }
22574         // @api
22575         function createIfStatement(expression, thenStatement, elseStatement) {
22576             var node = createBaseNode(234 /* IfStatement */);
22577             node.expression = expression;
22578             node.thenStatement = asEmbeddedStatement(thenStatement);
22579             node.elseStatement = asEmbeddedStatement(elseStatement);
22580             node.transformFlags |=
22581                 propagateChildFlags(node.expression) |
22582                     propagateChildFlags(node.thenStatement) |
22583                     propagateChildFlags(node.elseStatement);
22584             return node;
22585         }
22586         // @api
22587         function updateIfStatement(node, expression, thenStatement, elseStatement) {
22588             return node.expression !== expression
22589                 || node.thenStatement !== thenStatement
22590                 || node.elseStatement !== elseStatement
22591                 ? update(createIfStatement(expression, thenStatement, elseStatement), node)
22592                 : node;
22593         }
22594         // @api
22595         function createDoStatement(statement, expression) {
22596             var node = createBaseNode(235 /* DoStatement */);
22597             node.statement = asEmbeddedStatement(statement);
22598             node.expression = expression;
22599             node.transformFlags |=
22600                 propagateChildFlags(node.statement) |
22601                     propagateChildFlags(node.expression);
22602             return node;
22603         }
22604         // @api
22605         function updateDoStatement(node, statement, expression) {
22606             return node.statement !== statement
22607                 || node.expression !== expression
22608                 ? update(createDoStatement(statement, expression), node)
22609                 : node;
22610         }
22611         // @api
22612         function createWhileStatement(expression, statement) {
22613             var node = createBaseNode(236 /* WhileStatement */);
22614             node.expression = expression;
22615             node.statement = asEmbeddedStatement(statement);
22616             node.transformFlags |=
22617                 propagateChildFlags(node.expression) |
22618                     propagateChildFlags(node.statement);
22619             return node;
22620         }
22621         // @api
22622         function updateWhileStatement(node, expression, statement) {
22623             return node.expression !== expression
22624                 || node.statement !== statement
22625                 ? update(createWhileStatement(expression, statement), node)
22626                 : node;
22627         }
22628         // @api
22629         function createForStatement(initializer, condition, incrementor, statement) {
22630             var node = createBaseNode(237 /* ForStatement */);
22631             node.initializer = initializer;
22632             node.condition = condition;
22633             node.incrementor = incrementor;
22634             node.statement = asEmbeddedStatement(statement);
22635             node.transformFlags |=
22636                 propagateChildFlags(node.initializer) |
22637                     propagateChildFlags(node.condition) |
22638                     propagateChildFlags(node.incrementor) |
22639                     propagateChildFlags(node.statement);
22640             return node;
22641         }
22642         // @api
22643         function updateForStatement(node, initializer, condition, incrementor, statement) {
22644             return node.initializer !== initializer
22645                 || node.condition !== condition
22646                 || node.incrementor !== incrementor
22647                 || node.statement !== statement
22648                 ? update(createForStatement(initializer, condition, incrementor, statement), node)
22649                 : node;
22650         }
22651         // @api
22652         function createForInStatement(initializer, expression, statement) {
22653             var node = createBaseNode(238 /* ForInStatement */);
22654             node.initializer = initializer;
22655             node.expression = expression;
22656             node.statement = asEmbeddedStatement(statement);
22657             node.transformFlags |=
22658                 propagateChildFlags(node.initializer) |
22659                     propagateChildFlags(node.expression) |
22660                     propagateChildFlags(node.statement);
22661             return node;
22662         }
22663         // @api
22664         function updateForInStatement(node, initializer, expression, statement) {
22665             return node.initializer !== initializer
22666                 || node.expression !== expression
22667                 || node.statement !== statement
22668                 ? update(createForInStatement(initializer, expression, statement), node)
22669                 : node;
22670         }
22671         // @api
22672         function createForOfStatement(awaitModifier, initializer, expression, statement) {
22673             var node = createBaseNode(239 /* ForOfStatement */);
22674             node.awaitModifier = awaitModifier;
22675             node.initializer = initializer;
22676             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22677             node.statement = asEmbeddedStatement(statement);
22678             node.transformFlags |=
22679                 propagateChildFlags(node.awaitModifier) |
22680                     propagateChildFlags(node.initializer) |
22681                     propagateChildFlags(node.expression) |
22682                     propagateChildFlags(node.statement) |
22683                     256 /* ContainsES2015 */;
22684             if (awaitModifier)
22685                 node.transformFlags |= 32 /* ContainsES2018 */;
22686             return node;
22687         }
22688         // @api
22689         function updateForOfStatement(node, awaitModifier, initializer, expression, statement) {
22690             return node.awaitModifier !== awaitModifier
22691                 || node.initializer !== initializer
22692                 || node.expression !== expression
22693                 || node.statement !== statement
22694                 ? update(createForOfStatement(awaitModifier, initializer, expression, statement), node)
22695                 : node;
22696         }
22697         // @api
22698         function createContinueStatement(label) {
22699             var node = createBaseNode(240 /* ContinueStatement */);
22700             node.label = asName(label);
22701             node.transformFlags |=
22702                 propagateChildFlags(node.label) |
22703                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
22704             return node;
22705         }
22706         // @api
22707         function updateContinueStatement(node, label) {
22708             return node.label !== label
22709                 ? update(createContinueStatement(label), node)
22710                 : node;
22711         }
22712         // @api
22713         function createBreakStatement(label) {
22714             var node = createBaseNode(241 /* BreakStatement */);
22715             node.label = asName(label);
22716             node.transformFlags |=
22717                 propagateChildFlags(node.label) |
22718                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
22719             return node;
22720         }
22721         // @api
22722         function updateBreakStatement(node, label) {
22723             return node.label !== label
22724                 ? update(createBreakStatement(label), node)
22725                 : node;
22726         }
22727         // @api
22728         function createReturnStatement(expression) {
22729             var node = createBaseNode(242 /* ReturnStatement */);
22730             node.expression = expression;
22731             // return in an ES2018 async generator must be awaited
22732             node.transformFlags |=
22733                 propagateChildFlags(node.expression) |
22734                     32 /* ContainsES2018 */ |
22735                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
22736             return node;
22737         }
22738         // @api
22739         function updateReturnStatement(node, expression) {
22740             return node.expression !== expression
22741                 ? update(createReturnStatement(expression), node)
22742                 : node;
22743         }
22744         // @api
22745         function createWithStatement(expression, statement) {
22746             var node = createBaseNode(243 /* WithStatement */);
22747             node.expression = expression;
22748             node.statement = asEmbeddedStatement(statement);
22749             node.transformFlags |=
22750                 propagateChildFlags(node.expression) |
22751                     propagateChildFlags(node.statement);
22752             return node;
22753         }
22754         // @api
22755         function updateWithStatement(node, expression, statement) {
22756             return node.expression !== expression
22757                 || node.statement !== statement
22758                 ? update(createWithStatement(expression, statement), node)
22759                 : node;
22760         }
22761         // @api
22762         function createSwitchStatement(expression, caseBlock) {
22763             var node = createBaseNode(244 /* SwitchStatement */);
22764             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
22765             node.caseBlock = caseBlock;
22766             node.transformFlags |=
22767                 propagateChildFlags(node.expression) |
22768                     propagateChildFlags(node.caseBlock);
22769             return node;
22770         }
22771         // @api
22772         function updateSwitchStatement(node, expression, caseBlock) {
22773             return node.expression !== expression
22774                 || node.caseBlock !== caseBlock
22775                 ? update(createSwitchStatement(expression, caseBlock), node)
22776                 : node;
22777         }
22778         // @api
22779         function createLabeledStatement(label, statement) {
22780             var node = createBaseNode(245 /* LabeledStatement */);
22781             node.label = asName(label);
22782             node.statement = asEmbeddedStatement(statement);
22783             node.transformFlags |=
22784                 propagateChildFlags(node.label) |
22785                     propagateChildFlags(node.statement);
22786             return node;
22787         }
22788         // @api
22789         function updateLabeledStatement(node, label, statement) {
22790             return node.label !== label
22791                 || node.statement !== statement
22792                 ? update(createLabeledStatement(label, statement), node)
22793                 : node;
22794         }
22795         // @api
22796         function createThrowStatement(expression) {
22797             var node = createBaseNode(246 /* ThrowStatement */);
22798             node.expression = expression;
22799             node.transformFlags |= propagateChildFlags(node.expression);
22800             return node;
22801         }
22802         // @api
22803         function updateThrowStatement(node, expression) {
22804             return node.expression !== expression
22805                 ? update(createThrowStatement(expression), node)
22806                 : node;
22807         }
22808         // @api
22809         function createTryStatement(tryBlock, catchClause, finallyBlock) {
22810             var node = createBaseNode(247 /* TryStatement */);
22811             node.tryBlock = tryBlock;
22812             node.catchClause = catchClause;
22813             node.finallyBlock = finallyBlock;
22814             node.transformFlags |=
22815                 propagateChildFlags(node.tryBlock) |
22816                     propagateChildFlags(node.catchClause) |
22817                     propagateChildFlags(node.finallyBlock);
22818             return node;
22819         }
22820         // @api
22821         function updateTryStatement(node, tryBlock, catchClause, finallyBlock) {
22822             return node.tryBlock !== tryBlock
22823                 || node.catchClause !== catchClause
22824                 || node.finallyBlock !== finallyBlock
22825                 ? update(createTryStatement(tryBlock, catchClause, finallyBlock), node)
22826                 : node;
22827         }
22828         // @api
22829         function createDebuggerStatement() {
22830             return createBaseNode(248 /* DebuggerStatement */);
22831         }
22832         // @api
22833         function createVariableDeclaration(name, exclamationToken, type, initializer) {
22834             var node = createBaseVariableLikeDeclaration(249 /* VariableDeclaration */, 
22835             /*decorators*/ undefined, 
22836             /*modifiers*/ undefined, name, type, initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer));
22837             node.exclamationToken = exclamationToken;
22838             node.transformFlags |= propagateChildFlags(node.exclamationToken);
22839             if (exclamationToken) {
22840                 node.transformFlags |= 1 /* ContainsTypeScript */;
22841             }
22842             return node;
22843         }
22844         // @api
22845         function updateVariableDeclaration(node, name, exclamationToken, type, initializer) {
22846             return node.name !== name
22847                 || node.type !== type
22848                 || node.exclamationToken !== exclamationToken
22849                 || node.initializer !== initializer
22850                 ? update(createVariableDeclaration(name, exclamationToken, type, initializer), node)
22851                 : node;
22852         }
22853         // @api
22854         function createVariableDeclarationList(declarations, flags) {
22855             if (flags === void 0) { flags = 0 /* None */; }
22856             var node = createBaseNode(250 /* VariableDeclarationList */);
22857             node.flags |= flags & 3 /* BlockScoped */;
22858             node.declarations = createNodeArray(declarations);
22859             node.transformFlags |=
22860                 propagateChildrenFlags(node.declarations) |
22861                     1048576 /* ContainsHoistedDeclarationOrCompletion */;
22862             if (flags & 3 /* BlockScoped */) {
22863                 node.transformFlags |=
22864                     256 /* ContainsES2015 */ |
22865                         65536 /* ContainsBlockScopedBinding */;
22866             }
22867             return node;
22868         }
22869         // @api
22870         function updateVariableDeclarationList(node, declarations) {
22871             return node.declarations !== declarations
22872                 ? update(createVariableDeclarationList(declarations, node.flags), node)
22873                 : node;
22874         }
22875         // @api
22876         function createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22877             var node = createBaseFunctionLikeDeclaration(251 /* FunctionDeclaration */, decorators, modifiers, name, typeParameters, parameters, type, body);
22878             node.asteriskToken = asteriskToken;
22879             if (!node.body || ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22880                 node.transformFlags = 1 /* ContainsTypeScript */;
22881             }
22882             else {
22883                 node.transformFlags |=
22884                     propagateChildFlags(node.asteriskToken) |
22885                         1048576 /* ContainsHoistedDeclarationOrCompletion */;
22886                 if (ts.modifiersToFlags(node.modifiers) & 256 /* Async */) {
22887                     if (node.asteriskToken) {
22888                         node.transformFlags |= 32 /* ContainsES2018 */;
22889                     }
22890                     else {
22891                         node.transformFlags |= 64 /* ContainsES2017 */;
22892                     }
22893                 }
22894                 else if (node.asteriskToken) {
22895                     node.transformFlags |= 512 /* ContainsGenerator */;
22896                 }
22897             }
22898             return node;
22899         }
22900         // @api
22901         function updateFunctionDeclaration(node, decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body) {
22902             return node.decorators !== decorators
22903                 || node.modifiers !== modifiers
22904                 || node.asteriskToken !== asteriskToken
22905                 || node.name !== name
22906                 || node.typeParameters !== typeParameters
22907                 || node.parameters !== parameters
22908                 || node.type !== type
22909                 || node.body !== body
22910                 ? updateBaseFunctionLikeDeclaration(createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body), node)
22911                 : node;
22912         }
22913         // @api
22914         function createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
22915             var node = createBaseClassLikeDeclaration(252 /* ClassDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses, members);
22916             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
22917                 node.transformFlags = 1 /* ContainsTypeScript */;
22918             }
22919             else {
22920                 node.transformFlags |= 256 /* ContainsES2015 */;
22921                 if (node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */) {
22922                     node.transformFlags |= 1 /* ContainsTypeScript */;
22923                 }
22924             }
22925             return node;
22926         }
22927         // @api
22928         function updateClassDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
22929             return node.decorators !== decorators
22930                 || node.modifiers !== modifiers
22931                 || node.name !== name
22932                 || node.typeParameters !== typeParameters
22933                 || node.heritageClauses !== heritageClauses
22934                 || node.members !== members
22935                 ? update(createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
22936                 : node;
22937         }
22938         // @api
22939         function createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members) {
22940             var node = createBaseInterfaceOrClassLikeDeclaration(253 /* InterfaceDeclaration */, decorators, modifiers, name, typeParameters, heritageClauses);
22941             node.members = createNodeArray(members);
22942             node.transformFlags = 1 /* ContainsTypeScript */;
22943             return node;
22944         }
22945         // @api
22946         function updateInterfaceDeclaration(node, decorators, modifiers, name, typeParameters, heritageClauses, members) {
22947             return node.decorators !== decorators
22948                 || node.modifiers !== modifiers
22949                 || node.name !== name
22950                 || node.typeParameters !== typeParameters
22951                 || node.heritageClauses !== heritageClauses
22952                 || node.members !== members
22953                 ? update(createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members), node)
22954                 : node;
22955         }
22956         // @api
22957         function createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type) {
22958             var node = createBaseGenericNamedDeclaration(254 /* TypeAliasDeclaration */, decorators, modifiers, name, typeParameters);
22959             node.type = type;
22960             node.transformFlags = 1 /* ContainsTypeScript */;
22961             return node;
22962         }
22963         // @api
22964         function updateTypeAliasDeclaration(node, decorators, modifiers, name, typeParameters, type) {
22965             return node.decorators !== decorators
22966                 || node.modifiers !== modifiers
22967                 || node.name !== name
22968                 || node.typeParameters !== typeParameters
22969                 || node.type !== type
22970                 ? update(createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type), node)
22971                 : node;
22972         }
22973         // @api
22974         function createEnumDeclaration(decorators, modifiers, name, members) {
22975             var node = createBaseNamedDeclaration(255 /* EnumDeclaration */, decorators, modifiers, name);
22976             node.members = createNodeArray(members);
22977             node.transformFlags |=
22978                 propagateChildrenFlags(node.members) |
22979                     1 /* ContainsTypeScript */;
22980             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Enum declarations cannot contain `await`
22981             return node;
22982         }
22983         // @api
22984         function updateEnumDeclaration(node, decorators, modifiers, name, members) {
22985             return node.decorators !== decorators
22986                 || node.modifiers !== modifiers
22987                 || node.name !== name
22988                 || node.members !== members
22989                 ? update(createEnumDeclaration(decorators, modifiers, name, members), node)
22990                 : node;
22991         }
22992         // @api
22993         function createModuleDeclaration(decorators, modifiers, name, body, flags) {
22994             if (flags === void 0) { flags = 0 /* None */; }
22995             var node = createBaseDeclaration(256 /* ModuleDeclaration */, decorators, modifiers);
22996             node.flags |= flags & (16 /* Namespace */ | 4 /* NestedNamespace */ | 1024 /* GlobalAugmentation */);
22997             node.name = name;
22998             node.body = body;
22999             if (ts.modifiersToFlags(node.modifiers) & 2 /* Ambient */) {
23000                 node.transformFlags = 1 /* ContainsTypeScript */;
23001             }
23002             else {
23003                 node.transformFlags |=
23004                     propagateChildFlags(node.name) |
23005                         propagateChildFlags(node.body) |
23006                         1 /* ContainsTypeScript */;
23007             }
23008             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Module declarations cannot contain `await`.
23009             return node;
23010         }
23011         // @api
23012         function updateModuleDeclaration(node, decorators, modifiers, name, body) {
23013             return node.decorators !== decorators
23014                 || node.modifiers !== modifiers
23015                 || node.name !== name
23016                 || node.body !== body
23017                 ? update(createModuleDeclaration(decorators, modifiers, name, body, node.flags), node)
23018                 : node;
23019         }
23020         // @api
23021         function createModuleBlock(statements) {
23022             var node = createBaseNode(257 /* ModuleBlock */);
23023             node.statements = createNodeArray(statements);
23024             node.transformFlags |= propagateChildrenFlags(node.statements);
23025             return node;
23026         }
23027         // @api
23028         function updateModuleBlock(node, statements) {
23029             return node.statements !== statements
23030                 ? update(createModuleBlock(statements), node)
23031                 : node;
23032         }
23033         // @api
23034         function createCaseBlock(clauses) {
23035             var node = createBaseNode(258 /* CaseBlock */);
23036             node.clauses = createNodeArray(clauses);
23037             node.transformFlags |= propagateChildrenFlags(node.clauses);
23038             return node;
23039         }
23040         // @api
23041         function updateCaseBlock(node, clauses) {
23042             return node.clauses !== clauses
23043                 ? update(createCaseBlock(clauses), node)
23044                 : node;
23045         }
23046         // @api
23047         function createNamespaceExportDeclaration(name) {
23048             var node = createBaseNamedDeclaration(259 /* NamespaceExportDeclaration */, 
23049             /*decorators*/ undefined, 
23050             /*modifiers*/ undefined, name);
23051             node.transformFlags = 1 /* ContainsTypeScript */;
23052             return node;
23053         }
23054         // @api
23055         function updateNamespaceExportDeclaration(node, name) {
23056             return node.name !== name
23057                 ? update(createNamespaceExportDeclaration(name), node)
23058                 : node;
23059         }
23060         // @api
23061         function createImportEqualsDeclaration(decorators, modifiers, name, moduleReference) {
23062             var node = createBaseNamedDeclaration(260 /* ImportEqualsDeclaration */, decorators, modifiers, name);
23063             node.moduleReference = moduleReference;
23064             node.transformFlags |= propagateChildFlags(node.moduleReference);
23065             if (!ts.isExternalModuleReference(node.moduleReference))
23066                 node.transformFlags |= 1 /* ContainsTypeScript */;
23067             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // Import= declaration is always parsed in an Await context
23068             return node;
23069         }
23070         // @api
23071         function updateImportEqualsDeclaration(node, decorators, modifiers, name, moduleReference) {
23072             return node.decorators !== decorators
23073                 || node.modifiers !== modifiers
23074                 || node.name !== name
23075                 || node.moduleReference !== moduleReference
23076                 ? update(createImportEqualsDeclaration(decorators, modifiers, name, moduleReference), node)
23077                 : node;
23078         }
23079         // @api
23080         function createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier) {
23081             var node = createBaseDeclaration(261 /* ImportDeclaration */, decorators, modifiers);
23082             node.importClause = importClause;
23083             node.moduleSpecifier = moduleSpecifier;
23084             node.transformFlags |=
23085                 propagateChildFlags(node.importClause) |
23086                     propagateChildFlags(node.moduleSpecifier);
23087             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23088             return node;
23089         }
23090         // @api
23091         function updateImportDeclaration(node, decorators, modifiers, importClause, moduleSpecifier) {
23092             return node.decorators !== decorators
23093                 || node.modifiers !== modifiers
23094                 || node.importClause !== importClause
23095                 || node.moduleSpecifier !== moduleSpecifier
23096                 ? update(createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier), node)
23097                 : node;
23098         }
23099         // @api
23100         function createImportClause(isTypeOnly, name, namedBindings) {
23101             var node = createBaseNode(262 /* ImportClause */);
23102             node.isTypeOnly = isTypeOnly;
23103             node.name = name;
23104             node.namedBindings = namedBindings;
23105             node.transformFlags |=
23106                 propagateChildFlags(node.name) |
23107                     propagateChildFlags(node.namedBindings);
23108             if (isTypeOnly) {
23109                 node.transformFlags |= 1 /* ContainsTypeScript */;
23110             }
23111             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23112             return node;
23113         }
23114         // @api
23115         function updateImportClause(node, isTypeOnly, name, namedBindings) {
23116             return node.isTypeOnly !== isTypeOnly
23117                 || node.name !== name
23118                 || node.namedBindings !== namedBindings
23119                 ? update(createImportClause(isTypeOnly, name, namedBindings), node)
23120                 : node;
23121         }
23122         // @api
23123         function createNamespaceImport(name) {
23124             var node = createBaseNode(263 /* NamespaceImport */);
23125             node.name = name;
23126             node.transformFlags |= propagateChildFlags(node.name);
23127             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23128             return node;
23129         }
23130         // @api
23131         function updateNamespaceImport(node, name) {
23132             return node.name !== name
23133                 ? update(createNamespaceImport(name), node)
23134                 : node;
23135         }
23136         // @api
23137         function createNamespaceExport(name) {
23138             var node = createBaseNode(269 /* NamespaceExport */);
23139             node.name = name;
23140             node.transformFlags |=
23141                 propagateChildFlags(node.name) |
23142                     4 /* ContainsESNext */;
23143             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23144             return node;
23145         }
23146         // @api
23147         function updateNamespaceExport(node, name) {
23148             return node.name !== name
23149                 ? update(createNamespaceExport(name), node)
23150                 : node;
23151         }
23152         // @api
23153         function createNamedImports(elements) {
23154             var node = createBaseNode(264 /* NamedImports */);
23155             node.elements = createNodeArray(elements);
23156             node.transformFlags |= propagateChildrenFlags(node.elements);
23157             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23158             return node;
23159         }
23160         // @api
23161         function updateNamedImports(node, elements) {
23162             return node.elements !== elements
23163                 ? update(createNamedImports(elements), node)
23164                 : node;
23165         }
23166         // @api
23167         function createImportSpecifier(propertyName, name) {
23168             var node = createBaseNode(265 /* ImportSpecifier */);
23169             node.propertyName = propertyName;
23170             node.name = name;
23171             node.transformFlags |=
23172                 propagateChildFlags(node.propertyName) |
23173                     propagateChildFlags(node.name);
23174             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23175             return node;
23176         }
23177         // @api
23178         function updateImportSpecifier(node, propertyName, name) {
23179             return node.propertyName !== propertyName
23180                 || node.name !== name
23181                 ? update(createImportSpecifier(propertyName, name), node)
23182                 : node;
23183         }
23184         // @api
23185         function createExportAssignment(decorators, modifiers, isExportEquals, expression) {
23186             var node = createBaseDeclaration(266 /* ExportAssignment */, decorators, modifiers);
23187             node.isExportEquals = isExportEquals;
23188             node.expression = isExportEquals
23189                 ? parenthesizerRules().parenthesizeRightSideOfBinary(62 /* EqualsToken */, /*leftSide*/ undefined, expression)
23190                 : parenthesizerRules().parenthesizeExpressionOfExportDefault(expression);
23191             node.transformFlags |= propagateChildFlags(node.expression);
23192             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23193             return node;
23194         }
23195         // @api
23196         function updateExportAssignment(node, decorators, modifiers, expression) {
23197             return node.decorators !== decorators
23198                 || node.modifiers !== modifiers
23199                 || node.expression !== expression
23200                 ? update(createExportAssignment(decorators, modifiers, node.isExportEquals, expression), node)
23201                 : node;
23202         }
23203         // @api
23204         function createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) {
23205             var node = createBaseDeclaration(267 /* ExportDeclaration */, decorators, modifiers);
23206             node.isTypeOnly = isTypeOnly;
23207             node.exportClause = exportClause;
23208             node.moduleSpecifier = moduleSpecifier;
23209             node.transformFlags |=
23210                 propagateChildFlags(node.exportClause) |
23211                     propagateChildFlags(node.moduleSpecifier);
23212             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23213             return node;
23214         }
23215         // @api
23216         function updateExportDeclaration(node, decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier) {
23217             return node.decorators !== decorators
23218                 || node.modifiers !== modifiers
23219                 || node.isTypeOnly !== isTypeOnly
23220                 || node.exportClause !== exportClause
23221                 || node.moduleSpecifier !== moduleSpecifier
23222                 ? update(createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier), node)
23223                 : node;
23224         }
23225         // @api
23226         function createNamedExports(elements) {
23227             var node = createBaseNode(268 /* NamedExports */);
23228             node.elements = createNodeArray(elements);
23229             node.transformFlags |= propagateChildrenFlags(node.elements);
23230             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23231             return node;
23232         }
23233         // @api
23234         function updateNamedExports(node, elements) {
23235             return node.elements !== elements
23236                 ? update(createNamedExports(elements), node)
23237                 : node;
23238         }
23239         // @api
23240         function createExportSpecifier(propertyName, name) {
23241             var node = createBaseNode(270 /* ExportSpecifier */);
23242             node.propertyName = asName(propertyName);
23243             node.name = asName(name);
23244             node.transformFlags |=
23245                 propagateChildFlags(node.propertyName) |
23246                     propagateChildFlags(node.name);
23247             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23248             return node;
23249         }
23250         // @api
23251         function updateExportSpecifier(node, propertyName, name) {
23252             return node.propertyName !== propertyName
23253                 || node.name !== name
23254                 ? update(createExportSpecifier(propertyName, name), node)
23255                 : node;
23256         }
23257         // @api
23258         function createMissingDeclaration() {
23259             var node = createBaseDeclaration(271 /* MissingDeclaration */, 
23260             /*decorators*/ undefined, 
23261             /*modifiers*/ undefined);
23262             return node;
23263         }
23264         //
23265         // Module references
23266         //
23267         // @api
23268         function createExternalModuleReference(expression) {
23269             var node = createBaseNode(272 /* ExternalModuleReference */);
23270             node.expression = expression;
23271             node.transformFlags |= propagateChildFlags(node.expression);
23272             node.transformFlags &= ~8388608 /* ContainsPossibleTopLevelAwait */; // always parsed in an Await context
23273             return node;
23274         }
23275         // @api
23276         function updateExternalModuleReference(node, expression) {
23277             return node.expression !== expression
23278                 ? update(createExternalModuleReference(expression), node)
23279                 : node;
23280         }
23281         //
23282         // JSDoc
23283         //
23284         // @api
23285         // createJSDocAllType
23286         // createJSDocUnknownType
23287         function createJSDocPrimaryTypeWorker(kind) {
23288             return createBaseNode(kind);
23289         }
23290         // @api
23291         // createJSDocNonNullableType
23292         // createJSDocNullableType
23293         // createJSDocOptionalType
23294         // createJSDocVariadicType
23295         // createJSDocNamepathType
23296         function createJSDocUnaryTypeWorker(kind, type) {
23297             var node = createBaseNode(kind);
23298             node.type = type;
23299             return node;
23300         }
23301         // @api
23302         // updateJSDocNonNullableType
23303         // updateJSDocNullableType
23304         // updateJSDocOptionalType
23305         // updateJSDocVariadicType
23306         // updateJSDocNamepathType
23307         function updateJSDocUnaryTypeWorker(kind, node, type) {
23308             return node.type !== type
23309                 ? update(createJSDocUnaryTypeWorker(kind, type), node)
23310                 : node;
23311         }
23312         // @api
23313         function createJSDocFunctionType(parameters, type) {
23314             var node = createBaseSignatureDeclaration(308 /* JSDocFunctionType */, 
23315             /*decorators*/ undefined, 
23316             /*modifiers*/ undefined, 
23317             /*name*/ undefined, 
23318             /*typeParameters*/ undefined, parameters, type);
23319             return node;
23320         }
23321         // @api
23322         function updateJSDocFunctionType(node, parameters, type) {
23323             return node.parameters !== parameters
23324                 || node.type !== type
23325                 ? update(createJSDocFunctionType(parameters, type), node)
23326                 : node;
23327         }
23328         // @api
23329         function createJSDocTypeLiteral(propertyTags, isArrayType) {
23330             if (isArrayType === void 0) { isArrayType = false; }
23331             var node = createBaseNode(312 /* JSDocTypeLiteral */);
23332             node.jsDocPropertyTags = asNodeArray(propertyTags);
23333             node.isArrayType = isArrayType;
23334             return node;
23335         }
23336         // @api
23337         function updateJSDocTypeLiteral(node, propertyTags, isArrayType) {
23338             return node.jsDocPropertyTags !== propertyTags
23339                 || node.isArrayType !== isArrayType
23340                 ? update(createJSDocTypeLiteral(propertyTags, isArrayType), node)
23341                 : node;
23342         }
23343         // @api
23344         function createJSDocTypeExpression(type) {
23345             var node = createBaseNode(301 /* JSDocTypeExpression */);
23346             node.type = type;
23347             return node;
23348         }
23349         // @api
23350         function updateJSDocTypeExpression(node, type) {
23351             return node.type !== type
23352                 ? update(createJSDocTypeExpression(type), node)
23353                 : node;
23354         }
23355         // @api
23356         function createJSDocSignature(typeParameters, parameters, type) {
23357             var node = createBaseNode(313 /* JSDocSignature */);
23358             node.typeParameters = asNodeArray(typeParameters);
23359             node.parameters = createNodeArray(parameters);
23360             node.type = type;
23361             return node;
23362         }
23363         // @api
23364         function updateJSDocSignature(node, typeParameters, parameters, type) {
23365             return node.typeParameters !== typeParameters
23366                 || node.parameters !== parameters
23367                 || node.type !== type
23368                 ? update(createJSDocSignature(typeParameters, parameters, type), node)
23369                 : node;
23370         }
23371         function getDefaultTagName(node) {
23372             var defaultTagName = getDefaultTagNameForKind(node.kind);
23373             return node.tagName.escapedText === ts.escapeLeadingUnderscores(defaultTagName)
23374                 ? node.tagName
23375                 : createIdentifier(defaultTagName);
23376         }
23377         // @api
23378         function createBaseJSDocTag(kind, tagName, comment) {
23379             var node = createBaseNode(kind);
23380             node.tagName = tagName;
23381             node.comment = comment;
23382             return node;
23383         }
23384         // @api
23385         function createJSDocTemplateTag(tagName, constraint, typeParameters, comment) {
23386             var node = createBaseJSDocTag(330 /* JSDocTemplateTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("template"), comment);
23387             node.constraint = constraint;
23388             node.typeParameters = createNodeArray(typeParameters);
23389             return node;
23390         }
23391         // @api
23392         function updateJSDocTemplateTag(node, tagName, constraint, typeParameters, comment) {
23393             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23394             return node.tagName !== tagName
23395                 || node.constraint !== constraint
23396                 || node.typeParameters !== typeParameters
23397                 || node.comment !== comment
23398                 ? update(createJSDocTemplateTag(tagName, constraint, typeParameters, comment), node)
23399                 : node;
23400         }
23401         // @api
23402         function createJSDocTypedefTag(tagName, typeExpression, fullName, comment) {
23403             var node = createBaseJSDocTag(331 /* JSDocTypedefTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("typedef"), comment);
23404             node.typeExpression = typeExpression;
23405             node.fullName = fullName;
23406             node.name = ts.getJSDocTypeAliasName(fullName);
23407             return node;
23408         }
23409         // @api
23410         function updateJSDocTypedefTag(node, tagName, typeExpression, fullName, comment) {
23411             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23412             return node.tagName !== tagName
23413                 || node.typeExpression !== typeExpression
23414                 || node.fullName !== fullName
23415                 || node.comment !== comment
23416                 ? update(createJSDocTypedefTag(tagName, typeExpression, fullName, comment), node)
23417                 : node;
23418         }
23419         // @api
23420         function createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23421             var node = createBaseJSDocTag(326 /* JSDocParameterTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("param"), comment);
23422             node.typeExpression = typeExpression;
23423             node.name = name;
23424             node.isNameFirst = !!isNameFirst;
23425             node.isBracketed = isBracketed;
23426             return node;
23427         }
23428         // @api
23429         function updateJSDocParameterTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23430             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23431             return node.tagName !== tagName
23432                 || node.name !== name
23433                 || node.isBracketed !== isBracketed
23434                 || node.typeExpression !== typeExpression
23435                 || node.isNameFirst !== isNameFirst
23436                 || node.comment !== comment
23437                 ? update(createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
23438                 : node;
23439         }
23440         // @api
23441         function createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23442             var node = createBaseJSDocTag(333 /* JSDocPropertyTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("prop"), comment);
23443             node.typeExpression = typeExpression;
23444             node.name = name;
23445             node.isNameFirst = !!isNameFirst;
23446             node.isBracketed = isBracketed;
23447             return node;
23448         }
23449         // @api
23450         function updateJSDocPropertyTag(node, tagName, name, isBracketed, typeExpression, isNameFirst, comment) {
23451             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23452             return node.tagName !== tagName
23453                 || node.name !== name
23454                 || node.isBracketed !== isBracketed
23455                 || node.typeExpression !== typeExpression
23456                 || node.isNameFirst !== isNameFirst
23457                 || node.comment !== comment
23458                 ? update(createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment), node)
23459                 : node;
23460         }
23461         // @api
23462         function createJSDocCallbackTag(tagName, typeExpression, fullName, comment) {
23463             var node = createBaseJSDocTag(324 /* JSDocCallbackTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("callback"), comment);
23464             node.typeExpression = typeExpression;
23465             node.fullName = fullName;
23466             node.name = ts.getJSDocTypeAliasName(fullName);
23467             return node;
23468         }
23469         // @api
23470         function updateJSDocCallbackTag(node, tagName, typeExpression, fullName, comment) {
23471             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23472             return node.tagName !== tagName
23473                 || node.typeExpression !== typeExpression
23474                 || node.fullName !== fullName
23475                 || node.comment !== comment
23476                 ? update(createJSDocCallbackTag(tagName, typeExpression, fullName, comment), node)
23477                 : node;
23478         }
23479         // @api
23480         function createJSDocAugmentsTag(tagName, className, comment) {
23481             var node = createBaseJSDocTag(315 /* JSDocAugmentsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("augments"), comment);
23482             node.class = className;
23483             return node;
23484         }
23485         // @api
23486         function updateJSDocAugmentsTag(node, tagName, className, comment) {
23487             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23488             return node.tagName !== tagName
23489                 || node.class !== className
23490                 || node.comment !== comment
23491                 ? update(createJSDocAugmentsTag(tagName, className, comment), node)
23492                 : node;
23493         }
23494         // @api
23495         function createJSDocImplementsTag(tagName, className, comment) {
23496             var node = createBaseJSDocTag(316 /* JSDocImplementsTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("implements"), comment);
23497             node.class = className;
23498             return node;
23499         }
23500         // @api
23501         function createJSDocSeeTag(tagName, name, comment) {
23502             var node = createBaseJSDocTag(332 /* JSDocSeeTag */, tagName !== null && tagName !== void 0 ? tagName : createIdentifier("see"), comment);
23503             node.name = name;
23504             return node;
23505         }
23506         // @api
23507         function updateJSDocSeeTag(node, tagName, name, comment) {
23508             return node.tagName !== tagName
23509                 || node.name !== name
23510                 || node.comment !== comment
23511                 ? update(createJSDocSeeTag(tagName, name, comment), node)
23512                 : node;
23513         }
23514         // @api
23515         function createJSDocNameReference(name) {
23516             var node = createBaseNode(302 /* JSDocNameReference */);
23517             node.name = name;
23518             return node;
23519         }
23520         // @api
23521         function updateJSDocNameReference(node, name) {
23522             return node.name !== name
23523                 ? update(createJSDocNameReference(name), node)
23524                 : node;
23525         }
23526         // @api
23527         function updateJSDocImplementsTag(node, tagName, className, comment) {
23528             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23529             return node.tagName !== tagName
23530                 || node.class !== className
23531                 || node.comment !== comment
23532                 ? update(createJSDocImplementsTag(tagName, className, comment), node)
23533                 : node;
23534         }
23535         // @api
23536         // createJSDocAuthorTag
23537         // createJSDocClassTag
23538         // createJSDocPublicTag
23539         // createJSDocPrivateTag
23540         // createJSDocProtectedTag
23541         // createJSDocReadonlyTag
23542         // createJSDocDeprecatedTag
23543         function createJSDocSimpleTagWorker(kind, tagName, comment) {
23544             var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
23545             return node;
23546         }
23547         // @api
23548         // updateJSDocAuthorTag
23549         // updateJSDocClassTag
23550         // updateJSDocPublicTag
23551         // updateJSDocPrivateTag
23552         // updateJSDocProtectedTag
23553         // updateJSDocReadonlyTag
23554         // updateJSDocDeprecatedTag
23555         function updateJSDocSimpleTagWorker(kind, node, tagName, comment) {
23556             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23557             return node.tagName !== tagName
23558                 || node.comment !== comment
23559                 ? update(createJSDocSimpleTagWorker(kind, tagName, comment), node) :
23560                 node;
23561         }
23562         // @api
23563         // createJSDocTypeTag
23564         // createJSDocReturnTag
23565         // createJSDocThisTag
23566         // createJSDocEnumTag
23567         function createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment) {
23568             var node = createBaseJSDocTag(kind, tagName !== null && tagName !== void 0 ? tagName : createIdentifier(getDefaultTagNameForKind(kind)), comment);
23569             node.typeExpression = typeExpression;
23570             return node;
23571         }
23572         // @api
23573         // updateJSDocTypeTag
23574         // updateJSDocReturnTag
23575         // updateJSDocThisTag
23576         // updateJSDocEnumTag
23577         function updateJSDocTypeLikeTagWorker(kind, node, tagName, typeExpression, comment) {
23578             if (tagName === void 0) { tagName = getDefaultTagName(node); }
23579             return node.tagName !== tagName
23580                 || node.typeExpression !== typeExpression
23581                 || node.comment !== comment
23582                 ? update(createJSDocTypeLikeTagWorker(kind, tagName, typeExpression, comment), node)
23583                 : node;
23584         }
23585         // @api
23586         function createJSDocUnknownTag(tagName, comment) {
23587             var node = createBaseJSDocTag(314 /* JSDocTag */, tagName, comment);
23588             return node;
23589         }
23590         // @api
23591         function updateJSDocUnknownTag(node, tagName, comment) {
23592             return node.tagName !== tagName
23593                 || node.comment !== comment
23594                 ? update(createJSDocUnknownTag(tagName, comment), node)
23595                 : node;
23596         }
23597         // @api
23598         function createJSDocComment(comment, tags) {
23599             var node = createBaseNode(311 /* JSDocComment */);
23600             node.comment = comment;
23601             node.tags = asNodeArray(tags);
23602             return node;
23603         }
23604         // @api
23605         function updateJSDocComment(node, comment, tags) {
23606             return node.comment !== comment
23607                 || node.tags !== tags
23608                 ? update(createJSDocComment(comment, tags), node)
23609                 : node;
23610         }
23611         //
23612         // JSX
23613         //
23614         // @api
23615         function createJsxElement(openingElement, children, closingElement) {
23616             var node = createBaseNode(273 /* JsxElement */);
23617             node.openingElement = openingElement;
23618             node.children = createNodeArray(children);
23619             node.closingElement = closingElement;
23620             node.transformFlags |=
23621                 propagateChildFlags(node.openingElement) |
23622                     propagateChildrenFlags(node.children) |
23623                     propagateChildFlags(node.closingElement) |
23624                     2 /* ContainsJsx */;
23625             return node;
23626         }
23627         // @api
23628         function updateJsxElement(node, openingElement, children, closingElement) {
23629             return node.openingElement !== openingElement
23630                 || node.children !== children
23631                 || node.closingElement !== closingElement
23632                 ? update(createJsxElement(openingElement, children, closingElement), node)
23633                 : node;
23634         }
23635         // @api
23636         function createJsxSelfClosingElement(tagName, typeArguments, attributes) {
23637             var node = createBaseNode(274 /* JsxSelfClosingElement */);
23638             node.tagName = tagName;
23639             node.typeArguments = asNodeArray(typeArguments);
23640             node.attributes = attributes;
23641             node.transformFlags |=
23642                 propagateChildFlags(node.tagName) |
23643                     propagateChildrenFlags(node.typeArguments) |
23644                     propagateChildFlags(node.attributes) |
23645                     2 /* ContainsJsx */;
23646             if (node.typeArguments) {
23647                 node.transformFlags |= 1 /* ContainsTypeScript */;
23648             }
23649             return node;
23650         }
23651         // @api
23652         function updateJsxSelfClosingElement(node, tagName, typeArguments, attributes) {
23653             return node.tagName !== tagName
23654                 || node.typeArguments !== typeArguments
23655                 || node.attributes !== attributes
23656                 ? update(createJsxSelfClosingElement(tagName, typeArguments, attributes), node)
23657                 : node;
23658         }
23659         // @api
23660         function createJsxOpeningElement(tagName, typeArguments, attributes) {
23661             var node = createBaseNode(275 /* JsxOpeningElement */);
23662             node.tagName = tagName;
23663             node.typeArguments = asNodeArray(typeArguments);
23664             node.attributes = attributes;
23665             node.transformFlags |=
23666                 propagateChildFlags(node.tagName) |
23667                     propagateChildrenFlags(node.typeArguments) |
23668                     propagateChildFlags(node.attributes) |
23669                     2 /* ContainsJsx */;
23670             if (typeArguments) {
23671                 node.transformFlags |= 1 /* ContainsTypeScript */;
23672             }
23673             return node;
23674         }
23675         // @api
23676         function updateJsxOpeningElement(node, tagName, typeArguments, attributes) {
23677             return node.tagName !== tagName
23678                 || node.typeArguments !== typeArguments
23679                 || node.attributes !== attributes
23680                 ? update(createJsxOpeningElement(tagName, typeArguments, attributes), node)
23681                 : node;
23682         }
23683         // @api
23684         function createJsxClosingElement(tagName) {
23685             var node = createBaseNode(276 /* JsxClosingElement */);
23686             node.tagName = tagName;
23687             node.transformFlags |=
23688                 propagateChildFlags(node.tagName) |
23689                     2 /* ContainsJsx */;
23690             return node;
23691         }
23692         // @api
23693         function updateJsxClosingElement(node, tagName) {
23694             return node.tagName !== tagName
23695                 ? update(createJsxClosingElement(tagName), node)
23696                 : node;
23697         }
23698         // @api
23699         function createJsxFragment(openingFragment, children, closingFragment) {
23700             var node = createBaseNode(277 /* JsxFragment */);
23701             node.openingFragment = openingFragment;
23702             node.children = createNodeArray(children);
23703             node.closingFragment = closingFragment;
23704             node.transformFlags |=
23705                 propagateChildFlags(node.openingFragment) |
23706                     propagateChildrenFlags(node.children) |
23707                     propagateChildFlags(node.closingFragment) |
23708                     2 /* ContainsJsx */;
23709             return node;
23710         }
23711         // @api
23712         function updateJsxFragment(node, openingFragment, children, closingFragment) {
23713             return node.openingFragment !== openingFragment
23714                 || node.children !== children
23715                 || node.closingFragment !== closingFragment
23716                 ? update(createJsxFragment(openingFragment, children, closingFragment), node)
23717                 : node;
23718         }
23719         // @api
23720         function createJsxText(text, containsOnlyTriviaWhiteSpaces) {
23721             var node = createBaseNode(11 /* JsxText */);
23722             node.text = text;
23723             node.containsOnlyTriviaWhiteSpaces = !!containsOnlyTriviaWhiteSpaces;
23724             node.transformFlags |= 2 /* ContainsJsx */;
23725             return node;
23726         }
23727         // @api
23728         function updateJsxText(node, text, containsOnlyTriviaWhiteSpaces) {
23729             return node.text !== text
23730                 || node.containsOnlyTriviaWhiteSpaces !== containsOnlyTriviaWhiteSpaces
23731                 ? update(createJsxText(text, containsOnlyTriviaWhiteSpaces), node)
23732                 : node;
23733         }
23734         // @api
23735         function createJsxOpeningFragment() {
23736             var node = createBaseNode(278 /* JsxOpeningFragment */);
23737             node.transformFlags |= 2 /* ContainsJsx */;
23738             return node;
23739         }
23740         // @api
23741         function createJsxJsxClosingFragment() {
23742             var node = createBaseNode(279 /* JsxClosingFragment */);
23743             node.transformFlags |= 2 /* ContainsJsx */;
23744             return node;
23745         }
23746         // @api
23747         function createJsxAttribute(name, initializer) {
23748             var node = createBaseNode(280 /* JsxAttribute */);
23749             node.name = name;
23750             node.initializer = initializer;
23751             node.transformFlags |=
23752                 propagateChildFlags(node.name) |
23753                     propagateChildFlags(node.initializer) |
23754                     2 /* ContainsJsx */;
23755             return node;
23756         }
23757         // @api
23758         function updateJsxAttribute(node, name, initializer) {
23759             return node.name !== name
23760                 || node.initializer !== initializer
23761                 ? update(createJsxAttribute(name, initializer), node)
23762                 : node;
23763         }
23764         // @api
23765         function createJsxAttributes(properties) {
23766             var node = createBaseNode(281 /* JsxAttributes */);
23767             node.properties = createNodeArray(properties);
23768             node.transformFlags |=
23769                 propagateChildrenFlags(node.properties) |
23770                     2 /* ContainsJsx */;
23771             return node;
23772         }
23773         // @api
23774         function updateJsxAttributes(node, properties) {
23775             return node.properties !== properties
23776                 ? update(createJsxAttributes(properties), node)
23777                 : node;
23778         }
23779         // @api
23780         function createJsxSpreadAttribute(expression) {
23781             var node = createBaseNode(282 /* JsxSpreadAttribute */);
23782             node.expression = expression;
23783             node.transformFlags |=
23784                 propagateChildFlags(node.expression) |
23785                     2 /* ContainsJsx */;
23786             return node;
23787         }
23788         // @api
23789         function updateJsxSpreadAttribute(node, expression) {
23790             return node.expression !== expression
23791                 ? update(createJsxSpreadAttribute(expression), node)
23792                 : node;
23793         }
23794         // @api
23795         function createJsxExpression(dotDotDotToken, expression) {
23796             var node = createBaseNode(283 /* JsxExpression */);
23797             node.dotDotDotToken = dotDotDotToken;
23798             node.expression = expression;
23799             node.transformFlags |=
23800                 propagateChildFlags(node.dotDotDotToken) |
23801                     propagateChildFlags(node.expression) |
23802                     2 /* ContainsJsx */;
23803             return node;
23804         }
23805         // @api
23806         function updateJsxExpression(node, expression) {
23807             return node.expression !== expression
23808                 ? update(createJsxExpression(node.dotDotDotToken, expression), node)
23809                 : node;
23810         }
23811         //
23812         // Clauses
23813         //
23814         // @api
23815         function createCaseClause(expression, statements) {
23816             var node = createBaseNode(284 /* CaseClause */);
23817             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23818             node.statements = createNodeArray(statements);
23819             node.transformFlags |=
23820                 propagateChildFlags(node.expression) |
23821                     propagateChildrenFlags(node.statements);
23822             return node;
23823         }
23824         // @api
23825         function updateCaseClause(node, expression, statements) {
23826             return node.expression !== expression
23827                 || node.statements !== statements
23828                 ? update(createCaseClause(expression, statements), node)
23829                 : node;
23830         }
23831         // @api
23832         function createDefaultClause(statements) {
23833             var node = createBaseNode(285 /* DefaultClause */);
23834             node.statements = createNodeArray(statements);
23835             node.transformFlags = propagateChildrenFlags(node.statements);
23836             return node;
23837         }
23838         // @api
23839         function updateDefaultClause(node, statements) {
23840             return node.statements !== statements
23841                 ? update(createDefaultClause(statements), node)
23842                 : node;
23843         }
23844         // @api
23845         function createHeritageClause(token, types) {
23846             var node = createBaseNode(286 /* HeritageClause */);
23847             node.token = token;
23848             node.types = createNodeArray(types);
23849             node.transformFlags |= propagateChildrenFlags(node.types);
23850             switch (token) {
23851                 case 93 /* ExtendsKeyword */:
23852                     node.transformFlags |= 256 /* ContainsES2015 */;
23853                     break;
23854                 case 116 /* ImplementsKeyword */:
23855                     node.transformFlags |= 1 /* ContainsTypeScript */;
23856                     break;
23857                 default:
23858                     return ts.Debug.assertNever(token);
23859             }
23860             return node;
23861         }
23862         // @api
23863         function updateHeritageClause(node, types) {
23864             return node.types !== types
23865                 ? update(createHeritageClause(node.token, types), node)
23866                 : node;
23867         }
23868         // @api
23869         function createCatchClause(variableDeclaration, block) {
23870             var node = createBaseNode(287 /* CatchClause */);
23871             variableDeclaration = !ts.isString(variableDeclaration) ? variableDeclaration : createVariableDeclaration(variableDeclaration, 
23872             /*exclamationToken*/ undefined, 
23873             /*type*/ undefined, 
23874             /*initializer*/ undefined);
23875             node.variableDeclaration = variableDeclaration;
23876             node.block = block;
23877             node.transformFlags |=
23878                 propagateChildFlags(node.variableDeclaration) |
23879                     propagateChildFlags(node.block);
23880             if (!variableDeclaration)
23881                 node.transformFlags |= 16 /* ContainsES2019 */;
23882             return node;
23883         }
23884         // @api
23885         function updateCatchClause(node, variableDeclaration, block) {
23886             return node.variableDeclaration !== variableDeclaration
23887                 || node.block !== block
23888                 ? update(createCatchClause(variableDeclaration, block), node)
23889                 : node;
23890         }
23891         //
23892         // Property assignments
23893         //
23894         // @api
23895         function createPropertyAssignment(name, initializer) {
23896             var node = createBaseNamedDeclaration(288 /* PropertyAssignment */, 
23897             /*decorators*/ undefined, 
23898             /*modifiers*/ undefined, name);
23899             node.initializer = parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
23900             node.transformFlags |=
23901                 propagateChildFlags(node.name) |
23902                     propagateChildFlags(node.initializer);
23903             return node;
23904         }
23905         function finishUpdatePropertyAssignment(updated, original) {
23906             // copy children used only for error reporting
23907             if (original.decorators)
23908                 updated.decorators = original.decorators;
23909             if (original.modifiers)
23910                 updated.modifiers = original.modifiers;
23911             if (original.questionToken)
23912                 updated.questionToken = original.questionToken;
23913             if (original.exclamationToken)
23914                 updated.exclamationToken = original.exclamationToken;
23915             return update(updated, original);
23916         }
23917         // @api
23918         function updatePropertyAssignment(node, name, initializer) {
23919             return node.name !== name
23920                 || node.initializer !== initializer
23921                 ? finishUpdatePropertyAssignment(createPropertyAssignment(name, initializer), node)
23922                 : node;
23923         }
23924         // @api
23925         function createShorthandPropertyAssignment(name, objectAssignmentInitializer) {
23926             var node = createBaseNamedDeclaration(289 /* ShorthandPropertyAssignment */, 
23927             /*decorators*/ undefined, 
23928             /*modifiers*/ undefined, name);
23929             node.objectAssignmentInitializer = objectAssignmentInitializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(objectAssignmentInitializer);
23930             node.transformFlags |=
23931                 propagateChildFlags(node.objectAssignmentInitializer) |
23932                     256 /* ContainsES2015 */;
23933             return node;
23934         }
23935         function finishUpdateShorthandPropertyAssignment(updated, original) {
23936             // copy children used only for error reporting
23937             if (original.decorators)
23938                 updated.decorators = original.decorators;
23939             if (original.modifiers)
23940                 updated.modifiers = original.modifiers;
23941             if (original.equalsToken)
23942                 updated.equalsToken = original.equalsToken;
23943             if (original.questionToken)
23944                 updated.questionToken = original.questionToken;
23945             if (original.exclamationToken)
23946                 updated.exclamationToken = original.exclamationToken;
23947             return update(updated, original);
23948         }
23949         // @api
23950         function updateShorthandPropertyAssignment(node, name, objectAssignmentInitializer) {
23951             return node.name !== name
23952                 || node.objectAssignmentInitializer !== objectAssignmentInitializer
23953                 ? finishUpdateShorthandPropertyAssignment(createShorthandPropertyAssignment(name, objectAssignmentInitializer), node)
23954                 : node;
23955         }
23956         // @api
23957         function createSpreadAssignment(expression) {
23958             var node = createBaseNode(290 /* SpreadAssignment */);
23959             node.expression = parenthesizerRules().parenthesizeExpressionForDisallowedComma(expression);
23960             node.transformFlags |=
23961                 propagateChildFlags(node.expression) |
23962                     32 /* ContainsES2018 */ |
23963                     16384 /* ContainsObjectRestOrSpread */;
23964             return node;
23965         }
23966         // @api
23967         function updateSpreadAssignment(node, expression) {
23968             return node.expression !== expression
23969                 ? update(createSpreadAssignment(expression), node)
23970                 : node;
23971         }
23972         //
23973         // Enum
23974         //
23975         // @api
23976         function createEnumMember(name, initializer) {
23977             var node = createBaseNode(291 /* EnumMember */);
23978             node.name = asName(name);
23979             node.initializer = initializer && parenthesizerRules().parenthesizeExpressionForDisallowedComma(initializer);
23980             node.transformFlags |=
23981                 propagateChildFlags(node.name) |
23982                     propagateChildFlags(node.initializer) |
23983                     1 /* ContainsTypeScript */;
23984             return node;
23985         }
23986         // @api
23987         function updateEnumMember(node, name, initializer) {
23988             return node.name !== name
23989                 || node.initializer !== initializer
23990                 ? update(createEnumMember(name, initializer), node)
23991                 : node;
23992         }
23993         //
23994         // Top-level nodes
23995         //
23996         // @api
23997         function createSourceFile(statements, endOfFileToken, flags) {
23998             var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */);
23999             node.statements = createNodeArray(statements);
24000             node.endOfFileToken = endOfFileToken;
24001             node.flags |= flags;
24002             node.fileName = "";
24003             node.text = "";
24004             node.languageVersion = 0;
24005             node.languageVariant = 0;
24006             node.scriptKind = 0;
24007             node.isDeclarationFile = false;
24008             node.hasNoDefaultLib = false;
24009             node.transformFlags |=
24010                 propagateChildrenFlags(node.statements) |
24011                     propagateChildFlags(node.endOfFileToken);
24012             return node;
24013         }
24014         function cloneSourceFileWithChanges(source, statements, isDeclarationFile, referencedFiles, typeReferences, hasNoDefaultLib, libReferences) {
24015             var node = baseFactory.createBaseSourceFileNode(297 /* SourceFile */);
24016             for (var p in source) {
24017                 if (p === "emitNode" || ts.hasProperty(node, p) || !ts.hasProperty(source, p))
24018                     continue;
24019                 node[p] = source[p];
24020             }
24021             node.flags |= source.flags;
24022             node.statements = createNodeArray(statements);
24023             node.endOfFileToken = source.endOfFileToken;
24024             node.isDeclarationFile = isDeclarationFile;
24025             node.referencedFiles = referencedFiles;
24026             node.typeReferenceDirectives = typeReferences;
24027             node.hasNoDefaultLib = hasNoDefaultLib;
24028             node.libReferenceDirectives = libReferences;
24029             node.transformFlags =
24030                 propagateChildrenFlags(node.statements) |
24031                     propagateChildFlags(node.endOfFileToken);
24032             return node;
24033         }
24034         // @api
24035         function updateSourceFile(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives) {
24036             if (isDeclarationFile === void 0) { isDeclarationFile = node.isDeclarationFile; }
24037             if (referencedFiles === void 0) { referencedFiles = node.referencedFiles; }
24038             if (typeReferenceDirectives === void 0) { typeReferenceDirectives = node.typeReferenceDirectives; }
24039             if (hasNoDefaultLib === void 0) { hasNoDefaultLib = node.hasNoDefaultLib; }
24040             if (libReferenceDirectives === void 0) { libReferenceDirectives = node.libReferenceDirectives; }
24041             return node.statements !== statements
24042                 || node.isDeclarationFile !== isDeclarationFile
24043                 || node.referencedFiles !== referencedFiles
24044                 || node.typeReferenceDirectives !== typeReferenceDirectives
24045                 || node.hasNoDefaultLib !== hasNoDefaultLib
24046                 || node.libReferenceDirectives !== libReferenceDirectives
24047                 ? update(cloneSourceFileWithChanges(node, statements, isDeclarationFile, referencedFiles, typeReferenceDirectives, hasNoDefaultLib, libReferenceDirectives), node)
24048                 : node;
24049         }
24050         // @api
24051         function createBundle(sourceFiles, prepends) {
24052             if (prepends === void 0) { prepends = ts.emptyArray; }
24053             var node = createBaseNode(298 /* Bundle */);
24054             node.prepends = prepends;
24055             node.sourceFiles = sourceFiles;
24056             return node;
24057         }
24058         // @api
24059         function updateBundle(node, sourceFiles, prepends) {
24060             if (prepends === void 0) { prepends = ts.emptyArray; }
24061             return node.sourceFiles !== sourceFiles
24062                 || node.prepends !== prepends
24063                 ? update(createBundle(sourceFiles, prepends), node)
24064                 : node;
24065         }
24066         // @api
24067         function createUnparsedSource(prologues, syntheticReferences, texts) {
24068             var node = createBaseNode(299 /* UnparsedSource */);
24069             node.prologues = prologues;
24070             node.syntheticReferences = syntheticReferences;
24071             node.texts = texts;
24072             node.fileName = "";
24073             node.text = "";
24074             node.referencedFiles = ts.emptyArray;
24075             node.libReferenceDirectives = ts.emptyArray;
24076             node.getLineAndCharacterOfPosition = function (pos) { return ts.getLineAndCharacterOfPosition(node, pos); };
24077             return node;
24078         }
24079         function createBaseUnparsedNode(kind, data) {
24080             var node = createBaseNode(kind);
24081             node.data = data;
24082             return node;
24083         }
24084         // @api
24085         function createUnparsedPrologue(data) {
24086             return createBaseUnparsedNode(292 /* UnparsedPrologue */, data);
24087         }
24088         // @api
24089         function createUnparsedPrepend(data, texts) {
24090             var node = createBaseUnparsedNode(293 /* UnparsedPrepend */, data);
24091             node.texts = texts;
24092             return node;
24093         }
24094         // @api
24095         function createUnparsedTextLike(data, internal) {
24096             return createBaseUnparsedNode(internal ? 295 /* UnparsedInternalText */ : 294 /* UnparsedText */, data);
24097         }
24098         // @api
24099         function createUnparsedSyntheticReference(section) {
24100             var node = createBaseNode(296 /* UnparsedSyntheticReference */);
24101             node.data = section.data;
24102             node.section = section;
24103             return node;
24104         }
24105         // @api
24106         function createInputFiles() {
24107             var node = createBaseNode(300 /* InputFiles */);
24108             node.javascriptText = "";
24109             node.declarationText = "";
24110             return node;
24111         }
24112         //
24113         // Synthetic Nodes (used by checker)
24114         //
24115         // @api
24116         function createSyntheticExpression(type, isSpread, tupleNameSource) {
24117             if (isSpread === void 0) { isSpread = false; }
24118             var node = createBaseNode(227 /* SyntheticExpression */);
24119             node.type = type;
24120             node.isSpread = isSpread;
24121             node.tupleNameSource = tupleNameSource;
24122             return node;
24123         }
24124         // @api
24125         function createSyntaxList(children) {
24126             var node = createBaseNode(334 /* SyntaxList */);
24127             node._children = children;
24128             return node;
24129         }
24130         //
24131         // Transformation nodes
24132         //
24133         /**
24134          * Creates a synthetic statement to act as a placeholder for a not-emitted statement in
24135          * order to preserve comments.
24136          *
24137          * @param original The original statement.
24138          */
24139         // @api
24140         function createNotEmittedStatement(original) {
24141             var node = createBaseNode(335 /* NotEmittedStatement */);
24142             node.original = original;
24143             ts.setTextRange(node, original);
24144             return node;
24145         }
24146         /**
24147          * Creates a synthetic expression to act as a placeholder for a not-emitted expression in
24148          * order to preserve comments or sourcemap positions.
24149          *
24150          * @param expression The inner expression to emit.
24151          * @param original The original outer expression.
24152          */
24153         // @api
24154         function createPartiallyEmittedExpression(expression, original) {
24155             var node = createBaseNode(336 /* PartiallyEmittedExpression */);
24156             node.expression = expression;
24157             node.original = original;
24158             node.transformFlags |=
24159                 propagateChildFlags(node.expression) |
24160                     1 /* ContainsTypeScript */;
24161             ts.setTextRange(node, original);
24162             return node;
24163         }
24164         // @api
24165         function updatePartiallyEmittedExpression(node, expression) {
24166             return node.expression !== expression
24167                 ? update(createPartiallyEmittedExpression(expression, node.original), node)
24168                 : node;
24169         }
24170         function flattenCommaElements(node) {
24171             if (ts.nodeIsSynthesized(node) && !ts.isParseTreeNode(node) && !node.original && !node.emitNode && !node.id) {
24172                 if (ts.isCommaListExpression(node)) {
24173                     return node.elements;
24174                 }
24175                 if (ts.isBinaryExpression(node) && ts.isCommaToken(node.operatorToken)) {
24176                     return [node.left, node.right];
24177                 }
24178             }
24179             return node;
24180         }
24181         // @api
24182         function createCommaListExpression(elements) {
24183             var node = createBaseNode(337 /* CommaListExpression */);
24184             node.elements = createNodeArray(ts.sameFlatMap(elements, flattenCommaElements));
24185             node.transformFlags |= propagateChildrenFlags(node.elements);
24186             return node;
24187         }
24188         // @api
24189         function updateCommaListExpression(node, elements) {
24190             return node.elements !== elements
24191                 ? update(createCommaListExpression(elements), node)
24192                 : node;
24193         }
24194         /**
24195          * Creates a synthetic element to act as a placeholder for the end of an emitted declaration in
24196          * order to properly emit exports.
24197          */
24198         // @api
24199         function createEndOfDeclarationMarker(original) {
24200             var node = createBaseNode(339 /* EndOfDeclarationMarker */);
24201             node.emitNode = {};
24202             node.original = original;
24203             return node;
24204         }
24205         /**
24206          * Creates a synthetic element to act as a placeholder for the beginning of a merged declaration in
24207          * order to properly emit exports.
24208          */
24209         // @api
24210         function createMergeDeclarationMarker(original) {
24211             var node = createBaseNode(338 /* MergeDeclarationMarker */);
24212             node.emitNode = {};
24213             node.original = original;
24214             return node;
24215         }
24216         // @api
24217         function createSyntheticReferenceExpression(expression, thisArg) {
24218             var node = createBaseNode(340 /* SyntheticReferenceExpression */);
24219             node.expression = expression;
24220             node.thisArg = thisArg;
24221             node.transformFlags |=
24222                 propagateChildFlags(node.expression) |
24223                     propagateChildFlags(node.thisArg);
24224             return node;
24225         }
24226         // @api
24227         function updateSyntheticReferenceExpression(node, expression, thisArg) {
24228             return node.expression !== expression
24229                 || node.thisArg !== thisArg
24230                 ? update(createSyntheticReferenceExpression(expression, thisArg), node)
24231                 : node;
24232         }
24233         function cloneNode(node) {
24234             // We don't use "clone" from core.ts here, as we need to preserve the prototype chain of
24235             // the original node. We also need to exclude specific properties and only include own-
24236             // properties (to skip members already defined on the shared prototype).
24237             if (node === undefined) {
24238                 return node;
24239             }
24240             var clone = ts.isSourceFile(node) ? baseFactory.createBaseSourceFileNode(297 /* SourceFile */) :
24241                 ts.isIdentifier(node) ? baseFactory.createBaseIdentifierNode(78 /* Identifier */) :
24242                     ts.isPrivateIdentifier(node) ? baseFactory.createBasePrivateIdentifierNode(79 /* PrivateIdentifier */) :
24243                         !ts.isNodeKind(node.kind) ? baseFactory.createBaseTokenNode(node.kind) :
24244                             baseFactory.createBaseNode(node.kind);
24245             clone.flags |= (node.flags & ~8 /* Synthesized */);
24246             clone.transformFlags = node.transformFlags;
24247             setOriginalNode(clone, node);
24248             for (var key in node) {
24249                 if (clone.hasOwnProperty(key) || !node.hasOwnProperty(key)) {
24250                     continue;
24251                 }
24252                 clone[key] = node[key];
24253             }
24254             return clone;
24255         }
24256         function createImmediatelyInvokedFunctionExpression(statements, param, paramValue) {
24257             return createCallExpression(createFunctionExpression(
24258             /*modifiers*/ undefined, 
24259             /*asteriskToken*/ undefined, 
24260             /*name*/ undefined, 
24261             /*typeParameters*/ undefined, 
24262             /*parameters*/ param ? [param] : [], 
24263             /*type*/ undefined, createBlock(statements, /*multiLine*/ true)), 
24264             /*typeArguments*/ undefined, 
24265             /*argumentsArray*/ paramValue ? [paramValue] : []);
24266         }
24267         function createImmediatelyInvokedArrowFunction(statements, param, paramValue) {
24268             return createCallExpression(createArrowFunction(
24269             /*modifiers*/ undefined, 
24270             /*typeParameters*/ undefined, 
24271             /*parameters*/ param ? [param] : [], 
24272             /*type*/ undefined, 
24273             /*equalsGreaterThanToken*/ undefined, createBlock(statements, /*multiLine*/ true)), 
24274             /*typeArguments*/ undefined, 
24275             /*argumentsArray*/ paramValue ? [paramValue] : []);
24276         }
24277         function createVoidZero() {
24278             return createVoidExpression(createNumericLiteral("0"));
24279         }
24280         function createExportDefault(expression) {
24281             return createExportAssignment(
24282             /*decorators*/ undefined, 
24283             /*modifiers*/ undefined, 
24284             /*isExportEquals*/ false, expression);
24285         }
24286         function createExternalModuleExport(exportName) {
24287             return createExportDeclaration(
24288             /*decorators*/ undefined, 
24289             /*modifiers*/ undefined, 
24290             /*isTypeOnly*/ false, createNamedExports([
24291                 createExportSpecifier(/*propertyName*/ undefined, exportName)
24292             ]));
24293         }
24294         //
24295         // Utilities
24296         //
24297         function createTypeCheck(value, tag) {
24298             return tag === "undefined"
24299                 ? factory.createStrictEquality(value, createVoidZero())
24300                 : factory.createStrictEquality(createTypeOfExpression(value), createStringLiteral(tag));
24301         }
24302         function createMethodCall(object, methodName, argumentsList) {
24303             return createCallExpression(createPropertyAccessExpression(object, methodName), 
24304             /*typeArguments*/ undefined, argumentsList);
24305         }
24306         function createFunctionBindCall(target, thisArg, argumentsList) {
24307             return createMethodCall(target, "bind", __spreadArrays([thisArg], argumentsList));
24308         }
24309         function createFunctionCallCall(target, thisArg, argumentsList) {
24310             return createMethodCall(target, "call", __spreadArrays([thisArg], argumentsList));
24311         }
24312         function createFunctionApplyCall(target, thisArg, argumentsExpression) {
24313             return createMethodCall(target, "apply", [thisArg, argumentsExpression]);
24314         }
24315         function createGlobalMethodCall(globalObjectName, methodName, argumentsList) {
24316             return createMethodCall(createIdentifier(globalObjectName), methodName, argumentsList);
24317         }
24318         function createArraySliceCall(array, start) {
24319             return createMethodCall(array, "slice", start === undefined ? [] : [asExpression(start)]);
24320         }
24321         function createArrayConcatCall(array, argumentsList) {
24322             return createMethodCall(array, "concat", argumentsList);
24323         }
24324         function createObjectDefinePropertyCall(target, propertyName, attributes) {
24325             return createGlobalMethodCall("Object", "defineProperty", [target, asExpression(propertyName), attributes]);
24326         }
24327         function tryAddPropertyAssignment(properties, propertyName, expression) {
24328             if (expression) {
24329                 properties.push(createPropertyAssignment(propertyName, expression));
24330                 return true;
24331             }
24332             return false;
24333         }
24334         function createPropertyDescriptor(attributes, singleLine) {
24335             var properties = [];
24336             tryAddPropertyAssignment(properties, "enumerable", asExpression(attributes.enumerable));
24337             tryAddPropertyAssignment(properties, "configurable", asExpression(attributes.configurable));
24338             var isData = tryAddPropertyAssignment(properties, "writable", asExpression(attributes.writable));
24339             isData = tryAddPropertyAssignment(properties, "value", attributes.value) || isData;
24340             var isAccessor = tryAddPropertyAssignment(properties, "get", attributes.get);
24341             isAccessor = tryAddPropertyAssignment(properties, "set", attributes.set) || isAccessor;
24342             ts.Debug.assert(!(isData && isAccessor), "A PropertyDescriptor may not be both an accessor descriptor and a data descriptor.");
24343             return createObjectLiteralExpression(properties, !singleLine);
24344         }
24345         function updateOuterExpression(outerExpression, expression) {
24346             switch (outerExpression.kind) {
24347                 case 207 /* ParenthesizedExpression */: return updateParenthesizedExpression(outerExpression, expression);
24348                 case 206 /* TypeAssertionExpression */: return updateTypeAssertion(outerExpression, outerExpression.type, expression);
24349                 case 224 /* AsExpression */: return updateAsExpression(outerExpression, expression, outerExpression.type);
24350                 case 225 /* NonNullExpression */: return updateNonNullExpression(outerExpression, expression);
24351                 case 336 /* PartiallyEmittedExpression */: return updatePartiallyEmittedExpression(outerExpression, expression);
24352             }
24353         }
24354         /**
24355          * Determines whether a node is a parenthesized expression that can be ignored when recreating outer expressions.
24356          *
24357          * A parenthesized expression can be ignored when all of the following are true:
24358          *
24359          * - It's `pos` and `end` are not -1
24360          * - It does not have a custom source map range
24361          * - It does not have a custom comment range
24362          * - It does not have synthetic leading or trailing comments
24363          *
24364          * If an outermost parenthesized expression is ignored, but the containing expression requires a parentheses around
24365          * the expression to maintain precedence, a new parenthesized expression should be created automatically when
24366          * the containing expression is created/updated.
24367          */
24368         function isIgnorableParen(node) {
24369             return ts.isParenthesizedExpression(node)
24370                 && ts.nodeIsSynthesized(node)
24371                 && ts.nodeIsSynthesized(ts.getSourceMapRange(node))
24372                 && ts.nodeIsSynthesized(ts.getCommentRange(node))
24373                 && !ts.some(ts.getSyntheticLeadingComments(node))
24374                 && !ts.some(ts.getSyntheticTrailingComments(node));
24375         }
24376         function restoreOuterExpressions(outerExpression, innerExpression, kinds) {
24377             if (kinds === void 0) { kinds = 15 /* All */; }
24378             if (outerExpression && ts.isOuterExpression(outerExpression, kinds) && !isIgnorableParen(outerExpression)) {
24379                 return updateOuterExpression(outerExpression, restoreOuterExpressions(outerExpression.expression, innerExpression));
24380             }
24381             return innerExpression;
24382         }
24383         function restoreEnclosingLabel(node, outermostLabeledStatement, afterRestoreLabelCallback) {
24384             if (!outermostLabeledStatement) {
24385                 return node;
24386             }
24387             var updated = updateLabeledStatement(outermostLabeledStatement, outermostLabeledStatement.label, ts.isLabeledStatement(outermostLabeledStatement.statement)
24388                 ? restoreEnclosingLabel(node, outermostLabeledStatement.statement)
24389                 : node);
24390             if (afterRestoreLabelCallback) {
24391                 afterRestoreLabelCallback(outermostLabeledStatement);
24392             }
24393             return updated;
24394         }
24395         function shouldBeCapturedInTempVariable(node, cacheIdentifiers) {
24396             var target = ts.skipParentheses(node);
24397             switch (target.kind) {
24398                 case 78 /* Identifier */:
24399                     return cacheIdentifiers;
24400                 case 107 /* ThisKeyword */:
24401                 case 8 /* NumericLiteral */:
24402                 case 9 /* BigIntLiteral */:
24403                 case 10 /* StringLiteral */:
24404                     return false;
24405                 case 199 /* ArrayLiteralExpression */:
24406                     var elements = target.elements;
24407                     if (elements.length === 0) {
24408                         return false;
24409                     }
24410                     return true;
24411                 case 200 /* ObjectLiteralExpression */:
24412                     return target.properties.length > 0;
24413                 default:
24414                     return true;
24415             }
24416         }
24417         function createCallBinding(expression, recordTempVariable, languageVersion, cacheIdentifiers) {
24418             if (cacheIdentifiers === void 0) { cacheIdentifiers = false; }
24419             var callee = ts.skipOuterExpressions(expression, 15 /* All */);
24420             var thisArg;
24421             var target;
24422             if (ts.isSuperProperty(callee)) {
24423                 thisArg = createThis();
24424                 target = callee;
24425             }
24426             else if (ts.isSuperKeyword(callee)) {
24427                 thisArg = createThis();
24428                 target = languageVersion !== undefined && languageVersion < 2 /* ES2015 */
24429                     ? ts.setTextRange(createIdentifier("_super"), callee)
24430                     : callee;
24431             }
24432             else if (ts.getEmitFlags(callee) & 4096 /* HelperName */) {
24433                 thisArg = createVoidZero();
24434                 target = parenthesizerRules().parenthesizeLeftSideOfAccess(callee);
24435             }
24436             else if (ts.isPropertyAccessExpression(callee)) {
24437                 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
24438                     // for `a.b()` target is `(_a = a).b` and thisArg is `_a`
24439                     thisArg = createTempVariable(recordTempVariable);
24440                     target = createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.name);
24441                     ts.setTextRange(target, callee);
24442                 }
24443                 else {
24444                     thisArg = callee.expression;
24445                     target = callee;
24446                 }
24447             }
24448             else if (ts.isElementAccessExpression(callee)) {
24449                 if (shouldBeCapturedInTempVariable(callee.expression, cacheIdentifiers)) {
24450                     // for `a[b]()` target is `(_a = a)[b]` and thisArg is `_a`
24451                     thisArg = createTempVariable(recordTempVariable);
24452                     target = createElementAccessExpression(ts.setTextRange(factory.createAssignment(thisArg, callee.expression), callee.expression), callee.argumentExpression);
24453                     ts.setTextRange(target, callee);
24454                 }
24455                 else {
24456                     thisArg = callee.expression;
24457                     target = callee;
24458                 }
24459             }
24460             else {
24461                 // for `a()` target is `a` and thisArg is `void 0`
24462                 thisArg = createVoidZero();
24463                 target = parenthesizerRules().parenthesizeLeftSideOfAccess(expression);
24464             }
24465             return { target: target, thisArg: thisArg };
24466         }
24467         function inlineExpressions(expressions) {
24468             // Avoid deeply nested comma expressions as traversing them during emit can result in "Maximum call
24469             // stack size exceeded" errors.
24470             return expressions.length > 10
24471                 ? createCommaListExpression(expressions)
24472                 : ts.reduceLeft(expressions, factory.createComma);
24473         }
24474         function getName(node, allowComments, allowSourceMaps, emitFlags) {
24475             if (emitFlags === void 0) { emitFlags = 0; }
24476             var nodeName = ts.getNameOfDeclaration(node);
24477             if (nodeName && ts.isIdentifier(nodeName) && !ts.isGeneratedIdentifier(nodeName)) {
24478                 // TODO(rbuckton): Does this need to be parented?
24479                 var name = ts.setParent(ts.setTextRange(cloneNode(nodeName), nodeName), nodeName.parent);
24480                 emitFlags |= ts.getEmitFlags(nodeName);
24481                 if (!allowSourceMaps)
24482                     emitFlags |= 48 /* NoSourceMap */;
24483                 if (!allowComments)
24484                     emitFlags |= 1536 /* NoComments */;
24485                 if (emitFlags)
24486                     ts.setEmitFlags(name, emitFlags);
24487                 return name;
24488             }
24489             return getGeneratedNameForNode(node);
24490         }
24491         /**
24492          * Gets the internal name of a declaration. This is primarily used for declarations that can be
24493          * referred to by name in the body of an ES5 class function body. An internal name will *never*
24494          * be prefixed with an module or namespace export modifier like "exports." when emitted as an
24495          * expression. An internal name will also *never* be renamed due to a collision with a block
24496          * scoped variable.
24497          *
24498          * @param node The declaration.
24499          * @param allowComments A value indicating whether comments may be emitted for the name.
24500          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24501          */
24502         function getInternalName(node, allowComments, allowSourceMaps) {
24503             return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */ | 32768 /* InternalName */);
24504         }
24505         /**
24506          * Gets the local name of a declaration. This is primarily used for declarations that can be
24507          * referred to by name in the declaration's immediate scope (classes, enums, namespaces). A
24508          * local name will *never* be prefixed with an module or namespace export modifier like
24509          * "exports." when emitted as an expression.
24510          *
24511          * @param node The declaration.
24512          * @param allowComments A value indicating whether comments may be emitted for the name.
24513          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24514          */
24515         function getLocalName(node, allowComments, allowSourceMaps) {
24516             return getName(node, allowComments, allowSourceMaps, 16384 /* LocalName */);
24517         }
24518         /**
24519          * Gets the export name of a declaration. This is primarily used for declarations that can be
24520          * referred to by name in the declaration's immediate scope (classes, enums, namespaces). An
24521          * export name will *always* be prefixed with an module or namespace export modifier like
24522          * `"exports."` when emitted as an expression if the name points to an exported symbol.
24523          *
24524          * @param node The declaration.
24525          * @param allowComments A value indicating whether comments may be emitted for the name.
24526          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24527          */
24528         function getExportName(node, allowComments, allowSourceMaps) {
24529             return getName(node, allowComments, allowSourceMaps, 8192 /* ExportName */);
24530         }
24531         /**
24532          * Gets the name of a declaration for use in declarations.
24533          *
24534          * @param node The declaration.
24535          * @param allowComments A value indicating whether comments may be emitted for the name.
24536          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24537          */
24538         function getDeclarationName(node, allowComments, allowSourceMaps) {
24539             return getName(node, allowComments, allowSourceMaps);
24540         }
24541         /**
24542          * Gets a namespace-qualified name for use in expressions.
24543          *
24544          * @param ns The namespace identifier.
24545          * @param name The name.
24546          * @param allowComments A value indicating whether comments may be emitted for the name.
24547          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24548          */
24549         function getNamespaceMemberName(ns, name, allowComments, allowSourceMaps) {
24550             var qualifiedName = createPropertyAccessExpression(ns, ts.nodeIsSynthesized(name) ? name : cloneNode(name));
24551             ts.setTextRange(qualifiedName, name);
24552             var emitFlags = 0;
24553             if (!allowSourceMaps)
24554                 emitFlags |= 48 /* NoSourceMap */;
24555             if (!allowComments)
24556                 emitFlags |= 1536 /* NoComments */;
24557             if (emitFlags)
24558                 ts.setEmitFlags(qualifiedName, emitFlags);
24559             return qualifiedName;
24560         }
24561         /**
24562          * Gets the exported name of a declaration for use in expressions.
24563          *
24564          * An exported name will *always* be prefixed with an module or namespace export modifier like
24565          * "exports." if the name points to an exported symbol.
24566          *
24567          * @param ns The namespace identifier.
24568          * @param node The declaration.
24569          * @param allowComments A value indicating whether comments may be emitted for the name.
24570          * @param allowSourceMaps A value indicating whether source maps may be emitted for the name.
24571          */
24572         function getExternalModuleOrNamespaceExportName(ns, node, allowComments, allowSourceMaps) {
24573             if (ns && ts.hasSyntacticModifier(node, 1 /* Export */)) {
24574                 return getNamespaceMemberName(ns, getName(node), allowComments, allowSourceMaps);
24575             }
24576             return getExportName(node, allowComments, allowSourceMaps);
24577         }
24578         /**
24579          * Copies any necessary standard and custom prologue-directives into target array.
24580          * @param source origin statements array
24581          * @param target result statements array
24582          * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
24583          * @param visitor Optional callback used to visit any custom prologue directives.
24584          */
24585         function copyPrologue(source, target, ensureUseStrict, visitor) {
24586             var offset = copyStandardPrologue(source, target, ensureUseStrict);
24587             return copyCustomPrologue(source, target, offset, visitor);
24588         }
24589         function isUseStrictPrologue(node) {
24590             return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
24591         }
24592         function createUseStrictPrologue() {
24593             return ts.startOnNewLine(createExpressionStatement(createStringLiteral("use strict")));
24594         }
24595         /**
24596          * Copies only the standard (string-expression) prologue-directives into the target statement-array.
24597          * @param source origin statements array
24598          * @param target result statements array
24599          * @param ensureUseStrict boolean determining whether the function need to add prologue-directives
24600          */
24601         function copyStandardPrologue(source, target, ensureUseStrict) {
24602             ts.Debug.assert(target.length === 0, "Prologue directives should be at the first statement in the target statements array");
24603             var foundUseStrict = false;
24604             var statementOffset = 0;
24605             var numStatements = source.length;
24606             while (statementOffset < numStatements) {
24607                 var statement = source[statementOffset];
24608                 if (ts.isPrologueDirective(statement)) {
24609                     if (isUseStrictPrologue(statement)) {
24610                         foundUseStrict = true;
24611                     }
24612                     target.push(statement);
24613                 }
24614                 else {
24615                     break;
24616                 }
24617                 statementOffset++;
24618             }
24619             if (ensureUseStrict && !foundUseStrict) {
24620                 target.push(createUseStrictPrologue());
24621             }
24622             return statementOffset;
24623         }
24624         function copyCustomPrologue(source, target, statementOffset, visitor, filter) {
24625             if (filter === void 0) { filter = ts.returnTrue; }
24626             var numStatements = source.length;
24627             while (statementOffset !== undefined && statementOffset < numStatements) {
24628                 var statement = source[statementOffset];
24629                 if (ts.getEmitFlags(statement) & 1048576 /* CustomPrologue */ && filter(statement)) {
24630                     ts.append(target, visitor ? ts.visitNode(statement, visitor, ts.isStatement) : statement);
24631                 }
24632                 else {
24633                     break;
24634                 }
24635                 statementOffset++;
24636             }
24637             return statementOffset;
24638         }
24639         /**
24640          * Ensures "use strict" directive is added
24641          *
24642          * @param statements An array of statements
24643          */
24644         function ensureUseStrict(statements) {
24645             var foundUseStrict = ts.findUseStrictPrologue(statements);
24646             if (!foundUseStrict) {
24647                 return ts.setTextRange(createNodeArray(__spreadArrays([createUseStrictPrologue()], statements)), statements);
24648             }
24649             return statements;
24650         }
24651         /**
24652          * Lifts a NodeArray containing only Statement nodes to a block.
24653          *
24654          * @param nodes The NodeArray.
24655          */
24656         function liftToBlock(nodes) {
24657             ts.Debug.assert(ts.every(nodes, ts.isStatementOrBlock), "Cannot lift nodes to a Block.");
24658             return ts.singleOrUndefined(nodes) || createBlock(nodes);
24659         }
24660         function findSpanEnd(array, test, start) {
24661             var i = start;
24662             while (i < array.length && test(array[i])) {
24663                 i++;
24664             }
24665             return i;
24666         }
24667         function mergeLexicalEnvironment(statements, declarations) {
24668             if (!ts.some(declarations)) {
24669                 return statements;
24670             }
24671             // When we merge new lexical statements into an existing statement list, we merge them in the following manner:
24672             //
24673             // Given:
24674             //
24675             // | Left                               | Right                               |
24676             // |------------------------------------|-------------------------------------|
24677             // | [standard prologues (left)]        | [standard prologues (right)]        |
24678             // | [hoisted functions (left)]         | [hoisted functions (right)]         |
24679             // | [hoisted variables (left)]         | [hoisted variables (right)]         |
24680             // | [lexical init statements (left)]   | [lexical init statements (right)]   |
24681             // | [other statements (left)]          |                                     |
24682             //
24683             // The resulting statement list will be:
24684             //
24685             // | Result                              |
24686             // |-------------------------------------|
24687             // | [standard prologues (right)]        |
24688             // | [standard prologues (left)]         |
24689             // | [hoisted functions (right)]         |
24690             // | [hoisted functions (left)]          |
24691             // | [hoisted variables (right)]         |
24692             // | [hoisted variables (left)]          |
24693             // | [lexical init statements (right)]   |
24694             // | [lexical init statements (left)]    |
24695             // | [other statements (left)]           |
24696             //
24697             // NOTE: It is expected that new lexical init statements must be evaluated before existing lexical init statements,
24698             // as the prior transformation may depend on the evaluation of the lexical init statements to be in the correct state.
24699             // find standard prologues on left in the following order: standard directives, hoisted functions, hoisted variables, other custom
24700             var leftStandardPrologueEnd = findSpanEnd(statements, ts.isPrologueDirective, 0);
24701             var leftHoistedFunctionsEnd = findSpanEnd(statements, ts.isHoistedFunction, leftStandardPrologueEnd);
24702             var leftHoistedVariablesEnd = findSpanEnd(statements, ts.isHoistedVariableStatement, leftHoistedFunctionsEnd);
24703             // find standard prologues on right in the following order: standard directives, hoisted functions, hoisted variables, other custom
24704             var rightStandardPrologueEnd = findSpanEnd(declarations, ts.isPrologueDirective, 0);
24705             var rightHoistedFunctionsEnd = findSpanEnd(declarations, ts.isHoistedFunction, rightStandardPrologueEnd);
24706             var rightHoistedVariablesEnd = findSpanEnd(declarations, ts.isHoistedVariableStatement, rightHoistedFunctionsEnd);
24707             var rightCustomPrologueEnd = findSpanEnd(declarations, ts.isCustomPrologue, rightHoistedVariablesEnd);
24708             ts.Debug.assert(rightCustomPrologueEnd === declarations.length, "Expected declarations to be valid standard or custom prologues");
24709             // splice prologues from the right into the left. We do this in reverse order
24710             // so that we don't need to recompute the index on the left when we insert items.
24711             var left = ts.isNodeArray(statements) ? statements.slice() : statements;
24712             // splice other custom prologues from right into left
24713             if (rightCustomPrologueEnd > rightHoistedVariablesEnd) {
24714                 left.splice.apply(left, __spreadArrays([leftHoistedVariablesEnd, 0], declarations.slice(rightHoistedVariablesEnd, rightCustomPrologueEnd)));
24715             }
24716             // splice hoisted variables from right into left
24717             if (rightHoistedVariablesEnd > rightHoistedFunctionsEnd) {
24718                 left.splice.apply(left, __spreadArrays([leftHoistedFunctionsEnd, 0], declarations.slice(rightHoistedFunctionsEnd, rightHoistedVariablesEnd)));
24719             }
24720             // splice hoisted functions from right into left
24721             if (rightHoistedFunctionsEnd > rightStandardPrologueEnd) {
24722                 left.splice.apply(left, __spreadArrays([leftStandardPrologueEnd, 0], declarations.slice(rightStandardPrologueEnd, rightHoistedFunctionsEnd)));
24723             }
24724             // splice standard prologues from right into left (that are not already in left)
24725             if (rightStandardPrologueEnd > 0) {
24726                 if (leftStandardPrologueEnd === 0) {
24727                     left.splice.apply(left, __spreadArrays([0, 0], declarations.slice(0, rightStandardPrologueEnd)));
24728                 }
24729                 else {
24730                     var leftPrologues = new ts.Map();
24731                     for (var i = 0; i < leftStandardPrologueEnd; i++) {
24732                         var leftPrologue = statements[i];
24733                         leftPrologues.set(leftPrologue.expression.text, true);
24734                     }
24735                     for (var i = rightStandardPrologueEnd - 1; i >= 0; i--) {
24736                         var rightPrologue = declarations[i];
24737                         if (!leftPrologues.has(rightPrologue.expression.text)) {
24738                             left.unshift(rightPrologue);
24739                         }
24740                     }
24741                 }
24742             }
24743             if (ts.isNodeArray(statements)) {
24744                 return ts.setTextRange(createNodeArray(left, statements.hasTrailingComma), statements);
24745             }
24746             return statements;
24747         }
24748         function updateModifiers(node, modifiers) {
24749             var _a;
24750             if (typeof modifiers === "number") {
24751                 modifiers = createModifiersFromModifierFlags(modifiers);
24752             }
24753             return ts.isParameter(node) ? updateParameterDeclaration(node, node.decorators, modifiers, node.dotDotDotToken, node.name, node.questionToken, node.type, node.initializer) :
24754                 ts.isPropertySignature(node) ? updatePropertySignature(node, modifiers, node.name, node.questionToken, node.type) :
24755                     ts.isPropertyDeclaration(node) ? updatePropertyDeclaration(node, node.decorators, modifiers, node.name, (_a = node.questionToken) !== null && _a !== void 0 ? _a : node.exclamationToken, node.type, node.initializer) :
24756                         ts.isMethodSignature(node) ? updateMethodSignature(node, modifiers, node.name, node.questionToken, node.typeParameters, node.parameters, node.type) :
24757                             ts.isMethodDeclaration(node) ? updateMethodDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.questionToken, node.typeParameters, node.parameters, node.type, node.body) :
24758                                 ts.isConstructorDeclaration(node) ? updateConstructorDeclaration(node, node.decorators, modifiers, node.parameters, node.body) :
24759                                     ts.isGetAccessorDeclaration(node) ? updateGetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.type, node.body) :
24760                                         ts.isSetAccessorDeclaration(node) ? updateSetAccessorDeclaration(node, node.decorators, modifiers, node.name, node.parameters, node.body) :
24761                                             ts.isIndexSignatureDeclaration(node) ? updateIndexSignature(node, node.decorators, modifiers, node.parameters, node.type) :
24762                                                 ts.isFunctionExpression(node) ? updateFunctionExpression(node, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
24763                                                     ts.isArrowFunction(node) ? updateArrowFunction(node, modifiers, node.typeParameters, node.parameters, node.type, node.equalsGreaterThanToken, node.body) :
24764                                                         ts.isClassExpression(node) ? updateClassExpression(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
24765                                                             ts.isVariableStatement(node) ? updateVariableStatement(node, modifiers, node.declarationList) :
24766                                                                 ts.isFunctionDeclaration(node) ? updateFunctionDeclaration(node, node.decorators, modifiers, node.asteriskToken, node.name, node.typeParameters, node.parameters, node.type, node.body) :
24767                                                                     ts.isClassDeclaration(node) ? updateClassDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
24768                                                                         ts.isInterfaceDeclaration(node) ? updateInterfaceDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.heritageClauses, node.members) :
24769                                                                             ts.isTypeAliasDeclaration(node) ? updateTypeAliasDeclaration(node, node.decorators, modifiers, node.name, node.typeParameters, node.type) :
24770                                                                                 ts.isEnumDeclaration(node) ? updateEnumDeclaration(node, node.decorators, modifiers, node.name, node.members) :
24771                                                                                     ts.isModuleDeclaration(node) ? updateModuleDeclaration(node, node.decorators, modifiers, node.name, node.body) :
24772                                                                                         ts.isImportEqualsDeclaration(node) ? updateImportEqualsDeclaration(node, node.decorators, modifiers, node.name, node.moduleReference) :
24773                                                                                             ts.isImportDeclaration(node) ? updateImportDeclaration(node, node.decorators, modifiers, node.importClause, node.moduleSpecifier) :
24774                                                                                                 ts.isExportAssignment(node) ? updateExportAssignment(node, node.decorators, modifiers, node.expression) :
24775                                                                                                     ts.isExportDeclaration(node) ? updateExportDeclaration(node, node.decorators, modifiers, node.isTypeOnly, node.exportClause, node.moduleSpecifier) :
24776                                                                                                         ts.Debug.assertNever(node);
24777         }
24778         function asNodeArray(array) {
24779             return array ? createNodeArray(array) : undefined;
24780         }
24781         function asName(name) {
24782             return typeof name === "string" ? createIdentifier(name) :
24783                 name;
24784         }
24785         function asExpression(value) {
24786             return typeof value === "string" ? createStringLiteral(value) :
24787                 typeof value === "number" ? createNumericLiteral(value) :
24788                     typeof value === "boolean" ? value ? createTrue() : createFalse() :
24789                         value;
24790         }
24791         function asToken(value) {
24792             return typeof value === "number" ? createToken(value) : value;
24793         }
24794         function asEmbeddedStatement(statement) {
24795             return statement && ts.isNotEmittedStatement(statement) ? ts.setTextRange(setOriginalNode(createEmptyStatement(), statement), statement) : statement;
24796         }
24797     }
24798     ts.createNodeFactory = createNodeFactory;
24799     function updateWithoutOriginal(updated, original) {
24800         if (updated !== original) {
24801             ts.setTextRange(updated, original);
24802         }
24803         return updated;
24804     }
24805     function updateWithOriginal(updated, original) {
24806         if (updated !== original) {
24807             setOriginalNode(updated, original);
24808             ts.setTextRange(updated, original);
24809         }
24810         return updated;
24811     }
24812     function getDefaultTagNameForKind(kind) {
24813         switch (kind) {
24814             case 329 /* JSDocTypeTag */: return "type";
24815             case 327 /* JSDocReturnTag */: return "returns";
24816             case 328 /* JSDocThisTag */: return "this";
24817             case 325 /* JSDocEnumTag */: return "enum";
24818             case 317 /* JSDocAuthorTag */: return "author";
24819             case 319 /* JSDocClassTag */: return "class";
24820             case 320 /* JSDocPublicTag */: return "public";
24821             case 321 /* JSDocPrivateTag */: return "private";
24822             case 322 /* JSDocProtectedTag */: return "protected";
24823             case 323 /* JSDocReadonlyTag */: return "readonly";
24824             case 330 /* JSDocTemplateTag */: return "template";
24825             case 331 /* JSDocTypedefTag */: return "typedef";
24826             case 326 /* JSDocParameterTag */: return "param";
24827             case 333 /* JSDocPropertyTag */: return "prop";
24828             case 324 /* JSDocCallbackTag */: return "callback";
24829             case 315 /* JSDocAugmentsTag */: return "augments";
24830             case 316 /* JSDocImplementsTag */: return "implements";
24831             default:
24832                 return ts.Debug.fail("Unsupported kind: " + ts.Debug.formatSyntaxKind(kind));
24833         }
24834     }
24835     var rawTextScanner;
24836     var invalidValueSentinel = {};
24837     function getCookedText(kind, rawText) {
24838         if (!rawTextScanner) {
24839             rawTextScanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ false, 0 /* Standard */);
24840         }
24841         switch (kind) {
24842             case 14 /* NoSubstitutionTemplateLiteral */:
24843                 rawTextScanner.setText("`" + rawText + "`");
24844                 break;
24845             case 15 /* TemplateHead */:
24846                 // tslint:disable-next-line no-invalid-template-strings
24847                 rawTextScanner.setText("`" + rawText + "${");
24848                 break;
24849             case 16 /* TemplateMiddle */:
24850                 // tslint:disable-next-line no-invalid-template-strings
24851                 rawTextScanner.setText("}" + rawText + "${");
24852                 break;
24853             case 17 /* TemplateTail */:
24854                 rawTextScanner.setText("}" + rawText + "`");
24855                 break;
24856         }
24857         var token = rawTextScanner.scan();
24858         if (token === 23 /* CloseBracketToken */) {
24859             token = rawTextScanner.reScanTemplateToken(/*isTaggedTemplate*/ false);
24860         }
24861         if (rawTextScanner.isUnterminated()) {
24862             rawTextScanner.setText(undefined);
24863             return invalidValueSentinel;
24864         }
24865         var tokenValue;
24866         switch (token) {
24867             case 14 /* NoSubstitutionTemplateLiteral */:
24868             case 15 /* TemplateHead */:
24869             case 16 /* TemplateMiddle */:
24870             case 17 /* TemplateTail */:
24871                 tokenValue = rawTextScanner.getTokenValue();
24872                 break;
24873         }
24874         if (tokenValue === undefined || rawTextScanner.scan() !== 1 /* EndOfFileToken */) {
24875             rawTextScanner.setText(undefined);
24876             return invalidValueSentinel;
24877         }
24878         rawTextScanner.setText(undefined);
24879         return tokenValue;
24880     }
24881     function propagateIdentifierNameFlags(node) {
24882         // An IdentifierName is allowed to be `await`
24883         return propagateChildFlags(node) & ~8388608 /* ContainsPossibleTopLevelAwait */;
24884     }
24885     function propagatePropertyNameFlagsOfChild(node, transformFlags) {
24886         return transformFlags | (node.transformFlags & 4096 /* PropertyNamePropagatingFlags */);
24887     }
24888     function propagateChildFlags(child) {
24889         if (!child)
24890             return 0 /* None */;
24891         var childFlags = child.transformFlags & ~getTransformFlagsSubtreeExclusions(child.kind);
24892         return ts.isNamedDeclaration(child) && ts.isPropertyName(child.name) ? propagatePropertyNameFlagsOfChild(child.name, childFlags) : childFlags;
24893     }
24894     function propagateChildrenFlags(children) {
24895         return children ? children.transformFlags : 0 /* None */;
24896     }
24897     function aggregateChildrenFlags(children) {
24898         var subtreeFlags = 0 /* None */;
24899         for (var _i = 0, children_2 = children; _i < children_2.length; _i++) {
24900             var child = children_2[_i];
24901             subtreeFlags |= propagateChildFlags(child);
24902         }
24903         children.transformFlags = subtreeFlags;
24904     }
24905     /**
24906      * Gets the transform flags to exclude when unioning the transform flags of a subtree.
24907      */
24908     /* @internal */
24909     function getTransformFlagsSubtreeExclusions(kind) {
24910         if (kind >= 172 /* FirstTypeNode */ && kind <= 195 /* LastTypeNode */) {
24911             return -2 /* TypeExcludes */;
24912         }
24913         switch (kind) {
24914             case 203 /* CallExpression */:
24915             case 204 /* NewExpression */:
24916             case 199 /* ArrayLiteralExpression */:
24917                 return 536879104 /* ArrayLiteralOrCallOrNewExcludes */;
24918             case 256 /* ModuleDeclaration */:
24919                 return 546379776 /* ModuleExcludes */;
24920             case 160 /* Parameter */:
24921                 return 536870912 /* ParameterExcludes */;
24922             case 209 /* ArrowFunction */:
24923                 return 547309568 /* ArrowFunctionExcludes */;
24924             case 208 /* FunctionExpression */:
24925             case 251 /* FunctionDeclaration */:
24926                 return 547313664 /* FunctionExcludes */;
24927             case 250 /* VariableDeclarationList */:
24928                 return 537018368 /* VariableDeclarationListExcludes */;
24929             case 252 /* ClassDeclaration */:
24930             case 221 /* ClassExpression */:
24931                 return 536905728 /* ClassExcludes */;
24932             case 166 /* Constructor */:
24933                 return 547311616 /* ConstructorExcludes */;
24934             case 163 /* PropertyDeclaration */:
24935                 return 536875008 /* PropertyExcludes */;
24936             case 165 /* MethodDeclaration */:
24937             case 167 /* GetAccessor */:
24938             case 168 /* SetAccessor */:
24939                 return 538923008 /* MethodOrAccessorExcludes */;
24940             case 128 /* AnyKeyword */:
24941             case 144 /* NumberKeyword */:
24942             case 155 /* BigIntKeyword */:
24943             case 141 /* NeverKeyword */:
24944             case 147 /* StringKeyword */:
24945             case 145 /* ObjectKeyword */:
24946             case 131 /* BooleanKeyword */:
24947             case 148 /* SymbolKeyword */:
24948             case 113 /* VoidKeyword */:
24949             case 159 /* TypeParameter */:
24950             case 162 /* PropertySignature */:
24951             case 164 /* MethodSignature */:
24952             case 169 /* CallSignature */:
24953             case 170 /* ConstructSignature */:
24954             case 171 /* IndexSignature */:
24955             case 253 /* InterfaceDeclaration */:
24956             case 254 /* TypeAliasDeclaration */:
24957                 return -2 /* TypeExcludes */;
24958             case 200 /* ObjectLiteralExpression */:
24959                 return 536922112 /* ObjectLiteralExcludes */;
24960             case 287 /* CatchClause */:
24961                 return 536887296 /* CatchClauseExcludes */;
24962             case 196 /* ObjectBindingPattern */:
24963             case 197 /* ArrayBindingPattern */:
24964                 return 536879104 /* BindingPatternExcludes */;
24965             case 206 /* TypeAssertionExpression */:
24966             case 224 /* AsExpression */:
24967             case 336 /* PartiallyEmittedExpression */:
24968             case 207 /* ParenthesizedExpression */:
24969             case 105 /* SuperKeyword */:
24970                 return 536870912 /* OuterExpressionExcludes */;
24971             case 201 /* PropertyAccessExpression */:
24972             case 202 /* ElementAccessExpression */:
24973                 return 536870912 /* PropertyAccessExcludes */;
24974             default:
24975                 return 536870912 /* NodeExcludes */;
24976         }
24977     }
24978     ts.getTransformFlagsSubtreeExclusions = getTransformFlagsSubtreeExclusions;
24979     var baseFactory = ts.createBaseNodeFactory();
24980     function makeSynthetic(node) {
24981         node.flags |= 8 /* Synthesized */;
24982         return node;
24983     }
24984     var syntheticFactory = {
24985         createBaseSourceFileNode: function (kind) { return makeSynthetic(baseFactory.createBaseSourceFileNode(kind)); },
24986         createBaseIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBaseIdentifierNode(kind)); },
24987         createBasePrivateIdentifierNode: function (kind) { return makeSynthetic(baseFactory.createBasePrivateIdentifierNode(kind)); },
24988         createBaseTokenNode: function (kind) { return makeSynthetic(baseFactory.createBaseTokenNode(kind)); },
24989         createBaseNode: function (kind) { return makeSynthetic(baseFactory.createBaseNode(kind)); },
24990     };
24991     ts.factory = createNodeFactory(4 /* NoIndentationOnFreshPropertyAccess */, syntheticFactory);
24992     function createUnparsedSourceFile(textOrInputFiles, mapPathOrType, mapTextOrStripInternal) {
24993         var stripInternal;
24994         var bundleFileInfo;
24995         var fileName;
24996         var text;
24997         var length;
24998         var sourceMapPath;
24999         var sourceMapText;
25000         var getText;
25001         var getSourceMapText;
25002         var oldFileOfCurrentEmit;
25003         if (!ts.isString(textOrInputFiles)) {
25004             ts.Debug.assert(mapPathOrType === "js" || mapPathOrType === "dts");
25005             fileName = (mapPathOrType === "js" ? textOrInputFiles.javascriptPath : textOrInputFiles.declarationPath) || "";
25006             sourceMapPath = mapPathOrType === "js" ? textOrInputFiles.javascriptMapPath : textOrInputFiles.declarationMapPath;
25007             getText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptText : textOrInputFiles.declarationText; };
25008             getSourceMapText = function () { return mapPathOrType === "js" ? textOrInputFiles.javascriptMapText : textOrInputFiles.declarationMapText; };
25009             length = function () { return getText().length; };
25010             if (textOrInputFiles.buildInfo && textOrInputFiles.buildInfo.bundle) {
25011                 ts.Debug.assert(mapTextOrStripInternal === undefined || typeof mapTextOrStripInternal === "boolean");
25012                 stripInternal = mapTextOrStripInternal;
25013                 bundleFileInfo = mapPathOrType === "js" ? textOrInputFiles.buildInfo.bundle.js : textOrInputFiles.buildInfo.bundle.dts;
25014                 oldFileOfCurrentEmit = textOrInputFiles.oldFileOfCurrentEmit;
25015             }
25016         }
25017         else {
25018             fileName = "";
25019             text = textOrInputFiles;
25020             length = textOrInputFiles.length;
25021             sourceMapPath = mapPathOrType;
25022             sourceMapText = mapTextOrStripInternal;
25023         }
25024         var node = oldFileOfCurrentEmit ?
25025             parseOldFileOfCurrentEmit(ts.Debug.assertDefined(bundleFileInfo)) :
25026             parseUnparsedSourceFile(bundleFileInfo, stripInternal, length);
25027         node.fileName = fileName;
25028         node.sourceMapPath = sourceMapPath;
25029         node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
25030         if (getText && getSourceMapText) {
25031             Object.defineProperty(node, "text", { get: getText });
25032             Object.defineProperty(node, "sourceMapText", { get: getSourceMapText });
25033         }
25034         else {
25035             ts.Debug.assert(!oldFileOfCurrentEmit);
25036             node.text = text !== null && text !== void 0 ? text : "";
25037             node.sourceMapText = sourceMapText;
25038         }
25039         return node;
25040     }
25041     ts.createUnparsedSourceFile = createUnparsedSourceFile;
25042     function parseUnparsedSourceFile(bundleFileInfo, stripInternal, length) {
25043         var prologues;
25044         var helpers;
25045         var referencedFiles;
25046         var typeReferenceDirectives;
25047         var libReferenceDirectives;
25048         var prependChildren;
25049         var texts;
25050         var hasNoDefaultLib;
25051         for (var _i = 0, _a = bundleFileInfo ? bundleFileInfo.sections : ts.emptyArray; _i < _a.length; _i++) {
25052             var section = _a[_i];
25053             switch (section.kind) {
25054                 case "prologue" /* Prologue */:
25055                     prologues = ts.append(prologues, ts.setTextRange(ts.factory.createUnparsedPrologue(section.data), section));
25056                     break;
25057                 case "emitHelpers" /* EmitHelpers */:
25058                     helpers = ts.append(helpers, ts.getAllUnscopedEmitHelpers().get(section.data));
25059                     break;
25060                 case "no-default-lib" /* NoDefaultLib */:
25061                     hasNoDefaultLib = true;
25062                     break;
25063                 case "reference" /* Reference */:
25064                     referencedFiles = ts.append(referencedFiles, { pos: -1, end: -1, fileName: section.data });
25065                     break;
25066                 case "type" /* Type */:
25067                     typeReferenceDirectives = ts.append(typeReferenceDirectives, section.data);
25068                     break;
25069                 case "lib" /* Lib */:
25070                     libReferenceDirectives = ts.append(libReferenceDirectives, { pos: -1, end: -1, fileName: section.data });
25071                     break;
25072                 case "prepend" /* Prepend */:
25073                     var prependTexts = void 0;
25074                     for (var _b = 0, _c = section.texts; _b < _c.length; _b++) {
25075                         var text = _c[_b];
25076                         if (!stripInternal || text.kind !== "internal" /* Internal */) {
25077                             prependTexts = ts.append(prependTexts, ts.setTextRange(ts.factory.createUnparsedTextLike(text.data, text.kind === "internal" /* Internal */), text));
25078                         }
25079                     }
25080                     prependChildren = ts.addRange(prependChildren, prependTexts);
25081                     texts = ts.append(texts, ts.factory.createUnparsedPrepend(section.data, prependTexts !== null && prependTexts !== void 0 ? prependTexts : ts.emptyArray));
25082                     break;
25083                 case "internal" /* Internal */:
25084                     if (stripInternal) {
25085                         if (!texts)
25086                             texts = [];
25087                         break;
25088                     }
25089                 // falls through
25090                 case "text" /* Text */:
25091                     texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
25092                     break;
25093                 default:
25094                     ts.Debug.assertNever(section);
25095             }
25096         }
25097         if (!texts) {
25098             var textNode = ts.factory.createUnparsedTextLike(/*data*/ undefined, /*internal*/ false);
25099             ts.setTextRangePosWidth(textNode, 0, typeof length === "function" ? length() : length);
25100             texts = [textNode];
25101         }
25102         var node = ts.parseNodeFactory.createUnparsedSource(prologues !== null && prologues !== void 0 ? prologues : ts.emptyArray, /*syntheticReferences*/ undefined, texts);
25103         ts.setEachParent(prologues, node);
25104         ts.setEachParent(texts, node);
25105         ts.setEachParent(prependChildren, node);
25106         node.hasNoDefaultLib = hasNoDefaultLib;
25107         node.helpers = helpers;
25108         node.referencedFiles = referencedFiles || ts.emptyArray;
25109         node.typeReferenceDirectives = typeReferenceDirectives;
25110         node.libReferenceDirectives = libReferenceDirectives || ts.emptyArray;
25111         return node;
25112     }
25113     function parseOldFileOfCurrentEmit(bundleFileInfo) {
25114         var texts;
25115         var syntheticReferences;
25116         for (var _i = 0, _a = bundleFileInfo.sections; _i < _a.length; _i++) {
25117             var section = _a[_i];
25118             switch (section.kind) {
25119                 case "internal" /* Internal */:
25120                 case "text" /* Text */:
25121                     texts = ts.append(texts, ts.setTextRange(ts.factory.createUnparsedTextLike(section.data, section.kind === "internal" /* Internal */), section));
25122                     break;
25123                 case "no-default-lib" /* NoDefaultLib */:
25124                 case "reference" /* Reference */:
25125                 case "type" /* Type */:
25126                 case "lib" /* Lib */:
25127                     syntheticReferences = ts.append(syntheticReferences, ts.setTextRange(ts.factory.createUnparsedSyntheticReference(section), section));
25128                     break;
25129                 // Ignore
25130                 case "prologue" /* Prologue */:
25131                 case "emitHelpers" /* EmitHelpers */:
25132                 case "prepend" /* Prepend */:
25133                     break;
25134                 default:
25135                     ts.Debug.assertNever(section);
25136             }
25137         }
25138         var node = ts.factory.createUnparsedSource(ts.emptyArray, syntheticReferences, texts !== null && texts !== void 0 ? texts : ts.emptyArray);
25139         ts.setEachParent(syntheticReferences, node);
25140         ts.setEachParent(texts, node);
25141         node.helpers = ts.map(bundleFileInfo.sources && bundleFileInfo.sources.helpers, function (name) { return ts.getAllUnscopedEmitHelpers().get(name); });
25142         return node;
25143     }
25144     function createInputFiles(javascriptTextOrReadFileText, declarationTextOrJavascriptPath, javascriptMapPath, javascriptMapTextOrDeclarationPath, declarationMapPath, declarationMapTextOrBuildInfoPath, javascriptPath, declarationPath, buildInfoPath, buildInfo, oldFileOfCurrentEmit) {
25145         var node = ts.parseNodeFactory.createInputFiles();
25146         if (!ts.isString(javascriptTextOrReadFileText)) {
25147             var cache_1 = new ts.Map();
25148             var textGetter_1 = function (path) {
25149                 if (path === undefined)
25150                     return undefined;
25151                 var value = cache_1.get(path);
25152                 if (value === undefined) {
25153                     value = javascriptTextOrReadFileText(path);
25154                     cache_1.set(path, value !== undefined ? value : false);
25155                 }
25156                 return value !== false ? value : undefined;
25157             };
25158             var definedTextGetter_1 = function (path) {
25159                 var result = textGetter_1(path);
25160                 return result !== undefined ? result : "/* Input file " + path + " was missing */\r\n";
25161             };
25162             var buildInfo_1;
25163             var getAndCacheBuildInfo_1 = function (getText) {
25164                 if (buildInfo_1 === undefined) {
25165                     var result = getText();
25166                     buildInfo_1 = result !== undefined ? ts.getBuildInfo(result) : false;
25167                 }
25168                 return buildInfo_1 || undefined;
25169             };
25170             node.javascriptPath = declarationTextOrJavascriptPath;
25171             node.javascriptMapPath = javascriptMapPath;
25172             node.declarationPath = ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath);
25173             node.declarationMapPath = declarationMapPath;
25174             node.buildInfoPath = declarationMapTextOrBuildInfoPath;
25175             Object.defineProperties(node, {
25176                 javascriptText: { get: function () { return definedTextGetter_1(declarationTextOrJavascriptPath); } },
25177                 javascriptMapText: { get: function () { return textGetter_1(javascriptMapPath); } },
25178                 declarationText: { get: function () { return definedTextGetter_1(ts.Debug.assertDefined(javascriptMapTextOrDeclarationPath)); } },
25179                 declarationMapText: { get: function () { return textGetter_1(declarationMapPath); } },
25180                 buildInfo: { get: function () { return getAndCacheBuildInfo_1(function () { return textGetter_1(declarationMapTextOrBuildInfoPath); }); } }
25181             });
25182         }
25183         else {
25184             node.javascriptText = javascriptTextOrReadFileText;
25185             node.javascriptMapPath = javascriptMapPath;
25186             node.javascriptMapText = javascriptMapTextOrDeclarationPath;
25187             node.declarationText = declarationTextOrJavascriptPath;
25188             node.declarationMapPath = declarationMapPath;
25189             node.declarationMapText = declarationMapTextOrBuildInfoPath;
25190             node.javascriptPath = javascriptPath;
25191             node.declarationPath = declarationPath;
25192             node.buildInfoPath = buildInfoPath;
25193             node.buildInfo = buildInfo;
25194             node.oldFileOfCurrentEmit = oldFileOfCurrentEmit;
25195         }
25196         return node;
25197     }
25198     ts.createInputFiles = createInputFiles;
25199     // tslint:disable-next-line variable-name
25200     var SourceMapSource;
25201     /**
25202      * Create an external source map source file reference
25203      */
25204     function createSourceMapSource(fileName, text, skipTrivia) {
25205         return new (SourceMapSource || (SourceMapSource = ts.objectAllocator.getSourceMapSourceConstructor()))(fileName, text, skipTrivia);
25206     }
25207     ts.createSourceMapSource = createSourceMapSource;
25208     // Utilities
25209     function setOriginalNode(node, original) {
25210         node.original = original;
25211         if (original) {
25212             var emitNode = original.emitNode;
25213             if (emitNode)
25214                 node.emitNode = mergeEmitNode(emitNode, node.emitNode);
25215         }
25216         return node;
25217     }
25218     ts.setOriginalNode = setOriginalNode;
25219     function mergeEmitNode(sourceEmitNode, destEmitNode) {
25220         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;
25221         if (!destEmitNode)
25222             destEmitNode = {};
25223         // We are using `.slice()` here in case `destEmitNode.leadingComments` is pushed to later.
25224         if (leadingComments)
25225             destEmitNode.leadingComments = ts.addRange(leadingComments.slice(), destEmitNode.leadingComments);
25226         if (trailingComments)
25227             destEmitNode.trailingComments = ts.addRange(trailingComments.slice(), destEmitNode.trailingComments);
25228         if (flags)
25229             destEmitNode.flags = flags;
25230         if (commentRange)
25231             destEmitNode.commentRange = commentRange;
25232         if (sourceMapRange)
25233             destEmitNode.sourceMapRange = sourceMapRange;
25234         if (tokenSourceMapRanges)
25235             destEmitNode.tokenSourceMapRanges = mergeTokenSourceMapRanges(tokenSourceMapRanges, destEmitNode.tokenSourceMapRanges);
25236         if (constantValue !== undefined)
25237             destEmitNode.constantValue = constantValue;
25238         if (helpers) {
25239             for (var _i = 0, helpers_1 = helpers; _i < helpers_1.length; _i++) {
25240                 var helper = helpers_1[_i];
25241                 destEmitNode.helpers = ts.appendIfUnique(destEmitNode.helpers, helper);
25242             }
25243         }
25244         if (startsOnNewLine !== undefined)
25245             destEmitNode.startsOnNewLine = startsOnNewLine;
25246         return destEmitNode;
25247     }
25248     function mergeTokenSourceMapRanges(sourceRanges, destRanges) {
25249         if (!destRanges)
25250             destRanges = [];
25251         for (var key in sourceRanges) {
25252             destRanges[key] = sourceRanges[key];
25253         }
25254         return destRanges;
25255     }
25256 })(ts || (ts = {}));
25257 var ts;
25258 (function (ts) {
25259     /**
25260      * Associates a node with the current transformation, initializing
25261      * various transient transformation properties.
25262      * @internal
25263      */
25264     function getOrCreateEmitNode(node) {
25265         var _a;
25266         if (!node.emitNode) {
25267             if (ts.isParseTreeNode(node)) {
25268                 // To avoid holding onto transformation artifacts, we keep track of any
25269                 // parse tree node we are annotating. This allows us to clean them up after
25270                 // all transformations have completed.
25271                 if (node.kind === 297 /* SourceFile */) {
25272                     return node.emitNode = { annotatedNodes: [node] };
25273                 }
25274                 var sourceFile = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(ts.getSourceFileOfNode(node)))) !== null && _a !== void 0 ? _a : ts.Debug.fail("Could not determine parsed source file.");
25275                 getOrCreateEmitNode(sourceFile).annotatedNodes.push(node);
25276             }
25277             node.emitNode = {};
25278         }
25279         return node.emitNode;
25280     }
25281     ts.getOrCreateEmitNode = getOrCreateEmitNode;
25282     /**
25283      * Clears any `EmitNode` entries from parse-tree nodes.
25284      * @param sourceFile A source file.
25285      */
25286     function disposeEmitNodes(sourceFile) {
25287         var _a, _b;
25288         // During transformation we may need to annotate a parse tree node with transient
25289         // transformation properties. As parse tree nodes live longer than transformation
25290         // nodes, we need to make sure we reclaim any memory allocated for custom ranges
25291         // from these nodes to ensure we do not hold onto entire subtrees just for position
25292         // information. We also need to reset these nodes to a pre-transformation state
25293         // for incremental parsing scenarios so that we do not impact later emit.
25294         var annotatedNodes = (_b = (_a = ts.getSourceFileOfNode(ts.getParseTreeNode(sourceFile))) === null || _a === void 0 ? void 0 : _a.emitNode) === null || _b === void 0 ? void 0 : _b.annotatedNodes;
25295         if (annotatedNodes) {
25296             for (var _i = 0, annotatedNodes_1 = annotatedNodes; _i < annotatedNodes_1.length; _i++) {
25297                 var node = annotatedNodes_1[_i];
25298                 node.emitNode = undefined;
25299             }
25300         }
25301     }
25302     ts.disposeEmitNodes = disposeEmitNodes;
25303     /**
25304      * Sets `EmitFlags.NoComments` on a node and removes any leading and trailing synthetic comments.
25305      * @internal
25306      */
25307     function removeAllComments(node) {
25308         var emitNode = getOrCreateEmitNode(node);
25309         emitNode.flags |= 1536 /* NoComments */;
25310         emitNode.leadingComments = undefined;
25311         emitNode.trailingComments = undefined;
25312         return node;
25313     }
25314     ts.removeAllComments = removeAllComments;
25315     /**
25316      * Sets flags that control emit behavior of a node.
25317      */
25318     function setEmitFlags(node, emitFlags) {
25319         getOrCreateEmitNode(node).flags = emitFlags;
25320         return node;
25321     }
25322     ts.setEmitFlags = setEmitFlags;
25323     /**
25324      * Sets flags that control emit behavior of a node.
25325      */
25326     /* @internal */
25327     function addEmitFlags(node, emitFlags) {
25328         var emitNode = getOrCreateEmitNode(node);
25329         emitNode.flags = emitNode.flags | emitFlags;
25330         return node;
25331     }
25332     ts.addEmitFlags = addEmitFlags;
25333     /**
25334      * Gets a custom text range to use when emitting source maps.
25335      */
25336     function getSourceMapRange(node) {
25337         var _a, _b;
25338         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.sourceMapRange) !== null && _b !== void 0 ? _b : node;
25339     }
25340     ts.getSourceMapRange = getSourceMapRange;
25341     /**
25342      * Sets a custom text range to use when emitting source maps.
25343      */
25344     function setSourceMapRange(node, range) {
25345         getOrCreateEmitNode(node).sourceMapRange = range;
25346         return node;
25347     }
25348     ts.setSourceMapRange = setSourceMapRange;
25349     /**
25350      * Gets the TextRange to use for source maps for a token of a node.
25351      */
25352     function getTokenSourceMapRange(node, token) {
25353         var _a, _b;
25354         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.tokenSourceMapRanges) === null || _b === void 0 ? void 0 : _b[token];
25355     }
25356     ts.getTokenSourceMapRange = getTokenSourceMapRange;
25357     /**
25358      * Sets the TextRange to use for source maps for a token of a node.
25359      */
25360     function setTokenSourceMapRange(node, token, range) {
25361         var _a;
25362         var emitNode = getOrCreateEmitNode(node);
25363         var tokenSourceMapRanges = (_a = emitNode.tokenSourceMapRanges) !== null && _a !== void 0 ? _a : (emitNode.tokenSourceMapRanges = []);
25364         tokenSourceMapRanges[token] = range;
25365         return node;
25366     }
25367     ts.setTokenSourceMapRange = setTokenSourceMapRange;
25368     /**
25369      * Gets a custom text range to use when emitting comments.
25370      */
25371     /*@internal*/
25372     function getStartsOnNewLine(node) {
25373         var _a;
25374         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.startsOnNewLine;
25375     }
25376     ts.getStartsOnNewLine = getStartsOnNewLine;
25377     /**
25378      * Sets a custom text range to use when emitting comments.
25379      */
25380     /*@internal*/
25381     function setStartsOnNewLine(node, newLine) {
25382         getOrCreateEmitNode(node).startsOnNewLine = newLine;
25383         return node;
25384     }
25385     ts.setStartsOnNewLine = setStartsOnNewLine;
25386     /**
25387      * Gets a custom text range to use when emitting comments.
25388      */
25389     function getCommentRange(node) {
25390         var _a, _b;
25391         return (_b = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.commentRange) !== null && _b !== void 0 ? _b : node;
25392     }
25393     ts.getCommentRange = getCommentRange;
25394     /**
25395      * Sets a custom text range to use when emitting comments.
25396      */
25397     function setCommentRange(node, range) {
25398         getOrCreateEmitNode(node).commentRange = range;
25399         return node;
25400     }
25401     ts.setCommentRange = setCommentRange;
25402     function getSyntheticLeadingComments(node) {
25403         var _a;
25404         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.leadingComments;
25405     }
25406     ts.getSyntheticLeadingComments = getSyntheticLeadingComments;
25407     function setSyntheticLeadingComments(node, comments) {
25408         getOrCreateEmitNode(node).leadingComments = comments;
25409         return node;
25410     }
25411     ts.setSyntheticLeadingComments = setSyntheticLeadingComments;
25412     function addSyntheticLeadingComment(node, kind, text, hasTrailingNewLine) {
25413         return setSyntheticLeadingComments(node, ts.append(getSyntheticLeadingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
25414     }
25415     ts.addSyntheticLeadingComment = addSyntheticLeadingComment;
25416     function getSyntheticTrailingComments(node) {
25417         var _a;
25418         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.trailingComments;
25419     }
25420     ts.getSyntheticTrailingComments = getSyntheticTrailingComments;
25421     function setSyntheticTrailingComments(node, comments) {
25422         getOrCreateEmitNode(node).trailingComments = comments;
25423         return node;
25424     }
25425     ts.setSyntheticTrailingComments = setSyntheticTrailingComments;
25426     function addSyntheticTrailingComment(node, kind, text, hasTrailingNewLine) {
25427         return setSyntheticTrailingComments(node, ts.append(getSyntheticTrailingComments(node), { kind: kind, pos: -1, end: -1, hasTrailingNewLine: hasTrailingNewLine, text: text }));
25428     }
25429     ts.addSyntheticTrailingComment = addSyntheticTrailingComment;
25430     function moveSyntheticComments(node, original) {
25431         setSyntheticLeadingComments(node, getSyntheticLeadingComments(original));
25432         setSyntheticTrailingComments(node, getSyntheticTrailingComments(original));
25433         var emit = getOrCreateEmitNode(original);
25434         emit.leadingComments = undefined;
25435         emit.trailingComments = undefined;
25436         return node;
25437     }
25438     ts.moveSyntheticComments = moveSyntheticComments;
25439     /**
25440      * Gets the constant value to emit for an expression representing an enum.
25441      */
25442     function getConstantValue(node) {
25443         var _a;
25444         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.constantValue;
25445     }
25446     ts.getConstantValue = getConstantValue;
25447     /**
25448      * Sets the constant value to emit for an expression.
25449      */
25450     function setConstantValue(node, value) {
25451         var emitNode = getOrCreateEmitNode(node);
25452         emitNode.constantValue = value;
25453         return node;
25454     }
25455     ts.setConstantValue = setConstantValue;
25456     /**
25457      * Adds an EmitHelper to a node.
25458      */
25459     function addEmitHelper(node, helper) {
25460         var emitNode = getOrCreateEmitNode(node);
25461         emitNode.helpers = ts.append(emitNode.helpers, helper);
25462         return node;
25463     }
25464     ts.addEmitHelper = addEmitHelper;
25465     /**
25466      * Add EmitHelpers to a node.
25467      */
25468     function addEmitHelpers(node, helpers) {
25469         if (ts.some(helpers)) {
25470             var emitNode = getOrCreateEmitNode(node);
25471             for (var _i = 0, helpers_2 = helpers; _i < helpers_2.length; _i++) {
25472                 var helper = helpers_2[_i];
25473                 emitNode.helpers = ts.appendIfUnique(emitNode.helpers, helper);
25474             }
25475         }
25476         return node;
25477     }
25478     ts.addEmitHelpers = addEmitHelpers;
25479     /**
25480      * Removes an EmitHelper from a node.
25481      */
25482     function removeEmitHelper(node, helper) {
25483         var _a;
25484         var helpers = (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
25485         if (helpers) {
25486             return ts.orderedRemoveItem(helpers, helper);
25487         }
25488         return false;
25489     }
25490     ts.removeEmitHelper = removeEmitHelper;
25491     /**
25492      * Gets the EmitHelpers of a node.
25493      */
25494     function getEmitHelpers(node) {
25495         var _a;
25496         return (_a = node.emitNode) === null || _a === void 0 ? void 0 : _a.helpers;
25497     }
25498     ts.getEmitHelpers = getEmitHelpers;
25499     /**
25500      * Moves matching emit helpers from a source node to a target node.
25501      */
25502     function moveEmitHelpers(source, target, predicate) {
25503         var sourceEmitNode = source.emitNode;
25504         var sourceEmitHelpers = sourceEmitNode && sourceEmitNode.helpers;
25505         if (!ts.some(sourceEmitHelpers))
25506             return;
25507         var targetEmitNode = getOrCreateEmitNode(target);
25508         var helpersRemoved = 0;
25509         for (var i = 0; i < sourceEmitHelpers.length; i++) {
25510             var helper = sourceEmitHelpers[i];
25511             if (predicate(helper)) {
25512                 helpersRemoved++;
25513                 targetEmitNode.helpers = ts.appendIfUnique(targetEmitNode.helpers, helper);
25514             }
25515             else if (helpersRemoved > 0) {
25516                 sourceEmitHelpers[i - helpersRemoved] = helper;
25517             }
25518         }
25519         if (helpersRemoved > 0) {
25520             sourceEmitHelpers.length -= helpersRemoved;
25521         }
25522     }
25523     ts.moveEmitHelpers = moveEmitHelpers;
25524     /* @internal */
25525     function ignoreSourceNewlines(node) {
25526         getOrCreateEmitNode(node).flags |= 134217728 /* IgnoreSourceNewlines */;
25527         return node;
25528     }
25529     ts.ignoreSourceNewlines = ignoreSourceNewlines;
25530 })(ts || (ts = {}));
25531 /* @internal */
25532 var ts;
25533 (function (ts) {
25534     function createEmitHelperFactory(context) {
25535         var factory = context.factory;
25536         return {
25537             getUnscopedHelperName: getUnscopedHelperName,
25538             // TypeScript Helpers
25539             createDecorateHelper: createDecorateHelper,
25540             createMetadataHelper: createMetadataHelper,
25541             createParamHelper: createParamHelper,
25542             // ES2018 Helpers
25543             createAssignHelper: createAssignHelper,
25544             createAwaitHelper: createAwaitHelper,
25545             createAsyncGeneratorHelper: createAsyncGeneratorHelper,
25546             createAsyncDelegatorHelper: createAsyncDelegatorHelper,
25547             createAsyncValuesHelper: createAsyncValuesHelper,
25548             // ES2018 Destructuring Helpers
25549             createRestHelper: createRestHelper,
25550             // ES2017 Helpers
25551             createAwaiterHelper: createAwaiterHelper,
25552             // ES2015 Helpers
25553             createExtendsHelper: createExtendsHelper,
25554             createTemplateObjectHelper: createTemplateObjectHelper,
25555             createSpreadHelper: createSpreadHelper,
25556             createSpreadArraysHelper: createSpreadArraysHelper,
25557             // ES2015 Destructuring Helpers
25558             createValuesHelper: createValuesHelper,
25559             createReadHelper: createReadHelper,
25560             // ES2015 Generator Helpers
25561             createGeneratorHelper: createGeneratorHelper,
25562             // ES Module Helpers
25563             createCreateBindingHelper: createCreateBindingHelper,
25564             createImportStarHelper: createImportStarHelper,
25565             createImportStarCallbackHelper: createImportStarCallbackHelper,
25566             createImportDefaultHelper: createImportDefaultHelper,
25567             createExportStarHelper: createExportStarHelper,
25568             // Class Fields Helpers
25569             createClassPrivateFieldGetHelper: createClassPrivateFieldGetHelper,
25570             createClassPrivateFieldSetHelper: createClassPrivateFieldSetHelper,
25571         };
25572         /**
25573          * Gets an identifier for the name of an *unscoped* emit helper.
25574          */
25575         function getUnscopedHelperName(name) {
25576             return ts.setEmitFlags(factory.createIdentifier(name), 4096 /* HelperName */ | 2 /* AdviseOnEmitNode */);
25577         }
25578         // TypeScript Helpers
25579         function createDecorateHelper(decoratorExpressions, target, memberName, descriptor) {
25580             context.requestEmitHelper(ts.decorateHelper);
25581             var argumentsArray = [];
25582             argumentsArray.push(factory.createArrayLiteralExpression(decoratorExpressions, /*multiLine*/ true));
25583             argumentsArray.push(target);
25584             if (memberName) {
25585                 argumentsArray.push(memberName);
25586                 if (descriptor) {
25587                     argumentsArray.push(descriptor);
25588                 }
25589             }
25590             return factory.createCallExpression(getUnscopedHelperName("__decorate"), 
25591             /*typeArguments*/ undefined, argumentsArray);
25592         }
25593         function createMetadataHelper(metadataKey, metadataValue) {
25594             context.requestEmitHelper(ts.metadataHelper);
25595             return factory.createCallExpression(getUnscopedHelperName("__metadata"), 
25596             /*typeArguments*/ undefined, [
25597                 factory.createStringLiteral(metadataKey),
25598                 metadataValue
25599             ]);
25600         }
25601         function createParamHelper(expression, parameterOffset, location) {
25602             context.requestEmitHelper(ts.paramHelper);
25603             return ts.setTextRange(factory.createCallExpression(getUnscopedHelperName("__param"), 
25604             /*typeArguments*/ undefined, [
25605                 factory.createNumericLiteral(parameterOffset + ""),
25606                 expression
25607             ]), location);
25608         }
25609         // ES2018 Helpers
25610         function createAssignHelper(attributesSegments) {
25611             if (context.getCompilerOptions().target >= 2 /* ES2015 */) {
25612                 return factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "assign"), 
25613                 /*typeArguments*/ undefined, attributesSegments);
25614             }
25615             context.requestEmitHelper(ts.assignHelper);
25616             return factory.createCallExpression(getUnscopedHelperName("__assign"), 
25617             /*typeArguments*/ undefined, attributesSegments);
25618         }
25619         function createAwaitHelper(expression) {
25620             context.requestEmitHelper(ts.awaitHelper);
25621             return factory.createCallExpression(getUnscopedHelperName("__await"), /*typeArguments*/ undefined, [expression]);
25622         }
25623         function createAsyncGeneratorHelper(generatorFunc, hasLexicalThis) {
25624             context.requestEmitHelper(ts.awaitHelper);
25625             context.requestEmitHelper(ts.asyncGeneratorHelper);
25626             // Mark this node as originally an async function
25627             (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
25628             return factory.createCallExpression(getUnscopedHelperName("__asyncGenerator"), 
25629             /*typeArguments*/ undefined, [
25630                 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
25631                 factory.createIdentifier("arguments"),
25632                 generatorFunc
25633             ]);
25634         }
25635         function createAsyncDelegatorHelper(expression) {
25636             context.requestEmitHelper(ts.awaitHelper);
25637             context.requestEmitHelper(ts.asyncDelegator);
25638             return factory.createCallExpression(getUnscopedHelperName("__asyncDelegator"), 
25639             /*typeArguments*/ undefined, [expression]);
25640         }
25641         function createAsyncValuesHelper(expression) {
25642             context.requestEmitHelper(ts.asyncValues);
25643             return factory.createCallExpression(getUnscopedHelperName("__asyncValues"), 
25644             /*typeArguments*/ undefined, [expression]);
25645         }
25646         // ES2018 Destructuring Helpers
25647         /** Given value: o, propName: p, pattern: { a, b, ...p } from the original statement
25648          * `{ a, b, ...p } = o`, create `p = __rest(o, ["a", "b"]);`
25649          */
25650         function createRestHelper(value, elements, computedTempVariables, location) {
25651             context.requestEmitHelper(ts.restHelper);
25652             var propertyNames = [];
25653             var computedTempVariableOffset = 0;
25654             for (var i = 0; i < elements.length - 1; i++) {
25655                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(elements[i]);
25656                 if (propertyName) {
25657                     if (ts.isComputedPropertyName(propertyName)) {
25658                         ts.Debug.assertIsDefined(computedTempVariables, "Encountered computed property name but 'computedTempVariables' argument was not provided.");
25659                         var temp = computedTempVariables[computedTempVariableOffset];
25660                         computedTempVariableOffset++;
25661                         // typeof _tmp === "symbol" ? _tmp : _tmp + ""
25662                         propertyNames.push(factory.createConditionalExpression(factory.createTypeCheck(temp, "symbol"), 
25663                         /*questionToken*/ undefined, temp, 
25664                         /*colonToken*/ undefined, factory.createAdd(temp, factory.createStringLiteral(""))));
25665                     }
25666                     else {
25667                         propertyNames.push(factory.createStringLiteralFromNode(propertyName));
25668                     }
25669                 }
25670             }
25671             return factory.createCallExpression(getUnscopedHelperName("__rest"), 
25672             /*typeArguments*/ undefined, [
25673                 value,
25674                 ts.setTextRange(factory.createArrayLiteralExpression(propertyNames), location)
25675             ]);
25676         }
25677         // ES2017 Helpers
25678         function createAwaiterHelper(hasLexicalThis, hasLexicalArguments, promiseConstructor, body) {
25679             context.requestEmitHelper(ts.awaiterHelper);
25680             var generatorFunc = factory.createFunctionExpression(
25681             /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */), 
25682             /*name*/ undefined, 
25683             /*typeParameters*/ undefined, 
25684             /*parameters*/ [], 
25685             /*type*/ undefined, body);
25686             // Mark this node as originally an async function
25687             (generatorFunc.emitNode || (generatorFunc.emitNode = {})).flags |= 262144 /* AsyncFunctionBody */ | 524288 /* ReuseTempVariableScope */;
25688             return factory.createCallExpression(getUnscopedHelperName("__awaiter"), 
25689             /*typeArguments*/ undefined, [
25690                 hasLexicalThis ? factory.createThis() : factory.createVoidZero(),
25691                 hasLexicalArguments ? factory.createIdentifier("arguments") : factory.createVoidZero(),
25692                 promiseConstructor ? ts.createExpressionFromEntityName(factory, promiseConstructor) : factory.createVoidZero(),
25693                 generatorFunc
25694             ]);
25695         }
25696         // ES2015 Helpers
25697         function createExtendsHelper(name) {
25698             context.requestEmitHelper(ts.extendsHelper);
25699             return factory.createCallExpression(getUnscopedHelperName("__extends"), 
25700             /*typeArguments*/ undefined, [name, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */)]);
25701         }
25702         function createTemplateObjectHelper(cooked, raw) {
25703             context.requestEmitHelper(ts.templateObjectHelper);
25704             return factory.createCallExpression(getUnscopedHelperName("__makeTemplateObject"), 
25705             /*typeArguments*/ undefined, [cooked, raw]);
25706         }
25707         function createSpreadHelper(argumentList) {
25708             context.requestEmitHelper(ts.readHelper);
25709             context.requestEmitHelper(ts.spreadHelper);
25710             return factory.createCallExpression(getUnscopedHelperName("__spread"), 
25711             /*typeArguments*/ undefined, argumentList);
25712         }
25713         function createSpreadArraysHelper(argumentList) {
25714             context.requestEmitHelper(ts.spreadArraysHelper);
25715             return factory.createCallExpression(getUnscopedHelperName("__spreadArrays"), 
25716             /*typeArguments*/ undefined, argumentList);
25717         }
25718         // ES2015 Destructuring Helpers
25719         function createValuesHelper(expression) {
25720             context.requestEmitHelper(ts.valuesHelper);
25721             return factory.createCallExpression(getUnscopedHelperName("__values"), 
25722             /*typeArguments*/ undefined, [expression]);
25723         }
25724         function createReadHelper(iteratorRecord, count) {
25725             context.requestEmitHelper(ts.readHelper);
25726             return factory.createCallExpression(getUnscopedHelperName("__read"), 
25727             /*typeArguments*/ undefined, count !== undefined
25728                 ? [iteratorRecord, factory.createNumericLiteral(count + "")]
25729                 : [iteratorRecord]);
25730         }
25731         // ES2015 Generator Helpers
25732         function createGeneratorHelper(body) {
25733             context.requestEmitHelper(ts.generatorHelper);
25734             return factory.createCallExpression(getUnscopedHelperName("__generator"), 
25735             /*typeArguments*/ undefined, [factory.createThis(), body]);
25736         }
25737         // ES Module Helpers
25738         function createCreateBindingHelper(module, inputName, outputName) {
25739             context.requestEmitHelper(ts.createBindingHelper);
25740             return factory.createCallExpression(getUnscopedHelperName("__createBinding"), 
25741             /*typeArguments*/ undefined, __spreadArrays([factory.createIdentifier("exports"), module, inputName], (outputName ? [outputName] : [])));
25742         }
25743         function createImportStarHelper(expression) {
25744             context.requestEmitHelper(ts.importStarHelper);
25745             return factory.createCallExpression(getUnscopedHelperName("__importStar"), 
25746             /*typeArguments*/ undefined, [expression]);
25747         }
25748         function createImportStarCallbackHelper() {
25749             context.requestEmitHelper(ts.importStarHelper);
25750             return getUnscopedHelperName("__importStar");
25751         }
25752         function createImportDefaultHelper(expression) {
25753             context.requestEmitHelper(ts.importDefaultHelper);
25754             return factory.createCallExpression(getUnscopedHelperName("__importDefault"), 
25755             /*typeArguments*/ undefined, [expression]);
25756         }
25757         function createExportStarHelper(moduleExpression, exportsExpression) {
25758             if (exportsExpression === void 0) { exportsExpression = factory.createIdentifier("exports"); }
25759             context.requestEmitHelper(ts.exportStarHelper);
25760             context.requestEmitHelper(ts.createBindingHelper);
25761             return factory.createCallExpression(getUnscopedHelperName("__exportStar"), 
25762             /*typeArguments*/ undefined, [moduleExpression, exportsExpression]);
25763         }
25764         // Class Fields Helpers
25765         function createClassPrivateFieldGetHelper(receiver, privateField) {
25766             context.requestEmitHelper(ts.classPrivateFieldGetHelper);
25767             return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldGet"), /*typeArguments*/ undefined, [receiver, privateField]);
25768         }
25769         function createClassPrivateFieldSetHelper(receiver, privateField, value) {
25770             context.requestEmitHelper(ts.classPrivateFieldSetHelper);
25771             return factory.createCallExpression(getUnscopedHelperName("__classPrivateFieldSet"), /*typeArguments*/ undefined, [receiver, privateField, value]);
25772         }
25773     }
25774     ts.createEmitHelperFactory = createEmitHelperFactory;
25775     /* @internal */
25776     function compareEmitHelpers(x, y) {
25777         if (x === y)
25778             return 0 /* EqualTo */;
25779         if (x.priority === y.priority)
25780             return 0 /* EqualTo */;
25781         if (x.priority === undefined)
25782             return 1 /* GreaterThan */;
25783         if (y.priority === undefined)
25784             return -1 /* LessThan */;
25785         return ts.compareValues(x.priority, y.priority);
25786     }
25787     ts.compareEmitHelpers = compareEmitHelpers;
25788     /**
25789      * @param input Template string input strings
25790      * @param args Names which need to be made file-level unique
25791      */
25792     function helperString(input) {
25793         var args = [];
25794         for (var _i = 1; _i < arguments.length; _i++) {
25795             args[_i - 1] = arguments[_i];
25796         }
25797         return function (uniqueName) {
25798             var result = "";
25799             for (var i = 0; i < args.length; i++) {
25800                 result += input[i];
25801                 result += uniqueName(args[i]);
25802             }
25803             result += input[input.length - 1];
25804             return result;
25805         };
25806     }
25807     ts.helperString = helperString;
25808     // TypeScript Helpers
25809     ts.decorateHelper = {
25810         name: "typescript:decorate",
25811         importName: "__decorate",
25812         scoped: false,
25813         priority: 2,
25814         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            };"
25815     };
25816     ts.metadataHelper = {
25817         name: "typescript:metadata",
25818         importName: "__metadata",
25819         scoped: false,
25820         priority: 3,
25821         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            };"
25822     };
25823     ts.paramHelper = {
25824         name: "typescript:param",
25825         importName: "__param",
25826         scoped: false,
25827         priority: 4,
25828         text: "\n            var __param = (this && this.__param) || function (paramIndex, decorator) {\n                return function (target, key) { decorator(target, key, paramIndex); }\n            };"
25829     };
25830     // ES2018 Helpers
25831     ts.assignHelper = {
25832         name: "typescript:assign",
25833         importName: "__assign",
25834         scoped: false,
25835         priority: 1,
25836         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            };"
25837     };
25838     ts.awaitHelper = {
25839         name: "typescript:await",
25840         importName: "__await",
25841         scoped: false,
25842         text: "\n            var __await = (this && this.__await) || function (v) { return this instanceof __await ? (this.v = v, this) : new __await(v); }"
25843     };
25844     ts.asyncGeneratorHelper = {
25845         name: "typescript:asyncGenerator",
25846         importName: "__asyncGenerator",
25847         scoped: false,
25848         dependencies: [ts.awaitHelper],
25849         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            };"
25850     };
25851     ts.asyncDelegator = {
25852         name: "typescript:asyncDelegator",
25853         importName: "__asyncDelegator",
25854         scoped: false,
25855         dependencies: [ts.awaitHelper],
25856         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            };"
25857     };
25858     ts.asyncValues = {
25859         name: "typescript:asyncValues",
25860         importName: "__asyncValues",
25861         scoped: false,
25862         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            };"
25863     };
25864     // ES2018 Destructuring Helpers
25865     ts.restHelper = {
25866         name: "typescript:rest",
25867         importName: "__rest",
25868         scoped: false,
25869         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            };"
25870     };
25871     // ES2017 Helpers
25872     ts.awaiterHelper = {
25873         name: "typescript:awaiter",
25874         importName: "__awaiter",
25875         scoped: false,
25876         priority: 5,
25877         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            };"
25878     };
25879     // ES2015 Helpers
25880     ts.extendsHelper = {
25881         name: "typescript:extends",
25882         importName: "__extends",
25883         scoped: false,
25884         priority: 0,
25885         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 (Object.prototype.hasOwnProperty.call(b, 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            })();"
25886     };
25887     ts.templateObjectHelper = {
25888         name: "typescript:makeTemplateObject",
25889         importName: "__makeTemplateObject",
25890         scoped: false,
25891         priority: 0,
25892         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            };"
25893     };
25894     ts.readHelper = {
25895         name: "typescript:read",
25896         importName: "__read",
25897         scoped: false,
25898         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            };"
25899     };
25900     ts.spreadHelper = {
25901         name: "typescript:spread",
25902         importName: "__spread",
25903         scoped: false,
25904         dependencies: [ts.readHelper],
25905         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            };"
25906     };
25907     ts.spreadArraysHelper = {
25908         name: "typescript:spreadArrays",
25909         importName: "__spreadArrays",
25910         scoped: false,
25911         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            };"
25912     };
25913     // ES2015 Destructuring Helpers
25914     ts.valuesHelper = {
25915         name: "typescript:values",
25916         importName: "__values",
25917         scoped: false,
25918         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            };"
25919     };
25920     // ES2015 Generator Helpers
25921     // The __generator helper is used by down-level transformations to emulate the runtime
25922     // semantics of an ES2015 generator function. When called, this helper returns an
25923     // object that implements the Iterator protocol, in that it has `next`, `return`, and
25924     // `throw` methods that step through the generator when invoked.
25925     //
25926     // parameters:
25927     //  @param thisArg  The value to use as the `this` binding for the transformed generator body.
25928     //  @param body     A function that acts as the transformed generator body.
25929     //
25930     // variables:
25931     //  _       Persistent state for the generator that is shared between the helper and the
25932     //          generator body. The state object has the following members:
25933     //            sent() - A method that returns or throws the current completion value.
25934     //            label  - The next point at which to resume evaluation of the generator body.
25935     //            trys   - A stack of protected regions (try/catch/finally blocks).
25936     //            ops    - A stack of pending instructions when inside of a finally block.
25937     //  f       A value indicating whether the generator is executing.
25938     //  y       An iterator to delegate for a yield*.
25939     //  t       A temporary variable that holds one of the following values (note that these
25940     //          cases do not overlap):
25941     //          - The completion value when resuming from a `yield` or `yield*`.
25942     //          - The error value for a catch block.
25943     //          - The current protected region (array of try/catch/finally/end labels).
25944     //          - The verb (`next`, `throw`, or `return` method) to delegate to the expression
25945     //            of a `yield*`.
25946     //          - The result of evaluating the verb delegated to the expression of a `yield*`.
25947     //
25948     // functions:
25949     //  verb(n)     Creates a bound callback to the `step` function for opcode `n`.
25950     //  step(op)    Evaluates opcodes in a generator body until execution is suspended or
25951     //              completed.
25952     //
25953     // The __generator helper understands a limited set of instructions:
25954     //  0: next(value?)     - Start or resume the generator with the specified value.
25955     //  1: throw(error)     - Resume the generator with an exception. If the generator is
25956     //                        suspended inside of one or more protected regions, evaluates
25957     //                        any intervening finally blocks between the current label and
25958     //                        the nearest catch block or function boundary. If uncaught, the
25959     //                        exception is thrown to the caller.
25960     //  2: return(value?)   - Resume the generator as if with a return. If the generator is
25961     //                        suspended inside of one or more protected regions, evaluates any
25962     //                        intervening finally blocks.
25963     //  3: break(label)     - Jump to the specified label. If the label is outside of the
25964     //                        current protected region, evaluates any intervening finally
25965     //                        blocks.
25966     //  4: yield(value?)    - Yield execution to the caller with an optional value. When
25967     //                        resumed, the generator will continue at the next label.
25968     //  5: yield*(value)    - Delegates evaluation to the supplied iterator. When
25969     //                        delegation completes, the generator will continue at the next
25970     //                        label.
25971     //  6: catch(error)     - Handles an exception thrown from within the generator body. If
25972     //                        the current label is inside of one or more protected regions,
25973     //                        evaluates any intervening finally blocks between the current
25974     //                        label and the nearest catch block or function boundary. If
25975     //                        uncaught, the exception is thrown to the caller.
25976     //  7: endfinally       - Ends a finally block, resuming the last instruction prior to
25977     //                        entering a finally block.
25978     //
25979     // For examples of how these are used, see the comments in ./transformers/generators.ts
25980     ts.generatorHelper = {
25981         name: "typescript:generator",
25982         importName: "__generator",
25983         scoped: false,
25984         priority: 6,
25985         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            };"
25986     };
25987     // ES Module Helpers
25988     ts.createBindingHelper = {
25989         name: "typescript:commonjscreatebinding",
25990         importName: "__createBinding",
25991         scoped: false,
25992         priority: 1,
25993         text: "\n            var __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            }));"
25994     };
25995     ts.setModuleDefaultHelper = {
25996         name: "typescript:commonjscreatevalue",
25997         importName: "__setModuleDefault",
25998         scoped: false,
25999         priority: 1,
26000         text: "\n            var __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            });"
26001     };
26002     // emit helper for `import * as Name from "foo"`
26003     ts.importStarHelper = {
26004         name: "typescript:commonjsimportstar",
26005         importName: "__importStar",
26006         scoped: false,
26007         dependencies: [ts.createBindingHelper, ts.setModuleDefaultHelper],
26008         priority: 2,
26009         text: "\n            var __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.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\n                __setModuleDefault(result, mod);\n                return result;\n            };"
26010     };
26011     // emit helper for `import Name from "foo"`
26012     ts.importDefaultHelper = {
26013         name: "typescript:commonjsimportdefault",
26014         importName: "__importDefault",
26015         scoped: false,
26016         text: "\n            var __importDefault = (this && this.__importDefault) || function (mod) {\n                return (mod && mod.__esModule) ? mod : { \"default\": mod };\n            };"
26017     };
26018     // emit output for the __export helper function
26019     ts.exportStarHelper = {
26020         name: "typescript:export-star",
26021         importName: "__exportStar",
26022         scoped: false,
26023         dependencies: [ts.createBindingHelper],
26024         priority: 2,
26025         text: "\n            var __exportStar = (this && this.__exportStar) || function(m, exports) {\n                for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);\n            };"
26026     };
26027     // Class fields helpers
26028     ts.classPrivateFieldGetHelper = {
26029         name: "typescript:classPrivateFieldGet",
26030         importName: "__classPrivateFieldGet",
26031         scoped: false,
26032         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            };"
26033     };
26034     ts.classPrivateFieldSetHelper = {
26035         name: "typescript:classPrivateFieldSet",
26036         importName: "__classPrivateFieldSet",
26037         scoped: false,
26038         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            };"
26039     };
26040     var allUnscopedEmitHelpers;
26041     function getAllUnscopedEmitHelpers() {
26042         return allUnscopedEmitHelpers || (allUnscopedEmitHelpers = ts.arrayToMap([
26043             ts.decorateHelper,
26044             ts.metadataHelper,
26045             ts.paramHelper,
26046             ts.assignHelper,
26047             ts.awaitHelper,
26048             ts.asyncGeneratorHelper,
26049             ts.asyncDelegator,
26050             ts.asyncValues,
26051             ts.restHelper,
26052             ts.awaiterHelper,
26053             ts.extendsHelper,
26054             ts.templateObjectHelper,
26055             ts.spreadHelper,
26056             ts.spreadArraysHelper,
26057             ts.valuesHelper,
26058             ts.readHelper,
26059             ts.generatorHelper,
26060             ts.importStarHelper,
26061             ts.importDefaultHelper,
26062             ts.exportStarHelper,
26063             ts.classPrivateFieldGetHelper,
26064             ts.classPrivateFieldSetHelper,
26065             ts.createBindingHelper,
26066             ts.setModuleDefaultHelper
26067         ], function (helper) { return helper.name; }));
26068     }
26069     ts.getAllUnscopedEmitHelpers = getAllUnscopedEmitHelpers;
26070     ts.asyncSuperHelper = {
26071         name: "typescript:async-super",
26072         scoped: true,
26073         text: helperString(__makeTemplateObject(["\n            const ", " = name => super[name];"], ["\n            const ", " = name => super[name];"]), "_superIndex")
26074     };
26075     ts.advancedAsyncSuperHelper = {
26076         name: "typescript:advanced-async-super",
26077         scoped: true,
26078         text: 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")
26079     };
26080 })(ts || (ts = {}));
26081 var ts;
26082 (function (ts) {
26083     // Literals
26084     function isNumericLiteral(node) {
26085         return node.kind === 8 /* NumericLiteral */;
26086     }
26087     ts.isNumericLiteral = isNumericLiteral;
26088     function isBigIntLiteral(node) {
26089         return node.kind === 9 /* BigIntLiteral */;
26090     }
26091     ts.isBigIntLiteral = isBigIntLiteral;
26092     function isStringLiteral(node) {
26093         return node.kind === 10 /* StringLiteral */;
26094     }
26095     ts.isStringLiteral = isStringLiteral;
26096     function isJsxText(node) {
26097         return node.kind === 11 /* JsxText */;
26098     }
26099     ts.isJsxText = isJsxText;
26100     function isRegularExpressionLiteral(node) {
26101         return node.kind === 13 /* RegularExpressionLiteral */;
26102     }
26103     ts.isRegularExpressionLiteral = isRegularExpressionLiteral;
26104     function isNoSubstitutionTemplateLiteral(node) {
26105         return node.kind === 14 /* NoSubstitutionTemplateLiteral */;
26106     }
26107     ts.isNoSubstitutionTemplateLiteral = isNoSubstitutionTemplateLiteral;
26108     // Pseudo-literals
26109     function isTemplateHead(node) {
26110         return node.kind === 15 /* TemplateHead */;
26111     }
26112     ts.isTemplateHead = isTemplateHead;
26113     function isTemplateMiddle(node) {
26114         return node.kind === 16 /* TemplateMiddle */;
26115     }
26116     ts.isTemplateMiddle = isTemplateMiddle;
26117     function isTemplateTail(node) {
26118         return node.kind === 17 /* TemplateTail */;
26119     }
26120     ts.isTemplateTail = isTemplateTail;
26121     // Identifiers
26122     function isIdentifier(node) {
26123         return node.kind === 78 /* Identifier */;
26124     }
26125     ts.isIdentifier = isIdentifier;
26126     // Names
26127     function isQualifiedName(node) {
26128         return node.kind === 157 /* QualifiedName */;
26129     }
26130     ts.isQualifiedName = isQualifiedName;
26131     function isComputedPropertyName(node) {
26132         return node.kind === 158 /* ComputedPropertyName */;
26133     }
26134     ts.isComputedPropertyName = isComputedPropertyName;
26135     function isPrivateIdentifier(node) {
26136         return node.kind === 79 /* PrivateIdentifier */;
26137     }
26138     ts.isPrivateIdentifier = isPrivateIdentifier;
26139     // Tokens
26140     /*@internal*/
26141     function isSuperKeyword(node) {
26142         return node.kind === 105 /* SuperKeyword */;
26143     }
26144     ts.isSuperKeyword = isSuperKeyword;
26145     /*@internal*/
26146     function isImportKeyword(node) {
26147         return node.kind === 99 /* ImportKeyword */;
26148     }
26149     ts.isImportKeyword = isImportKeyword;
26150     /*@internal*/
26151     function isCommaToken(node) {
26152         return node.kind === 27 /* CommaToken */;
26153     }
26154     ts.isCommaToken = isCommaToken;
26155     /*@internal*/
26156     function isQuestionToken(node) {
26157         return node.kind === 57 /* QuestionToken */;
26158     }
26159     ts.isQuestionToken = isQuestionToken;
26160     /*@internal*/
26161     function isExclamationToken(node) {
26162         return node.kind === 53 /* ExclamationToken */;
26163     }
26164     ts.isExclamationToken = isExclamationToken;
26165     // Signature elements
26166     function isTypeParameterDeclaration(node) {
26167         return node.kind === 159 /* TypeParameter */;
26168     }
26169     ts.isTypeParameterDeclaration = isTypeParameterDeclaration;
26170     // TODO(rbuckton): Rename to 'isParameterDeclaration'
26171     function isParameter(node) {
26172         return node.kind === 160 /* Parameter */;
26173     }
26174     ts.isParameter = isParameter;
26175     function isDecorator(node) {
26176         return node.kind === 161 /* Decorator */;
26177     }
26178     ts.isDecorator = isDecorator;
26179     // TypeMember
26180     function isPropertySignature(node) {
26181         return node.kind === 162 /* PropertySignature */;
26182     }
26183     ts.isPropertySignature = isPropertySignature;
26184     function isPropertyDeclaration(node) {
26185         return node.kind === 163 /* PropertyDeclaration */;
26186     }
26187     ts.isPropertyDeclaration = isPropertyDeclaration;
26188     function isMethodSignature(node) {
26189         return node.kind === 164 /* MethodSignature */;
26190     }
26191     ts.isMethodSignature = isMethodSignature;
26192     function isMethodDeclaration(node) {
26193         return node.kind === 165 /* MethodDeclaration */;
26194     }
26195     ts.isMethodDeclaration = isMethodDeclaration;
26196     function isConstructorDeclaration(node) {
26197         return node.kind === 166 /* Constructor */;
26198     }
26199     ts.isConstructorDeclaration = isConstructorDeclaration;
26200     function isGetAccessorDeclaration(node) {
26201         return node.kind === 167 /* GetAccessor */;
26202     }
26203     ts.isGetAccessorDeclaration = isGetAccessorDeclaration;
26204     function isSetAccessorDeclaration(node) {
26205         return node.kind === 168 /* SetAccessor */;
26206     }
26207     ts.isSetAccessorDeclaration = isSetAccessorDeclaration;
26208     function isCallSignatureDeclaration(node) {
26209         return node.kind === 169 /* CallSignature */;
26210     }
26211     ts.isCallSignatureDeclaration = isCallSignatureDeclaration;
26212     function isConstructSignatureDeclaration(node) {
26213         return node.kind === 170 /* ConstructSignature */;
26214     }
26215     ts.isConstructSignatureDeclaration = isConstructSignatureDeclaration;
26216     function isIndexSignatureDeclaration(node) {
26217         return node.kind === 171 /* IndexSignature */;
26218     }
26219     ts.isIndexSignatureDeclaration = isIndexSignatureDeclaration;
26220     // Type
26221     function isTypePredicateNode(node) {
26222         return node.kind === 172 /* TypePredicate */;
26223     }
26224     ts.isTypePredicateNode = isTypePredicateNode;
26225     function isTypeReferenceNode(node) {
26226         return node.kind === 173 /* TypeReference */;
26227     }
26228     ts.isTypeReferenceNode = isTypeReferenceNode;
26229     function isFunctionTypeNode(node) {
26230         return node.kind === 174 /* FunctionType */;
26231     }
26232     ts.isFunctionTypeNode = isFunctionTypeNode;
26233     function isConstructorTypeNode(node) {
26234         return node.kind === 175 /* ConstructorType */;
26235     }
26236     ts.isConstructorTypeNode = isConstructorTypeNode;
26237     function isTypeQueryNode(node) {
26238         return node.kind === 176 /* TypeQuery */;
26239     }
26240     ts.isTypeQueryNode = isTypeQueryNode;
26241     function isTypeLiteralNode(node) {
26242         return node.kind === 177 /* TypeLiteral */;
26243     }
26244     ts.isTypeLiteralNode = isTypeLiteralNode;
26245     function isArrayTypeNode(node) {
26246         return node.kind === 178 /* ArrayType */;
26247     }
26248     ts.isArrayTypeNode = isArrayTypeNode;
26249     function isTupleTypeNode(node) {
26250         return node.kind === 179 /* TupleType */;
26251     }
26252     ts.isTupleTypeNode = isTupleTypeNode;
26253     function isNamedTupleMember(node) {
26254         return node.kind === 192 /* NamedTupleMember */;
26255     }
26256     ts.isNamedTupleMember = isNamedTupleMember;
26257     function isOptionalTypeNode(node) {
26258         return node.kind === 180 /* OptionalType */;
26259     }
26260     ts.isOptionalTypeNode = isOptionalTypeNode;
26261     function isRestTypeNode(node) {
26262         return node.kind === 181 /* RestType */;
26263     }
26264     ts.isRestTypeNode = isRestTypeNode;
26265     function isUnionTypeNode(node) {
26266         return node.kind === 182 /* UnionType */;
26267     }
26268     ts.isUnionTypeNode = isUnionTypeNode;
26269     function isIntersectionTypeNode(node) {
26270         return node.kind === 183 /* IntersectionType */;
26271     }
26272     ts.isIntersectionTypeNode = isIntersectionTypeNode;
26273     function isConditionalTypeNode(node) {
26274         return node.kind === 184 /* ConditionalType */;
26275     }
26276     ts.isConditionalTypeNode = isConditionalTypeNode;
26277     function isInferTypeNode(node) {
26278         return node.kind === 185 /* InferType */;
26279     }
26280     ts.isInferTypeNode = isInferTypeNode;
26281     function isParenthesizedTypeNode(node) {
26282         return node.kind === 186 /* ParenthesizedType */;
26283     }
26284     ts.isParenthesizedTypeNode = isParenthesizedTypeNode;
26285     function isThisTypeNode(node) {
26286         return node.kind === 187 /* ThisType */;
26287     }
26288     ts.isThisTypeNode = isThisTypeNode;
26289     function isTypeOperatorNode(node) {
26290         return node.kind === 188 /* TypeOperator */;
26291     }
26292     ts.isTypeOperatorNode = isTypeOperatorNode;
26293     function isIndexedAccessTypeNode(node) {
26294         return node.kind === 189 /* IndexedAccessType */;
26295     }
26296     ts.isIndexedAccessTypeNode = isIndexedAccessTypeNode;
26297     function isMappedTypeNode(node) {
26298         return node.kind === 190 /* MappedType */;
26299     }
26300     ts.isMappedTypeNode = isMappedTypeNode;
26301     function isLiteralTypeNode(node) {
26302         return node.kind === 191 /* LiteralType */;
26303     }
26304     ts.isLiteralTypeNode = isLiteralTypeNode;
26305     function isImportTypeNode(node) {
26306         return node.kind === 195 /* ImportType */;
26307     }
26308     ts.isImportTypeNode = isImportTypeNode;
26309     function isTemplateLiteralTypeSpan(node) {
26310         return node.kind === 194 /* TemplateLiteralTypeSpan */;
26311     }
26312     ts.isTemplateLiteralTypeSpan = isTemplateLiteralTypeSpan;
26313     function isTemplateLiteralTypeNode(node) {
26314         return node.kind === 193 /* TemplateLiteralType */;
26315     }
26316     ts.isTemplateLiteralTypeNode = isTemplateLiteralTypeNode;
26317     // Binding patterns
26318     function isObjectBindingPattern(node) {
26319         return node.kind === 196 /* ObjectBindingPattern */;
26320     }
26321     ts.isObjectBindingPattern = isObjectBindingPattern;
26322     function isArrayBindingPattern(node) {
26323         return node.kind === 197 /* ArrayBindingPattern */;
26324     }
26325     ts.isArrayBindingPattern = isArrayBindingPattern;
26326     function isBindingElement(node) {
26327         return node.kind === 198 /* BindingElement */;
26328     }
26329     ts.isBindingElement = isBindingElement;
26330     // Expression
26331     function isArrayLiteralExpression(node) {
26332         return node.kind === 199 /* ArrayLiteralExpression */;
26333     }
26334     ts.isArrayLiteralExpression = isArrayLiteralExpression;
26335     function isObjectLiteralExpression(node) {
26336         return node.kind === 200 /* ObjectLiteralExpression */;
26337     }
26338     ts.isObjectLiteralExpression = isObjectLiteralExpression;
26339     function isPropertyAccessExpression(node) {
26340         return node.kind === 201 /* PropertyAccessExpression */;
26341     }
26342     ts.isPropertyAccessExpression = isPropertyAccessExpression;
26343     function isElementAccessExpression(node) {
26344         return node.kind === 202 /* ElementAccessExpression */;
26345     }
26346     ts.isElementAccessExpression = isElementAccessExpression;
26347     function isCallExpression(node) {
26348         return node.kind === 203 /* CallExpression */;
26349     }
26350     ts.isCallExpression = isCallExpression;
26351     function isNewExpression(node) {
26352         return node.kind === 204 /* NewExpression */;
26353     }
26354     ts.isNewExpression = isNewExpression;
26355     function isTaggedTemplateExpression(node) {
26356         return node.kind === 205 /* TaggedTemplateExpression */;
26357     }
26358     ts.isTaggedTemplateExpression = isTaggedTemplateExpression;
26359     function isTypeAssertionExpression(node) {
26360         return node.kind === 206 /* TypeAssertionExpression */;
26361     }
26362     ts.isTypeAssertionExpression = isTypeAssertionExpression;
26363     function isParenthesizedExpression(node) {
26364         return node.kind === 207 /* ParenthesizedExpression */;
26365     }
26366     ts.isParenthesizedExpression = isParenthesizedExpression;
26367     function isFunctionExpression(node) {
26368         return node.kind === 208 /* FunctionExpression */;
26369     }
26370     ts.isFunctionExpression = isFunctionExpression;
26371     function isArrowFunction(node) {
26372         return node.kind === 209 /* ArrowFunction */;
26373     }
26374     ts.isArrowFunction = isArrowFunction;
26375     function isDeleteExpression(node) {
26376         return node.kind === 210 /* DeleteExpression */;
26377     }
26378     ts.isDeleteExpression = isDeleteExpression;
26379     function isTypeOfExpression(node) {
26380         return node.kind === 211 /* TypeOfExpression */;
26381     }
26382     ts.isTypeOfExpression = isTypeOfExpression;
26383     function isVoidExpression(node) {
26384         return node.kind === 212 /* VoidExpression */;
26385     }
26386     ts.isVoidExpression = isVoidExpression;
26387     function isAwaitExpression(node) {
26388         return node.kind === 213 /* AwaitExpression */;
26389     }
26390     ts.isAwaitExpression = isAwaitExpression;
26391     function isPrefixUnaryExpression(node) {
26392         return node.kind === 214 /* PrefixUnaryExpression */;
26393     }
26394     ts.isPrefixUnaryExpression = isPrefixUnaryExpression;
26395     function isPostfixUnaryExpression(node) {
26396         return node.kind === 215 /* PostfixUnaryExpression */;
26397     }
26398     ts.isPostfixUnaryExpression = isPostfixUnaryExpression;
26399     function isBinaryExpression(node) {
26400         return node.kind === 216 /* BinaryExpression */;
26401     }
26402     ts.isBinaryExpression = isBinaryExpression;
26403     function isConditionalExpression(node) {
26404         return node.kind === 217 /* ConditionalExpression */;
26405     }
26406     ts.isConditionalExpression = isConditionalExpression;
26407     function isTemplateExpression(node) {
26408         return node.kind === 218 /* TemplateExpression */;
26409     }
26410     ts.isTemplateExpression = isTemplateExpression;
26411     function isYieldExpression(node) {
26412         return node.kind === 219 /* YieldExpression */;
26413     }
26414     ts.isYieldExpression = isYieldExpression;
26415     function isSpreadElement(node) {
26416         return node.kind === 220 /* SpreadElement */;
26417     }
26418     ts.isSpreadElement = isSpreadElement;
26419     function isClassExpression(node) {
26420         return node.kind === 221 /* ClassExpression */;
26421     }
26422     ts.isClassExpression = isClassExpression;
26423     function isOmittedExpression(node) {
26424         return node.kind === 222 /* OmittedExpression */;
26425     }
26426     ts.isOmittedExpression = isOmittedExpression;
26427     function isExpressionWithTypeArguments(node) {
26428         return node.kind === 223 /* ExpressionWithTypeArguments */;
26429     }
26430     ts.isExpressionWithTypeArguments = isExpressionWithTypeArguments;
26431     function isAsExpression(node) {
26432         return node.kind === 224 /* AsExpression */;
26433     }
26434     ts.isAsExpression = isAsExpression;
26435     function isNonNullExpression(node) {
26436         return node.kind === 225 /* NonNullExpression */;
26437     }
26438     ts.isNonNullExpression = isNonNullExpression;
26439     function isMetaProperty(node) {
26440         return node.kind === 226 /* MetaProperty */;
26441     }
26442     ts.isMetaProperty = isMetaProperty;
26443     function isSyntheticExpression(node) {
26444         return node.kind === 227 /* SyntheticExpression */;
26445     }
26446     ts.isSyntheticExpression = isSyntheticExpression;
26447     function isPartiallyEmittedExpression(node) {
26448         return node.kind === 336 /* PartiallyEmittedExpression */;
26449     }
26450     ts.isPartiallyEmittedExpression = isPartiallyEmittedExpression;
26451     function isCommaListExpression(node) {
26452         return node.kind === 337 /* CommaListExpression */;
26453     }
26454     ts.isCommaListExpression = isCommaListExpression;
26455     // Misc
26456     function isTemplateSpan(node) {
26457         return node.kind === 228 /* TemplateSpan */;
26458     }
26459     ts.isTemplateSpan = isTemplateSpan;
26460     function isSemicolonClassElement(node) {
26461         return node.kind === 229 /* SemicolonClassElement */;
26462     }
26463     ts.isSemicolonClassElement = isSemicolonClassElement;
26464     // Elements
26465     function isBlock(node) {
26466         return node.kind === 230 /* Block */;
26467     }
26468     ts.isBlock = isBlock;
26469     function isVariableStatement(node) {
26470         return node.kind === 232 /* VariableStatement */;
26471     }
26472     ts.isVariableStatement = isVariableStatement;
26473     function isEmptyStatement(node) {
26474         return node.kind === 231 /* EmptyStatement */;
26475     }
26476     ts.isEmptyStatement = isEmptyStatement;
26477     function isExpressionStatement(node) {
26478         return node.kind === 233 /* ExpressionStatement */;
26479     }
26480     ts.isExpressionStatement = isExpressionStatement;
26481     function isIfStatement(node) {
26482         return node.kind === 234 /* IfStatement */;
26483     }
26484     ts.isIfStatement = isIfStatement;
26485     function isDoStatement(node) {
26486         return node.kind === 235 /* DoStatement */;
26487     }
26488     ts.isDoStatement = isDoStatement;
26489     function isWhileStatement(node) {
26490         return node.kind === 236 /* WhileStatement */;
26491     }
26492     ts.isWhileStatement = isWhileStatement;
26493     function isForStatement(node) {
26494         return node.kind === 237 /* ForStatement */;
26495     }
26496     ts.isForStatement = isForStatement;
26497     function isForInStatement(node) {
26498         return node.kind === 238 /* ForInStatement */;
26499     }
26500     ts.isForInStatement = isForInStatement;
26501     function isForOfStatement(node) {
26502         return node.kind === 239 /* ForOfStatement */;
26503     }
26504     ts.isForOfStatement = isForOfStatement;
26505     function isContinueStatement(node) {
26506         return node.kind === 240 /* ContinueStatement */;
26507     }
26508     ts.isContinueStatement = isContinueStatement;
26509     function isBreakStatement(node) {
26510         return node.kind === 241 /* BreakStatement */;
26511     }
26512     ts.isBreakStatement = isBreakStatement;
26513     function isReturnStatement(node) {
26514         return node.kind === 242 /* ReturnStatement */;
26515     }
26516     ts.isReturnStatement = isReturnStatement;
26517     function isWithStatement(node) {
26518         return node.kind === 243 /* WithStatement */;
26519     }
26520     ts.isWithStatement = isWithStatement;
26521     function isSwitchStatement(node) {
26522         return node.kind === 244 /* SwitchStatement */;
26523     }
26524     ts.isSwitchStatement = isSwitchStatement;
26525     function isLabeledStatement(node) {
26526         return node.kind === 245 /* LabeledStatement */;
26527     }
26528     ts.isLabeledStatement = isLabeledStatement;
26529     function isThrowStatement(node) {
26530         return node.kind === 246 /* ThrowStatement */;
26531     }
26532     ts.isThrowStatement = isThrowStatement;
26533     function isTryStatement(node) {
26534         return node.kind === 247 /* TryStatement */;
26535     }
26536     ts.isTryStatement = isTryStatement;
26537     function isDebuggerStatement(node) {
26538         return node.kind === 248 /* DebuggerStatement */;
26539     }
26540     ts.isDebuggerStatement = isDebuggerStatement;
26541     function isVariableDeclaration(node) {
26542         return node.kind === 249 /* VariableDeclaration */;
26543     }
26544     ts.isVariableDeclaration = isVariableDeclaration;
26545     function isVariableDeclarationList(node) {
26546         return node.kind === 250 /* VariableDeclarationList */;
26547     }
26548     ts.isVariableDeclarationList = isVariableDeclarationList;
26549     function isFunctionDeclaration(node) {
26550         return node.kind === 251 /* FunctionDeclaration */;
26551     }
26552     ts.isFunctionDeclaration = isFunctionDeclaration;
26553     function isClassDeclaration(node) {
26554         return node.kind === 252 /* ClassDeclaration */;
26555     }
26556     ts.isClassDeclaration = isClassDeclaration;
26557     function isInterfaceDeclaration(node) {
26558         return node.kind === 253 /* InterfaceDeclaration */;
26559     }
26560     ts.isInterfaceDeclaration = isInterfaceDeclaration;
26561     function isTypeAliasDeclaration(node) {
26562         return node.kind === 254 /* TypeAliasDeclaration */;
26563     }
26564     ts.isTypeAliasDeclaration = isTypeAliasDeclaration;
26565     function isEnumDeclaration(node) {
26566         return node.kind === 255 /* EnumDeclaration */;
26567     }
26568     ts.isEnumDeclaration = isEnumDeclaration;
26569     function isModuleDeclaration(node) {
26570         return node.kind === 256 /* ModuleDeclaration */;
26571     }
26572     ts.isModuleDeclaration = isModuleDeclaration;
26573     function isModuleBlock(node) {
26574         return node.kind === 257 /* ModuleBlock */;
26575     }
26576     ts.isModuleBlock = isModuleBlock;
26577     function isCaseBlock(node) {
26578         return node.kind === 258 /* CaseBlock */;
26579     }
26580     ts.isCaseBlock = isCaseBlock;
26581     function isNamespaceExportDeclaration(node) {
26582         return node.kind === 259 /* NamespaceExportDeclaration */;
26583     }
26584     ts.isNamespaceExportDeclaration = isNamespaceExportDeclaration;
26585     function isImportEqualsDeclaration(node) {
26586         return node.kind === 260 /* ImportEqualsDeclaration */;
26587     }
26588     ts.isImportEqualsDeclaration = isImportEqualsDeclaration;
26589     function isImportDeclaration(node) {
26590         return node.kind === 261 /* ImportDeclaration */;
26591     }
26592     ts.isImportDeclaration = isImportDeclaration;
26593     function isImportClause(node) {
26594         return node.kind === 262 /* ImportClause */;
26595     }
26596     ts.isImportClause = isImportClause;
26597     function isNamespaceImport(node) {
26598         return node.kind === 263 /* NamespaceImport */;
26599     }
26600     ts.isNamespaceImport = isNamespaceImport;
26601     function isNamespaceExport(node) {
26602         return node.kind === 269 /* NamespaceExport */;
26603     }
26604     ts.isNamespaceExport = isNamespaceExport;
26605     function isNamedImports(node) {
26606         return node.kind === 264 /* NamedImports */;
26607     }
26608     ts.isNamedImports = isNamedImports;
26609     function isImportSpecifier(node) {
26610         return node.kind === 265 /* ImportSpecifier */;
26611     }
26612     ts.isImportSpecifier = isImportSpecifier;
26613     function isExportAssignment(node) {
26614         return node.kind === 266 /* ExportAssignment */;
26615     }
26616     ts.isExportAssignment = isExportAssignment;
26617     function isExportDeclaration(node) {
26618         return node.kind === 267 /* ExportDeclaration */;
26619     }
26620     ts.isExportDeclaration = isExportDeclaration;
26621     function isNamedExports(node) {
26622         return node.kind === 268 /* NamedExports */;
26623     }
26624     ts.isNamedExports = isNamedExports;
26625     function isExportSpecifier(node) {
26626         return node.kind === 270 /* ExportSpecifier */;
26627     }
26628     ts.isExportSpecifier = isExportSpecifier;
26629     function isMissingDeclaration(node) {
26630         return node.kind === 271 /* MissingDeclaration */;
26631     }
26632     ts.isMissingDeclaration = isMissingDeclaration;
26633     function isNotEmittedStatement(node) {
26634         return node.kind === 335 /* NotEmittedStatement */;
26635     }
26636     ts.isNotEmittedStatement = isNotEmittedStatement;
26637     /* @internal */
26638     function isSyntheticReference(node) {
26639         return node.kind === 340 /* SyntheticReferenceExpression */;
26640     }
26641     ts.isSyntheticReference = isSyntheticReference;
26642     /* @internal */
26643     function isMergeDeclarationMarker(node) {
26644         return node.kind === 338 /* MergeDeclarationMarker */;
26645     }
26646     ts.isMergeDeclarationMarker = isMergeDeclarationMarker;
26647     /* @internal */
26648     function isEndOfDeclarationMarker(node) {
26649         return node.kind === 339 /* EndOfDeclarationMarker */;
26650     }
26651     ts.isEndOfDeclarationMarker = isEndOfDeclarationMarker;
26652     // Module References
26653     function isExternalModuleReference(node) {
26654         return node.kind === 272 /* ExternalModuleReference */;
26655     }
26656     ts.isExternalModuleReference = isExternalModuleReference;
26657     // JSX
26658     function isJsxElement(node) {
26659         return node.kind === 273 /* JsxElement */;
26660     }
26661     ts.isJsxElement = isJsxElement;
26662     function isJsxSelfClosingElement(node) {
26663         return node.kind === 274 /* JsxSelfClosingElement */;
26664     }
26665     ts.isJsxSelfClosingElement = isJsxSelfClosingElement;
26666     function isJsxOpeningElement(node) {
26667         return node.kind === 275 /* JsxOpeningElement */;
26668     }
26669     ts.isJsxOpeningElement = isJsxOpeningElement;
26670     function isJsxClosingElement(node) {
26671         return node.kind === 276 /* JsxClosingElement */;
26672     }
26673     ts.isJsxClosingElement = isJsxClosingElement;
26674     function isJsxFragment(node) {
26675         return node.kind === 277 /* JsxFragment */;
26676     }
26677     ts.isJsxFragment = isJsxFragment;
26678     function isJsxOpeningFragment(node) {
26679         return node.kind === 278 /* JsxOpeningFragment */;
26680     }
26681     ts.isJsxOpeningFragment = isJsxOpeningFragment;
26682     function isJsxClosingFragment(node) {
26683         return node.kind === 279 /* JsxClosingFragment */;
26684     }
26685     ts.isJsxClosingFragment = isJsxClosingFragment;
26686     function isJsxAttribute(node) {
26687         return node.kind === 280 /* JsxAttribute */;
26688     }
26689     ts.isJsxAttribute = isJsxAttribute;
26690     function isJsxAttributes(node) {
26691         return node.kind === 281 /* JsxAttributes */;
26692     }
26693     ts.isJsxAttributes = isJsxAttributes;
26694     function isJsxSpreadAttribute(node) {
26695         return node.kind === 282 /* JsxSpreadAttribute */;
26696     }
26697     ts.isJsxSpreadAttribute = isJsxSpreadAttribute;
26698     function isJsxExpression(node) {
26699         return node.kind === 283 /* JsxExpression */;
26700     }
26701     ts.isJsxExpression = isJsxExpression;
26702     // Clauses
26703     function isCaseClause(node) {
26704         return node.kind === 284 /* CaseClause */;
26705     }
26706     ts.isCaseClause = isCaseClause;
26707     function isDefaultClause(node) {
26708         return node.kind === 285 /* DefaultClause */;
26709     }
26710     ts.isDefaultClause = isDefaultClause;
26711     function isHeritageClause(node) {
26712         return node.kind === 286 /* HeritageClause */;
26713     }
26714     ts.isHeritageClause = isHeritageClause;
26715     function isCatchClause(node) {
26716         return node.kind === 287 /* CatchClause */;
26717     }
26718     ts.isCatchClause = isCatchClause;
26719     // Property assignments
26720     function isPropertyAssignment(node) {
26721         return node.kind === 288 /* PropertyAssignment */;
26722     }
26723     ts.isPropertyAssignment = isPropertyAssignment;
26724     function isShorthandPropertyAssignment(node) {
26725         return node.kind === 289 /* ShorthandPropertyAssignment */;
26726     }
26727     ts.isShorthandPropertyAssignment = isShorthandPropertyAssignment;
26728     function isSpreadAssignment(node) {
26729         return node.kind === 290 /* SpreadAssignment */;
26730     }
26731     ts.isSpreadAssignment = isSpreadAssignment;
26732     // Enum
26733     function isEnumMember(node) {
26734         return node.kind === 291 /* EnumMember */;
26735     }
26736     ts.isEnumMember = isEnumMember;
26737     // Unparsed
26738     // TODO(rbuckton): isUnparsedPrologue
26739     function isUnparsedPrepend(node) {
26740         return node.kind === 293 /* UnparsedPrepend */;
26741     }
26742     ts.isUnparsedPrepend = isUnparsedPrepend;
26743     // TODO(rbuckton): isUnparsedText
26744     // TODO(rbuckton): isUnparsedInternalText
26745     // TODO(rbuckton): isUnparsedSyntheticReference
26746     // Top-level nodes
26747     function isSourceFile(node) {
26748         return node.kind === 297 /* SourceFile */;
26749     }
26750     ts.isSourceFile = isSourceFile;
26751     function isBundle(node) {
26752         return node.kind === 298 /* Bundle */;
26753     }
26754     ts.isBundle = isBundle;
26755     function isUnparsedSource(node) {
26756         return node.kind === 299 /* UnparsedSource */;
26757     }
26758     ts.isUnparsedSource = isUnparsedSource;
26759     // TODO(rbuckton): isInputFiles
26760     // JSDoc Elements
26761     function isJSDocTypeExpression(node) {
26762         return node.kind === 301 /* JSDocTypeExpression */;
26763     }
26764     ts.isJSDocTypeExpression = isJSDocTypeExpression;
26765     function isJSDocNameReference(node) {
26766         return node.kind === 302 /* JSDocNameReference */;
26767     }
26768     ts.isJSDocNameReference = isJSDocNameReference;
26769     function isJSDocAllType(node) {
26770         return node.kind === 303 /* JSDocAllType */;
26771     }
26772     ts.isJSDocAllType = isJSDocAllType;
26773     function isJSDocUnknownType(node) {
26774         return node.kind === 304 /* JSDocUnknownType */;
26775     }
26776     ts.isJSDocUnknownType = isJSDocUnknownType;
26777     function isJSDocNullableType(node) {
26778         return node.kind === 305 /* JSDocNullableType */;
26779     }
26780     ts.isJSDocNullableType = isJSDocNullableType;
26781     function isJSDocNonNullableType(node) {
26782         return node.kind === 306 /* JSDocNonNullableType */;
26783     }
26784     ts.isJSDocNonNullableType = isJSDocNonNullableType;
26785     function isJSDocOptionalType(node) {
26786         return node.kind === 307 /* JSDocOptionalType */;
26787     }
26788     ts.isJSDocOptionalType = isJSDocOptionalType;
26789     function isJSDocFunctionType(node) {
26790         return node.kind === 308 /* JSDocFunctionType */;
26791     }
26792     ts.isJSDocFunctionType = isJSDocFunctionType;
26793     function isJSDocVariadicType(node) {
26794         return node.kind === 309 /* JSDocVariadicType */;
26795     }
26796     ts.isJSDocVariadicType = isJSDocVariadicType;
26797     function isJSDocNamepathType(node) {
26798         return node.kind === 310 /* JSDocNamepathType */;
26799     }
26800     ts.isJSDocNamepathType = isJSDocNamepathType;
26801     function isJSDoc(node) {
26802         return node.kind === 311 /* JSDocComment */;
26803     }
26804     ts.isJSDoc = isJSDoc;
26805     function isJSDocTypeLiteral(node) {
26806         return node.kind === 312 /* JSDocTypeLiteral */;
26807     }
26808     ts.isJSDocTypeLiteral = isJSDocTypeLiteral;
26809     function isJSDocSignature(node) {
26810         return node.kind === 313 /* JSDocSignature */;
26811     }
26812     ts.isJSDocSignature = isJSDocSignature;
26813     // JSDoc Tags
26814     function isJSDocAugmentsTag(node) {
26815         return node.kind === 315 /* JSDocAugmentsTag */;
26816     }
26817     ts.isJSDocAugmentsTag = isJSDocAugmentsTag;
26818     function isJSDocAuthorTag(node) {
26819         return node.kind === 317 /* JSDocAuthorTag */;
26820     }
26821     ts.isJSDocAuthorTag = isJSDocAuthorTag;
26822     function isJSDocClassTag(node) {
26823         return node.kind === 319 /* JSDocClassTag */;
26824     }
26825     ts.isJSDocClassTag = isJSDocClassTag;
26826     function isJSDocCallbackTag(node) {
26827         return node.kind === 324 /* JSDocCallbackTag */;
26828     }
26829     ts.isJSDocCallbackTag = isJSDocCallbackTag;
26830     function isJSDocPublicTag(node) {
26831         return node.kind === 320 /* JSDocPublicTag */;
26832     }
26833     ts.isJSDocPublicTag = isJSDocPublicTag;
26834     function isJSDocPrivateTag(node) {
26835         return node.kind === 321 /* JSDocPrivateTag */;
26836     }
26837     ts.isJSDocPrivateTag = isJSDocPrivateTag;
26838     function isJSDocProtectedTag(node) {
26839         return node.kind === 322 /* JSDocProtectedTag */;
26840     }
26841     ts.isJSDocProtectedTag = isJSDocProtectedTag;
26842     function isJSDocReadonlyTag(node) {
26843         return node.kind === 323 /* JSDocReadonlyTag */;
26844     }
26845     ts.isJSDocReadonlyTag = isJSDocReadonlyTag;
26846     function isJSDocDeprecatedTag(node) {
26847         return node.kind === 318 /* JSDocDeprecatedTag */;
26848     }
26849     ts.isJSDocDeprecatedTag = isJSDocDeprecatedTag;
26850     function isJSDocEnumTag(node) {
26851         return node.kind === 325 /* JSDocEnumTag */;
26852     }
26853     ts.isJSDocEnumTag = isJSDocEnumTag;
26854     function isJSDocParameterTag(node) {
26855         return node.kind === 326 /* JSDocParameterTag */;
26856     }
26857     ts.isJSDocParameterTag = isJSDocParameterTag;
26858     function isJSDocReturnTag(node) {
26859         return node.kind === 327 /* JSDocReturnTag */;
26860     }
26861     ts.isJSDocReturnTag = isJSDocReturnTag;
26862     function isJSDocThisTag(node) {
26863         return node.kind === 328 /* JSDocThisTag */;
26864     }
26865     ts.isJSDocThisTag = isJSDocThisTag;
26866     function isJSDocTypeTag(node) {
26867         return node.kind === 329 /* JSDocTypeTag */;
26868     }
26869     ts.isJSDocTypeTag = isJSDocTypeTag;
26870     function isJSDocTemplateTag(node) {
26871         return node.kind === 330 /* JSDocTemplateTag */;
26872     }
26873     ts.isJSDocTemplateTag = isJSDocTemplateTag;
26874     function isJSDocTypedefTag(node) {
26875         return node.kind === 331 /* JSDocTypedefTag */;
26876     }
26877     ts.isJSDocTypedefTag = isJSDocTypedefTag;
26878     function isJSDocUnknownTag(node) {
26879         return node.kind === 314 /* JSDocTag */;
26880     }
26881     ts.isJSDocUnknownTag = isJSDocUnknownTag;
26882     function isJSDocPropertyTag(node) {
26883         return node.kind === 333 /* JSDocPropertyTag */;
26884     }
26885     ts.isJSDocPropertyTag = isJSDocPropertyTag;
26886     function isJSDocImplementsTag(node) {
26887         return node.kind === 316 /* JSDocImplementsTag */;
26888     }
26889     ts.isJSDocImplementsTag = isJSDocImplementsTag;
26890     // Synthesized list
26891     /* @internal */
26892     function isSyntaxList(n) {
26893         return n.kind === 334 /* SyntaxList */;
26894     }
26895     ts.isSyntaxList = isSyntaxList;
26896 })(ts || (ts = {}));
26897 /* @internal */
26898 var ts;
26899 (function (ts) {
26900     // Compound nodes
26901     function createEmptyExports(factory) {
26902         return factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, factory.createNamedExports([]), /*moduleSpecifier*/ undefined);
26903     }
26904     ts.createEmptyExports = createEmptyExports;
26905     function createMemberAccessForPropertyName(factory, target, memberName, location) {
26906         if (ts.isComputedPropertyName(memberName)) {
26907             return ts.setTextRange(factory.createElementAccessExpression(target, memberName.expression), location);
26908         }
26909         else {
26910             var expression = ts.setTextRange(ts.isIdentifierOrPrivateIdentifier(memberName)
26911                 ? factory.createPropertyAccessExpression(target, memberName)
26912                 : factory.createElementAccessExpression(target, memberName), memberName);
26913             ts.getOrCreateEmitNode(expression).flags |= 64 /* NoNestedSourceMaps */;
26914             return expression;
26915         }
26916     }
26917     ts.createMemberAccessForPropertyName = createMemberAccessForPropertyName;
26918     function createReactNamespace(reactNamespace, parent) {
26919         // To ensure the emit resolver can properly resolve the namespace, we need to
26920         // treat this identifier as if it were a source tree node by clearing the `Synthesized`
26921         // flag and setting a parent node.
26922         var react = ts.parseNodeFactory.createIdentifier(reactNamespace || "React");
26923         // Set the parent that is in parse tree
26924         // this makes sure that parent chain is intact for checker to traverse complete scope tree
26925         ts.setParent(react, ts.getParseTreeNode(parent));
26926         return react;
26927     }
26928     function createJsxFactoryExpressionFromEntityName(factory, jsxFactory, parent) {
26929         if (ts.isQualifiedName(jsxFactory)) {
26930             var left = createJsxFactoryExpressionFromEntityName(factory, jsxFactory.left, parent);
26931             var right = factory.createIdentifier(ts.idText(jsxFactory.right));
26932             right.escapedText = jsxFactory.right.escapedText;
26933             return factory.createPropertyAccessExpression(left, right);
26934         }
26935         else {
26936             return createReactNamespace(ts.idText(jsxFactory), parent);
26937         }
26938     }
26939     function createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parent) {
26940         return jsxFactoryEntity ?
26941             createJsxFactoryExpressionFromEntityName(factory, jsxFactoryEntity, parent) :
26942             factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "createElement");
26943     }
26944     ts.createJsxFactoryExpression = createJsxFactoryExpression;
26945     function createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parent) {
26946         return jsxFragmentFactoryEntity ?
26947             createJsxFactoryExpressionFromEntityName(factory, jsxFragmentFactoryEntity, parent) :
26948             factory.createPropertyAccessExpression(createReactNamespace(reactNamespace, parent), "Fragment");
26949     }
26950     function createExpressionForJsxElement(factory, callee, tagName, props, children, location) {
26951         var argumentsList = [tagName];
26952         if (props) {
26953             argumentsList.push(props);
26954         }
26955         if (children && children.length > 0) {
26956             if (!props) {
26957                 argumentsList.push(factory.createNull());
26958             }
26959             if (children.length > 1) {
26960                 for (var _i = 0, children_3 = children; _i < children_3.length; _i++) {
26961                     var child = children_3[_i];
26962                     startOnNewLine(child);
26963                     argumentsList.push(child);
26964                 }
26965             }
26966             else {
26967                 argumentsList.push(children[0]);
26968             }
26969         }
26970         return ts.setTextRange(factory.createCallExpression(callee, 
26971         /*typeArguments*/ undefined, argumentsList), location);
26972     }
26973     ts.createExpressionForJsxElement = createExpressionForJsxElement;
26974     function createExpressionForJsxFragment(factory, jsxFactoryEntity, jsxFragmentFactoryEntity, reactNamespace, children, parentElement, location) {
26975         var tagName = createJsxFragmentFactoryExpression(factory, jsxFragmentFactoryEntity, reactNamespace, parentElement);
26976         var argumentsList = [tagName, factory.createNull()];
26977         if (children && children.length > 0) {
26978             if (children.length > 1) {
26979                 for (var _i = 0, children_4 = children; _i < children_4.length; _i++) {
26980                     var child = children_4[_i];
26981                     startOnNewLine(child);
26982                     argumentsList.push(child);
26983                 }
26984             }
26985             else {
26986                 argumentsList.push(children[0]);
26987             }
26988         }
26989         return ts.setTextRange(factory.createCallExpression(createJsxFactoryExpression(factory, jsxFactoryEntity, reactNamespace, parentElement), 
26990         /*typeArguments*/ undefined, argumentsList), location);
26991     }
26992     ts.createExpressionForJsxFragment = createExpressionForJsxFragment;
26993     // Utilities
26994     function createForOfBindingStatement(factory, node, boundValue) {
26995         if (ts.isVariableDeclarationList(node)) {
26996             var firstDeclaration = ts.first(node.declarations);
26997             var updatedDeclaration = factory.updateVariableDeclaration(firstDeclaration, firstDeclaration.name, 
26998             /*exclamationToken*/ undefined, 
26999             /*type*/ undefined, boundValue);
27000             return ts.setTextRange(factory.createVariableStatement(
27001             /*modifiers*/ undefined, factory.updateVariableDeclarationList(node, [updatedDeclaration])), 
27002             /*location*/ node);
27003         }
27004         else {
27005             var updatedExpression = ts.setTextRange(factory.createAssignment(node, boundValue), /*location*/ node);
27006             return ts.setTextRange(factory.createExpressionStatement(updatedExpression), /*location*/ node);
27007         }
27008     }
27009     ts.createForOfBindingStatement = createForOfBindingStatement;
27010     function insertLeadingStatement(factory, dest, source) {
27011         if (ts.isBlock(dest)) {
27012             return factory.updateBlock(dest, ts.setTextRange(factory.createNodeArray(__spreadArrays([source], dest.statements)), dest.statements));
27013         }
27014         else {
27015             return factory.createBlock(factory.createNodeArray([dest, source]), /*multiLine*/ true);
27016         }
27017     }
27018     ts.insertLeadingStatement = insertLeadingStatement;
27019     function createExpressionFromEntityName(factory, node) {
27020         if (ts.isQualifiedName(node)) {
27021             var left = createExpressionFromEntityName(factory, node.left);
27022             // TODO(rbuckton): Does this need to be parented?
27023             var right = ts.setParent(ts.setTextRange(factory.cloneNode(node.right), node.right), node.right.parent);
27024             return ts.setTextRange(factory.createPropertyAccessExpression(left, right), node);
27025         }
27026         else {
27027             // TODO(rbuckton): Does this need to be parented?
27028             return ts.setParent(ts.setTextRange(factory.cloneNode(node), node), node.parent);
27029         }
27030     }
27031     ts.createExpressionFromEntityName = createExpressionFromEntityName;
27032     function createExpressionForPropertyName(factory, memberName) {
27033         if (ts.isIdentifier(memberName)) {
27034             return factory.createStringLiteralFromNode(memberName);
27035         }
27036         else if (ts.isComputedPropertyName(memberName)) {
27037             // TODO(rbuckton): Does this need to be parented?
27038             return ts.setParent(ts.setTextRange(factory.cloneNode(memberName.expression), memberName.expression), memberName.expression.parent);
27039         }
27040         else {
27041             // TODO(rbuckton): Does this need to be parented?
27042             return ts.setParent(ts.setTextRange(factory.cloneNode(memberName), memberName), memberName.parent);
27043         }
27044     }
27045     ts.createExpressionForPropertyName = createExpressionForPropertyName;
27046     function createExpressionForAccessorDeclaration(factory, properties, property, receiver, multiLine) {
27047         var _a = ts.getAllAccessorDeclarations(properties, property), firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
27048         if (property === firstAccessor) {
27049             return ts.setTextRange(factory.createObjectDefinePropertyCall(receiver, createExpressionForPropertyName(factory, property.name), factory.createPropertyDescriptor({
27050                 enumerable: factory.createFalse(),
27051                 configurable: true,
27052                 get: getAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(getAccessor.modifiers, 
27053                 /*asteriskToken*/ undefined, 
27054                 /*name*/ undefined, 
27055                 /*typeParameters*/ undefined, getAccessor.parameters, 
27056                 /*type*/ undefined, getAccessor.body // TODO: GH#18217
27057                 ), getAccessor), getAccessor),
27058                 set: setAccessor && ts.setTextRange(ts.setOriginalNode(factory.createFunctionExpression(setAccessor.modifiers, 
27059                 /*asteriskToken*/ undefined, 
27060                 /*name*/ undefined, 
27061                 /*typeParameters*/ undefined, setAccessor.parameters, 
27062                 /*type*/ undefined, setAccessor.body // TODO: GH#18217
27063                 ), setAccessor), setAccessor)
27064             }, !multiLine)), firstAccessor);
27065         }
27066         return undefined;
27067     }
27068     function createExpressionForPropertyAssignment(factory, property, receiver) {
27069         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), property.initializer), property), property);
27070     }
27071     function createExpressionForShorthandPropertyAssignment(factory, property, receiver) {
27072         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, property.name, /*location*/ property.name), factory.cloneNode(property.name)), 
27073         /*location*/ property), 
27074         /*original*/ property);
27075     }
27076     function createExpressionForMethodDeclaration(factory, method, receiver) {
27077         return ts.setOriginalNode(ts.setTextRange(factory.createAssignment(createMemberAccessForPropertyName(factory, receiver, method.name, /*location*/ method.name), ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(method.modifiers, method.asteriskToken, 
27078         /*name*/ undefined, 
27079         /*typeParameters*/ undefined, method.parameters, 
27080         /*type*/ undefined, method.body // TODO: GH#18217
27081         ), 
27082         /*location*/ method), 
27083         /*original*/ method)), 
27084         /*location*/ method), 
27085         /*original*/ method);
27086     }
27087     function createExpressionForObjectLiteralElementLike(factory, node, property, receiver) {
27088         if (property.name && ts.isPrivateIdentifier(property.name)) {
27089             ts.Debug.failBadSyntaxKind(property.name, "Private identifiers are not allowed in object literals.");
27090         }
27091         switch (property.kind) {
27092             case 167 /* GetAccessor */:
27093             case 168 /* SetAccessor */:
27094                 return createExpressionForAccessorDeclaration(factory, node.properties, property, receiver, !!node.multiLine);
27095             case 288 /* PropertyAssignment */:
27096                 return createExpressionForPropertyAssignment(factory, property, receiver);
27097             case 289 /* ShorthandPropertyAssignment */:
27098                 return createExpressionForShorthandPropertyAssignment(factory, property, receiver);
27099             case 165 /* MethodDeclaration */:
27100                 return createExpressionForMethodDeclaration(factory, property, receiver);
27101         }
27102     }
27103     ts.createExpressionForObjectLiteralElementLike = createExpressionForObjectLiteralElementLike;
27104     /**
27105      * Gets whether an identifier should only be referred to by its internal name.
27106      */
27107     function isInternalName(node) {
27108         return (ts.getEmitFlags(node) & 32768 /* InternalName */) !== 0;
27109     }
27110     ts.isInternalName = isInternalName;
27111     /**
27112      * Gets whether an identifier should only be referred to by its local name.
27113      */
27114     function isLocalName(node) {
27115         return (ts.getEmitFlags(node) & 16384 /* LocalName */) !== 0;
27116     }
27117     ts.isLocalName = isLocalName;
27118     /**
27119      * Gets whether an identifier should only be referred to by its export representation if the
27120      * name points to an exported symbol.
27121      */
27122     function isExportName(node) {
27123         return (ts.getEmitFlags(node) & 8192 /* ExportName */) !== 0;
27124     }
27125     ts.isExportName = isExportName;
27126     function isUseStrictPrologue(node) {
27127         return ts.isStringLiteral(node.expression) && node.expression.text === "use strict";
27128     }
27129     function findUseStrictPrologue(statements) {
27130         for (var _i = 0, statements_1 = statements; _i < statements_1.length; _i++) {
27131             var statement = statements_1[_i];
27132             if (ts.isPrologueDirective(statement)) {
27133                 if (isUseStrictPrologue(statement)) {
27134                     return statement;
27135                 }
27136             }
27137             else {
27138                 break;
27139             }
27140         }
27141         return undefined;
27142     }
27143     ts.findUseStrictPrologue = findUseStrictPrologue;
27144     function startsWithUseStrict(statements) {
27145         var firstStatement = ts.firstOrUndefined(statements);
27146         return firstStatement !== undefined
27147             && ts.isPrologueDirective(firstStatement)
27148             && isUseStrictPrologue(firstStatement);
27149     }
27150     ts.startsWithUseStrict = startsWithUseStrict;
27151     function isCommaSequence(node) {
27152         return node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 27 /* CommaToken */ ||
27153             node.kind === 337 /* CommaListExpression */;
27154     }
27155     ts.isCommaSequence = isCommaSequence;
27156     function isOuterExpression(node, kinds) {
27157         if (kinds === void 0) { kinds = 15 /* All */; }
27158         switch (node.kind) {
27159             case 207 /* ParenthesizedExpression */:
27160                 return (kinds & 1 /* Parentheses */) !== 0;
27161             case 206 /* TypeAssertionExpression */:
27162             case 224 /* AsExpression */:
27163                 return (kinds & 2 /* TypeAssertions */) !== 0;
27164             case 225 /* NonNullExpression */:
27165                 return (kinds & 4 /* NonNullAssertions */) !== 0;
27166             case 336 /* PartiallyEmittedExpression */:
27167                 return (kinds & 8 /* PartiallyEmittedExpressions */) !== 0;
27168         }
27169         return false;
27170     }
27171     ts.isOuterExpression = isOuterExpression;
27172     function skipOuterExpressions(node, kinds) {
27173         if (kinds === void 0) { kinds = 15 /* All */; }
27174         while (isOuterExpression(node, kinds)) {
27175             node = node.expression;
27176         }
27177         return node;
27178     }
27179     ts.skipOuterExpressions = skipOuterExpressions;
27180     function skipAssertions(node) {
27181         return skipOuterExpressions(node, 6 /* Assertions */);
27182     }
27183     ts.skipAssertions = skipAssertions;
27184     function startOnNewLine(node) {
27185         return ts.setStartsOnNewLine(node, /*newLine*/ true);
27186     }
27187     ts.startOnNewLine = startOnNewLine;
27188     function getExternalHelpersModuleName(node) {
27189         var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
27190         var emitNode = parseNode && parseNode.emitNode;
27191         return emitNode && emitNode.externalHelpersModuleName;
27192     }
27193     ts.getExternalHelpersModuleName = getExternalHelpersModuleName;
27194     function hasRecordedExternalHelpers(sourceFile) {
27195         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
27196         var emitNode = parseNode && parseNode.emitNode;
27197         return !!emitNode && (!!emitNode.externalHelpersModuleName || !!emitNode.externalHelpers);
27198     }
27199     ts.hasRecordedExternalHelpers = hasRecordedExternalHelpers;
27200     function createExternalHelpersImportDeclarationIfNeeded(nodeFactory, helperFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault) {
27201         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
27202             var namedBindings = void 0;
27203             var moduleKind = ts.getEmitModuleKind(compilerOptions);
27204             if (moduleKind >= ts.ModuleKind.ES2015 && moduleKind <= ts.ModuleKind.ESNext) {
27205                 // use named imports
27206                 var helpers = ts.getEmitHelpers(sourceFile);
27207                 if (helpers) {
27208                     var helperNames = [];
27209                     for (var _i = 0, helpers_3 = helpers; _i < helpers_3.length; _i++) {
27210                         var helper = helpers_3[_i];
27211                         if (!helper.scoped) {
27212                             var importName = helper.importName;
27213                             if (importName) {
27214                                 ts.pushIfUnique(helperNames, importName);
27215                             }
27216                         }
27217                     }
27218                     if (ts.some(helperNames)) {
27219                         helperNames.sort(ts.compareStringsCaseSensitive);
27220                         // Alias the imports if the names are used somewhere in the file.
27221                         // NOTE: We don't need to care about global import collisions as this is a module.
27222                         namedBindings = nodeFactory.createNamedImports(ts.map(helperNames, function (name) { return ts.isFileLevelUniqueName(sourceFile, name)
27223                             ? nodeFactory.createImportSpecifier(/*propertyName*/ undefined, nodeFactory.createIdentifier(name))
27224                             : nodeFactory.createImportSpecifier(nodeFactory.createIdentifier(name), helperFactory.getUnscopedHelperName(name)); }));
27225                         var parseNode = ts.getOriginalNode(sourceFile, ts.isSourceFile);
27226                         var emitNode = ts.getOrCreateEmitNode(parseNode);
27227                         emitNode.externalHelpers = true;
27228                     }
27229                 }
27230             }
27231             else {
27232                 // use a namespace import
27233                 var externalHelpersModuleName = getOrCreateExternalHelpersModuleNameIfNeeded(nodeFactory, sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar || hasImportDefault);
27234                 if (externalHelpersModuleName) {
27235                     namedBindings = nodeFactory.createNamespaceImport(externalHelpersModuleName);
27236                 }
27237             }
27238             if (namedBindings) {
27239                 var externalHelpersImportDeclaration = nodeFactory.createImportDeclaration(
27240                 /*decorators*/ undefined, 
27241                 /*modifiers*/ undefined, nodeFactory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, namedBindings), nodeFactory.createStringLiteral(ts.externalHelpersModuleNameText));
27242                 ts.addEmitFlags(externalHelpersImportDeclaration, 67108864 /* NeverApplyImportHelper */);
27243                 return externalHelpersImportDeclaration;
27244             }
27245         }
27246     }
27247     ts.createExternalHelpersImportDeclarationIfNeeded = createExternalHelpersImportDeclarationIfNeeded;
27248     function getOrCreateExternalHelpersModuleNameIfNeeded(factory, node, compilerOptions, hasExportStarsToExportValues, hasImportStarOrImportDefault) {
27249         if (compilerOptions.importHelpers && ts.isEffectiveExternalModule(node, compilerOptions)) {
27250             var externalHelpersModuleName = getExternalHelpersModuleName(node);
27251             if (externalHelpersModuleName) {
27252                 return externalHelpersModuleName;
27253             }
27254             var moduleKind = ts.getEmitModuleKind(compilerOptions);
27255             var create = (hasExportStarsToExportValues || (compilerOptions.esModuleInterop && hasImportStarOrImportDefault))
27256                 && moduleKind !== ts.ModuleKind.System
27257                 && moduleKind < ts.ModuleKind.ES2015;
27258             if (!create) {
27259                 var helpers = ts.getEmitHelpers(node);
27260                 if (helpers) {
27261                     for (var _i = 0, helpers_4 = helpers; _i < helpers_4.length; _i++) {
27262                         var helper = helpers_4[_i];
27263                         if (!helper.scoped) {
27264                             create = true;
27265                             break;
27266                         }
27267                     }
27268                 }
27269             }
27270             if (create) {
27271                 var parseNode = ts.getOriginalNode(node, ts.isSourceFile);
27272                 var emitNode = ts.getOrCreateEmitNode(parseNode);
27273                 return emitNode.externalHelpersModuleName || (emitNode.externalHelpersModuleName = factory.createUniqueName(ts.externalHelpersModuleNameText));
27274             }
27275         }
27276     }
27277     ts.getOrCreateExternalHelpersModuleNameIfNeeded = getOrCreateExternalHelpersModuleNameIfNeeded;
27278     /**
27279      * Get the name of that target module from an import or export declaration
27280      */
27281     function getLocalNameForExternalImport(factory, node, sourceFile) {
27282         var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
27283         if (namespaceDeclaration && !ts.isDefaultImport(node) && !ts.isExportNamespaceAsDefaultDeclaration(node)) {
27284             var name = namespaceDeclaration.name;
27285             return ts.isGeneratedIdentifier(name) ? name : factory.createIdentifier(ts.getSourceTextOfNodeFromSourceFile(sourceFile, name) || ts.idText(name));
27286         }
27287         if (node.kind === 261 /* ImportDeclaration */ && node.importClause) {
27288             return factory.getGeneratedNameForNode(node);
27289         }
27290         if (node.kind === 267 /* ExportDeclaration */ && node.moduleSpecifier) {
27291             return factory.getGeneratedNameForNode(node);
27292         }
27293         return undefined;
27294     }
27295     ts.getLocalNameForExternalImport = getLocalNameForExternalImport;
27296     /**
27297      * Get the name of a target module from an import/export declaration as should be written in the emitted output.
27298      * The emitted output name can be different from the input if:
27299      *  1. The module has a /// <amd-module name="<new name>" />
27300      *  2. --out or --outFile is used, making the name relative to the rootDir
27301      *  3- The containing SourceFile has an entry in renamedDependencies for the import as requested by some module loaders (e.g. System).
27302      * Otherwise, a new StringLiteral node representing the module name will be returned.
27303      */
27304     function getExternalModuleNameLiteral(factory, importNode, sourceFile, host, resolver, compilerOptions) {
27305         var moduleName = ts.getExternalModuleName(importNode); // TODO: GH#18217
27306         if (moduleName.kind === 10 /* StringLiteral */) {
27307             return tryGetModuleNameFromDeclaration(importNode, host, factory, resolver, compilerOptions)
27308                 || tryRenameExternalModule(factory, moduleName, sourceFile)
27309                 || factory.cloneNode(moduleName);
27310         }
27311         return undefined;
27312     }
27313     ts.getExternalModuleNameLiteral = getExternalModuleNameLiteral;
27314     /**
27315      * Some bundlers (SystemJS builder) sometimes want to rename dependencies.
27316      * Here we check if alternative name was provided for a given moduleName and return it if possible.
27317      */
27318     function tryRenameExternalModule(factory, moduleName, sourceFile) {
27319         var rename = sourceFile.renamedDependencies && sourceFile.renamedDependencies.get(moduleName.text);
27320         return rename && factory.createStringLiteral(rename);
27321     }
27322     /**
27323      * Get the name of a module as should be written in the emitted output.
27324      * The emitted output name can be different from the input if:
27325      *  1. The module has a /// <amd-module name="<new name>" />
27326      *  2. --out or --outFile is used, making the name relative to the rootDir
27327      * Otherwise, a new StringLiteral node representing the module name will be returned.
27328      */
27329     function tryGetModuleNameFromFile(factory, file, host, options) {
27330         if (!file) {
27331             return undefined;
27332         }
27333         if (file.moduleName) {
27334             return factory.createStringLiteral(file.moduleName);
27335         }
27336         if (!file.isDeclarationFile && ts.outFile(options)) {
27337             return factory.createStringLiteral(ts.getExternalModuleNameFromPath(host, file.fileName));
27338         }
27339         return undefined;
27340     }
27341     ts.tryGetModuleNameFromFile = tryGetModuleNameFromFile;
27342     function tryGetModuleNameFromDeclaration(declaration, host, factory, resolver, compilerOptions) {
27343         return tryGetModuleNameFromFile(factory, resolver.getExternalModuleFileFromDeclaration(declaration), host, compilerOptions);
27344     }
27345     /**
27346      * Gets the initializer of an BindingOrAssignmentElement.
27347      */
27348     function getInitializerOfBindingOrAssignmentElement(bindingElement) {
27349         if (ts.isDeclarationBindingElement(bindingElement)) {
27350             // `1` in `let { a = 1 } = ...`
27351             // `1` in `let { a: b = 1 } = ...`
27352             // `1` in `let { a: {b} = 1 } = ...`
27353             // `1` in `let { a: [b] = 1 } = ...`
27354             // `1` in `let [a = 1] = ...`
27355             // `1` in `let [{a} = 1] = ...`
27356             // `1` in `let [[a] = 1] = ...`
27357             return bindingElement.initializer;
27358         }
27359         if (ts.isPropertyAssignment(bindingElement)) {
27360             // `1` in `({ a: b = 1 } = ...)`
27361             // `1` in `({ a: {b} = 1 } = ...)`
27362             // `1` in `({ a: [b] = 1 } = ...)`
27363             var initializer = bindingElement.initializer;
27364             return ts.isAssignmentExpression(initializer, /*excludeCompoundAssignment*/ true)
27365                 ? initializer.right
27366                 : undefined;
27367         }
27368         if (ts.isShorthandPropertyAssignment(bindingElement)) {
27369             // `1` in `({ a = 1 } = ...)`
27370             return bindingElement.objectAssignmentInitializer;
27371         }
27372         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
27373             // `1` in `[a = 1] = ...`
27374             // `1` in `[{a} = 1] = ...`
27375             // `1` in `[[a] = 1] = ...`
27376             return bindingElement.right;
27377         }
27378         if (ts.isSpreadElement(bindingElement)) {
27379             // Recovery consistent with existing emit.
27380             return getInitializerOfBindingOrAssignmentElement(bindingElement.expression);
27381         }
27382     }
27383     ts.getInitializerOfBindingOrAssignmentElement = getInitializerOfBindingOrAssignmentElement;
27384     /**
27385      * Gets the name of an BindingOrAssignmentElement.
27386      */
27387     function getTargetOfBindingOrAssignmentElement(bindingElement) {
27388         if (ts.isDeclarationBindingElement(bindingElement)) {
27389             // `a` in `let { a } = ...`
27390             // `a` in `let { a = 1 } = ...`
27391             // `b` in `let { a: b } = ...`
27392             // `b` in `let { a: b = 1 } = ...`
27393             // `a` in `let { ...a } = ...`
27394             // `{b}` in `let { a: {b} } = ...`
27395             // `{b}` in `let { a: {b} = 1 } = ...`
27396             // `[b]` in `let { a: [b] } = ...`
27397             // `[b]` in `let { a: [b] = 1 } = ...`
27398             // `a` in `let [a] = ...`
27399             // `a` in `let [a = 1] = ...`
27400             // `a` in `let [...a] = ...`
27401             // `{a}` in `let [{a}] = ...`
27402             // `{a}` in `let [{a} = 1] = ...`
27403             // `[a]` in `let [[a]] = ...`
27404             // `[a]` in `let [[a] = 1] = ...`
27405             return bindingElement.name;
27406         }
27407         if (ts.isObjectLiteralElementLike(bindingElement)) {
27408             switch (bindingElement.kind) {
27409                 case 288 /* PropertyAssignment */:
27410                     // `b` in `({ a: b } = ...)`
27411                     // `b` in `({ a: b = 1 } = ...)`
27412                     // `{b}` in `({ a: {b} } = ...)`
27413                     // `{b}` in `({ a: {b} = 1 } = ...)`
27414                     // `[b]` in `({ a: [b] } = ...)`
27415                     // `[b]` in `({ a: [b] = 1 } = ...)`
27416                     // `b.c` in `({ a: b.c } = ...)`
27417                     // `b.c` in `({ a: b.c = 1 } = ...)`
27418                     // `b[0]` in `({ a: b[0] } = ...)`
27419                     // `b[0]` in `({ a: b[0] = 1 } = ...)`
27420                     return getTargetOfBindingOrAssignmentElement(bindingElement.initializer);
27421                 case 289 /* ShorthandPropertyAssignment */:
27422                     // `a` in `({ a } = ...)`
27423                     // `a` in `({ a = 1 } = ...)`
27424                     return bindingElement.name;
27425                 case 290 /* SpreadAssignment */:
27426                     // `a` in `({ ...a } = ...)`
27427                     return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
27428             }
27429             // no target
27430             return undefined;
27431         }
27432         if (ts.isAssignmentExpression(bindingElement, /*excludeCompoundAssignment*/ true)) {
27433             // `a` in `[a = 1] = ...`
27434             // `{a}` in `[{a} = 1] = ...`
27435             // `[a]` in `[[a] = 1] = ...`
27436             // `a.b` in `[a.b = 1] = ...`
27437             // `a[0]` in `[a[0] = 1] = ...`
27438             return getTargetOfBindingOrAssignmentElement(bindingElement.left);
27439         }
27440         if (ts.isSpreadElement(bindingElement)) {
27441             // `a` in `[...a] = ...`
27442             return getTargetOfBindingOrAssignmentElement(bindingElement.expression);
27443         }
27444         // `a` in `[a] = ...`
27445         // `{a}` in `[{a}] = ...`
27446         // `[a]` in `[[a]] = ...`
27447         // `a.b` in `[a.b] = ...`
27448         // `a[0]` in `[a[0]] = ...`
27449         return bindingElement;
27450     }
27451     ts.getTargetOfBindingOrAssignmentElement = getTargetOfBindingOrAssignmentElement;
27452     /**
27453      * Determines whether an BindingOrAssignmentElement is a rest element.
27454      */
27455     function getRestIndicatorOfBindingOrAssignmentElement(bindingElement) {
27456         switch (bindingElement.kind) {
27457             case 160 /* Parameter */:
27458             case 198 /* BindingElement */:
27459                 // `...` in `let [...a] = ...`
27460                 return bindingElement.dotDotDotToken;
27461             case 220 /* SpreadElement */:
27462             case 290 /* SpreadAssignment */:
27463                 // `...` in `[...a] = ...`
27464                 return bindingElement;
27465         }
27466         return undefined;
27467     }
27468     ts.getRestIndicatorOfBindingOrAssignmentElement = getRestIndicatorOfBindingOrAssignmentElement;
27469     /**
27470      * Gets the property name of a BindingOrAssignmentElement
27471      */
27472     function getPropertyNameOfBindingOrAssignmentElement(bindingElement) {
27473         var propertyName = tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement);
27474         ts.Debug.assert(!!propertyName || ts.isSpreadAssignment(bindingElement), "Invalid property name for binding element.");
27475         return propertyName;
27476     }
27477     ts.getPropertyNameOfBindingOrAssignmentElement = getPropertyNameOfBindingOrAssignmentElement;
27478     function tryGetPropertyNameOfBindingOrAssignmentElement(bindingElement) {
27479         switch (bindingElement.kind) {
27480             case 198 /* BindingElement */:
27481                 // `a` in `let { a: b } = ...`
27482                 // `[a]` in `let { [a]: b } = ...`
27483                 // `"a"` in `let { "a": b } = ...`
27484                 // `1` in `let { 1: b } = ...`
27485                 if (bindingElement.propertyName) {
27486                     var propertyName = bindingElement.propertyName;
27487                     if (ts.isPrivateIdentifier(propertyName)) {
27488                         return ts.Debug.failBadSyntaxKind(propertyName);
27489                     }
27490                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
27491                         ? propertyName.expression
27492                         : propertyName;
27493                 }
27494                 break;
27495             case 288 /* PropertyAssignment */:
27496                 // `a` in `({ a: b } = ...)`
27497                 // `[a]` in `({ [a]: b } = ...)`
27498                 // `"a"` in `({ "a": b } = ...)`
27499                 // `1` in `({ 1: b } = ...)`
27500                 if (bindingElement.name) {
27501                     var propertyName = bindingElement.name;
27502                     if (ts.isPrivateIdentifier(propertyName)) {
27503                         return ts.Debug.failBadSyntaxKind(propertyName);
27504                     }
27505                     return ts.isComputedPropertyName(propertyName) && isStringOrNumericLiteral(propertyName.expression)
27506                         ? propertyName.expression
27507                         : propertyName;
27508                 }
27509                 break;
27510             case 290 /* SpreadAssignment */:
27511                 // `a` in `({ ...a } = ...)`
27512                 if (bindingElement.name && ts.isPrivateIdentifier(bindingElement.name)) {
27513                     return ts.Debug.failBadSyntaxKind(bindingElement.name);
27514                 }
27515                 return bindingElement.name;
27516         }
27517         var target = getTargetOfBindingOrAssignmentElement(bindingElement);
27518         if (target && ts.isPropertyName(target)) {
27519             return target;
27520         }
27521     }
27522     ts.tryGetPropertyNameOfBindingOrAssignmentElement = tryGetPropertyNameOfBindingOrAssignmentElement;
27523     function isStringOrNumericLiteral(node) {
27524         var kind = node.kind;
27525         return kind === 10 /* StringLiteral */
27526             || kind === 8 /* NumericLiteral */;
27527     }
27528     /**
27529      * Gets the elements of a BindingOrAssignmentPattern
27530      */
27531     function getElementsOfBindingOrAssignmentPattern(name) {
27532         switch (name.kind) {
27533             case 196 /* ObjectBindingPattern */:
27534             case 197 /* ArrayBindingPattern */:
27535             case 199 /* ArrayLiteralExpression */:
27536                 // `a` in `{a}`
27537                 // `a` in `[a]`
27538                 return name.elements;
27539             case 200 /* ObjectLiteralExpression */:
27540                 // `a` in `{a}`
27541                 return name.properties;
27542         }
27543     }
27544     ts.getElementsOfBindingOrAssignmentPattern = getElementsOfBindingOrAssignmentPattern;
27545     /* @internal */
27546     function getJSDocTypeAliasName(fullName) {
27547         if (fullName) {
27548             var rightNode = fullName;
27549             while (true) {
27550                 if (ts.isIdentifier(rightNode) || !rightNode.body) {
27551                     return ts.isIdentifier(rightNode) ? rightNode : rightNode.name;
27552                 }
27553                 rightNode = rightNode.body;
27554             }
27555         }
27556     }
27557     ts.getJSDocTypeAliasName = getJSDocTypeAliasName;
27558     function canHaveModifiers(node) {
27559         var kind = node.kind;
27560         return kind === 160 /* Parameter */
27561             || kind === 162 /* PropertySignature */
27562             || kind === 163 /* PropertyDeclaration */
27563             || kind === 164 /* MethodSignature */
27564             || kind === 165 /* MethodDeclaration */
27565             || kind === 166 /* Constructor */
27566             || kind === 167 /* GetAccessor */
27567             || kind === 168 /* SetAccessor */
27568             || kind === 171 /* IndexSignature */
27569             || kind === 208 /* FunctionExpression */
27570             || kind === 209 /* ArrowFunction */
27571             || kind === 221 /* ClassExpression */
27572             || kind === 232 /* VariableStatement */
27573             || kind === 251 /* FunctionDeclaration */
27574             || kind === 252 /* ClassDeclaration */
27575             || kind === 253 /* InterfaceDeclaration */
27576             || kind === 254 /* TypeAliasDeclaration */
27577             || kind === 255 /* EnumDeclaration */
27578             || kind === 256 /* ModuleDeclaration */
27579             || kind === 260 /* ImportEqualsDeclaration */
27580             || kind === 261 /* ImportDeclaration */
27581             || kind === 266 /* ExportAssignment */
27582             || kind === 267 /* ExportDeclaration */;
27583     }
27584     ts.canHaveModifiers = canHaveModifiers;
27585     /* @internal */
27586     function isExportModifier(node) {
27587         return node.kind === 92 /* ExportKeyword */;
27588     }
27589     ts.isExportModifier = isExportModifier;
27590     /* @internal */
27591     function isAsyncModifier(node) {
27592         return node.kind === 129 /* AsyncKeyword */;
27593     }
27594     ts.isAsyncModifier = isAsyncModifier;
27595     /* @internal */
27596     function isStaticModifier(node) {
27597         return node.kind === 123 /* StaticKeyword */;
27598     }
27599     ts.isStaticModifier = isStaticModifier;
27600 })(ts || (ts = {}));
27601 var ts;
27602 (function (ts) {
27603     function setTextRange(range, location) {
27604         return location ? ts.setTextRangePosEnd(range, location.pos, location.end) : range;
27605     }
27606     ts.setTextRange = setTextRange;
27607 })(ts || (ts = {}));
27608 var ts;
27609 (function (ts) {
27610     var SignatureFlags;
27611     (function (SignatureFlags) {
27612         SignatureFlags[SignatureFlags["None"] = 0] = "None";
27613         SignatureFlags[SignatureFlags["Yield"] = 1] = "Yield";
27614         SignatureFlags[SignatureFlags["Await"] = 2] = "Await";
27615         SignatureFlags[SignatureFlags["Type"] = 4] = "Type";
27616         SignatureFlags[SignatureFlags["IgnoreMissingOpenBrace"] = 16] = "IgnoreMissingOpenBrace";
27617         SignatureFlags[SignatureFlags["JSDoc"] = 32] = "JSDoc";
27618     })(SignatureFlags || (SignatureFlags = {}));
27619     var SpeculationKind;
27620     (function (SpeculationKind) {
27621         SpeculationKind[SpeculationKind["TryParse"] = 0] = "TryParse";
27622         SpeculationKind[SpeculationKind["Lookahead"] = 1] = "Lookahead";
27623         SpeculationKind[SpeculationKind["Reparse"] = 2] = "Reparse";
27624     })(SpeculationKind || (SpeculationKind = {}));
27625     var NodeConstructor;
27626     var TokenConstructor;
27627     var IdentifierConstructor;
27628     var PrivateIdentifierConstructor;
27629     var SourceFileConstructor;
27630     /**
27631      * NOTE: You should not use this, it is only exported to support `createNode` in `~/src/compat/deprecations.ts`.
27632      */
27633     /* @internal */
27634     ts.parseBaseNodeFactory = {
27635         createBaseSourceFileNode: function (kind) { return new (SourceFileConstructor || (SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor()))(kind, -1, -1); },
27636         createBaseIdentifierNode: function (kind) { return new (IdentifierConstructor || (IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor()))(kind, -1, -1); },
27637         createBasePrivateIdentifierNode: function (kind) { return new (PrivateIdentifierConstructor || (PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor()))(kind, -1, -1); },
27638         createBaseTokenNode: function (kind) { return new (TokenConstructor || (TokenConstructor = ts.objectAllocator.getTokenConstructor()))(kind, -1, -1); },
27639         createBaseNode: function (kind) { return new (NodeConstructor || (NodeConstructor = ts.objectAllocator.getNodeConstructor()))(kind, -1, -1); },
27640     };
27641     /* @internal */
27642     ts.parseNodeFactory = ts.createNodeFactory(1 /* NoParenthesizerRules */, ts.parseBaseNodeFactory);
27643     function visitNode(cbNode, node) {
27644         return node && cbNode(node);
27645     }
27646     function visitNodes(cbNode, cbNodes, nodes) {
27647         if (nodes) {
27648             if (cbNodes) {
27649                 return cbNodes(nodes);
27650             }
27651             for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
27652                 var node = nodes_1[_i];
27653                 var result = cbNode(node);
27654                 if (result) {
27655                     return result;
27656                 }
27657             }
27658         }
27659     }
27660     /*@internal*/
27661     function isJSDocLikeText(text, start) {
27662         return text.charCodeAt(start + 1) === 42 /* asterisk */ &&
27663             text.charCodeAt(start + 2) === 42 /* asterisk */ &&
27664             text.charCodeAt(start + 3) !== 47 /* slash */;
27665     }
27666     ts.isJSDocLikeText = isJSDocLikeText;
27667     /**
27668      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
27669      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; otherwise,
27670      * embedded arrays are flattened and the 'cbNode' callback is invoked for each element. If a callback returns
27671      * a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
27672      *
27673      * @param node a given node to visit its children
27674      * @param cbNode a callback to be invoked for all child nodes
27675      * @param cbNodes a callback to be invoked for embedded array
27676      *
27677      * @remarks `forEachChild` must visit the children of a node in the order
27678      * that they appear in the source code. The language service depends on this property to locate nodes by position.
27679      */
27680     function forEachChild(node, cbNode, cbNodes) {
27681         if (!node || node.kind <= 156 /* LastToken */) {
27682             return;
27683         }
27684         switch (node.kind) {
27685             case 157 /* QualifiedName */:
27686                 return visitNode(cbNode, node.left) ||
27687                     visitNode(cbNode, node.right);
27688             case 159 /* TypeParameter */:
27689                 return visitNode(cbNode, node.name) ||
27690                     visitNode(cbNode, node.constraint) ||
27691                     visitNode(cbNode, node.default) ||
27692                     visitNode(cbNode, node.expression);
27693             case 289 /* ShorthandPropertyAssignment */:
27694                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27695                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27696                     visitNode(cbNode, node.name) ||
27697                     visitNode(cbNode, node.questionToken) ||
27698                     visitNode(cbNode, node.exclamationToken) ||
27699                     visitNode(cbNode, node.equalsToken) ||
27700                     visitNode(cbNode, node.objectAssignmentInitializer);
27701             case 290 /* SpreadAssignment */:
27702                 return visitNode(cbNode, node.expression);
27703             case 160 /* Parameter */:
27704                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27705                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27706                     visitNode(cbNode, node.dotDotDotToken) ||
27707                     visitNode(cbNode, node.name) ||
27708                     visitNode(cbNode, node.questionToken) ||
27709                     visitNode(cbNode, node.type) ||
27710                     visitNode(cbNode, node.initializer);
27711             case 163 /* PropertyDeclaration */:
27712                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27713                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27714                     visitNode(cbNode, node.name) ||
27715                     visitNode(cbNode, node.questionToken) ||
27716                     visitNode(cbNode, node.exclamationToken) ||
27717                     visitNode(cbNode, node.type) ||
27718                     visitNode(cbNode, node.initializer);
27719             case 162 /* PropertySignature */:
27720                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27721                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27722                     visitNode(cbNode, node.name) ||
27723                     visitNode(cbNode, node.questionToken) ||
27724                     visitNode(cbNode, node.type) ||
27725                     visitNode(cbNode, node.initializer);
27726             case 288 /* PropertyAssignment */:
27727                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27728                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27729                     visitNode(cbNode, node.name) ||
27730                     visitNode(cbNode, node.questionToken) ||
27731                     visitNode(cbNode, node.initializer);
27732             case 249 /* VariableDeclaration */:
27733                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27734                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27735                     visitNode(cbNode, node.name) ||
27736                     visitNode(cbNode, node.exclamationToken) ||
27737                     visitNode(cbNode, node.type) ||
27738                     visitNode(cbNode, node.initializer);
27739             case 198 /* BindingElement */:
27740                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27741                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27742                     visitNode(cbNode, node.dotDotDotToken) ||
27743                     visitNode(cbNode, node.propertyName) ||
27744                     visitNode(cbNode, node.name) ||
27745                     visitNode(cbNode, node.initializer);
27746             case 174 /* FunctionType */:
27747             case 175 /* ConstructorType */:
27748             case 169 /* CallSignature */:
27749             case 170 /* ConstructSignature */:
27750             case 171 /* IndexSignature */:
27751                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27752                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27753                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27754                     visitNodes(cbNode, cbNodes, node.parameters) ||
27755                     visitNode(cbNode, node.type);
27756             case 165 /* MethodDeclaration */:
27757             case 164 /* MethodSignature */:
27758             case 166 /* Constructor */:
27759             case 167 /* GetAccessor */:
27760             case 168 /* SetAccessor */:
27761             case 208 /* FunctionExpression */:
27762             case 251 /* FunctionDeclaration */:
27763             case 209 /* ArrowFunction */:
27764                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27765                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27766                     visitNode(cbNode, node.asteriskToken) ||
27767                     visitNode(cbNode, node.name) ||
27768                     visitNode(cbNode, node.questionToken) ||
27769                     visitNode(cbNode, node.exclamationToken) ||
27770                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27771                     visitNodes(cbNode, cbNodes, node.parameters) ||
27772                     visitNode(cbNode, node.type) ||
27773                     visitNode(cbNode, node.equalsGreaterThanToken) ||
27774                     visitNode(cbNode, node.body);
27775             case 173 /* TypeReference */:
27776                 return visitNode(cbNode, node.typeName) ||
27777                     visitNodes(cbNode, cbNodes, node.typeArguments);
27778             case 172 /* TypePredicate */:
27779                 return visitNode(cbNode, node.assertsModifier) ||
27780                     visitNode(cbNode, node.parameterName) ||
27781                     visitNode(cbNode, node.type);
27782             case 176 /* TypeQuery */:
27783                 return visitNode(cbNode, node.exprName);
27784             case 177 /* TypeLiteral */:
27785                 return visitNodes(cbNode, cbNodes, node.members);
27786             case 178 /* ArrayType */:
27787                 return visitNode(cbNode, node.elementType);
27788             case 179 /* TupleType */:
27789                 return visitNodes(cbNode, cbNodes, node.elements);
27790             case 182 /* UnionType */:
27791             case 183 /* IntersectionType */:
27792                 return visitNodes(cbNode, cbNodes, node.types);
27793             case 184 /* ConditionalType */:
27794                 return visitNode(cbNode, node.checkType) ||
27795                     visitNode(cbNode, node.extendsType) ||
27796                     visitNode(cbNode, node.trueType) ||
27797                     visitNode(cbNode, node.falseType);
27798             case 185 /* InferType */:
27799                 return visitNode(cbNode, node.typeParameter);
27800             case 195 /* ImportType */:
27801                 return visitNode(cbNode, node.argument) ||
27802                     visitNode(cbNode, node.qualifier) ||
27803                     visitNodes(cbNode, cbNodes, node.typeArguments);
27804             case 186 /* ParenthesizedType */:
27805             case 188 /* TypeOperator */:
27806                 return visitNode(cbNode, node.type);
27807             case 189 /* IndexedAccessType */:
27808                 return visitNode(cbNode, node.objectType) ||
27809                     visitNode(cbNode, node.indexType);
27810             case 190 /* MappedType */:
27811                 return visitNode(cbNode, node.readonlyToken) ||
27812                     visitNode(cbNode, node.typeParameter) ||
27813                     visitNode(cbNode, node.nameType) ||
27814                     visitNode(cbNode, node.questionToken) ||
27815                     visitNode(cbNode, node.type);
27816             case 191 /* LiteralType */:
27817                 return visitNode(cbNode, node.literal);
27818             case 192 /* NamedTupleMember */:
27819                 return visitNode(cbNode, node.dotDotDotToken) ||
27820                     visitNode(cbNode, node.name) ||
27821                     visitNode(cbNode, node.questionToken) ||
27822                     visitNode(cbNode, node.type);
27823             case 196 /* ObjectBindingPattern */:
27824             case 197 /* ArrayBindingPattern */:
27825                 return visitNodes(cbNode, cbNodes, node.elements);
27826             case 199 /* ArrayLiteralExpression */:
27827                 return visitNodes(cbNode, cbNodes, node.elements);
27828             case 200 /* ObjectLiteralExpression */:
27829                 return visitNodes(cbNode, cbNodes, node.properties);
27830             case 201 /* PropertyAccessExpression */:
27831                 return visitNode(cbNode, node.expression) ||
27832                     visitNode(cbNode, node.questionDotToken) ||
27833                     visitNode(cbNode, node.name);
27834             case 202 /* ElementAccessExpression */:
27835                 return visitNode(cbNode, node.expression) ||
27836                     visitNode(cbNode, node.questionDotToken) ||
27837                     visitNode(cbNode, node.argumentExpression);
27838             case 203 /* CallExpression */:
27839             case 204 /* NewExpression */:
27840                 return visitNode(cbNode, node.expression) ||
27841                     visitNode(cbNode, node.questionDotToken) ||
27842                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
27843                     visitNodes(cbNode, cbNodes, node.arguments);
27844             case 205 /* TaggedTemplateExpression */:
27845                 return visitNode(cbNode, node.tag) ||
27846                     visitNode(cbNode, node.questionDotToken) ||
27847                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
27848                     visitNode(cbNode, node.template);
27849             case 206 /* TypeAssertionExpression */:
27850                 return visitNode(cbNode, node.type) ||
27851                     visitNode(cbNode, node.expression);
27852             case 207 /* ParenthesizedExpression */:
27853                 return visitNode(cbNode, node.expression);
27854             case 210 /* DeleteExpression */:
27855                 return visitNode(cbNode, node.expression);
27856             case 211 /* TypeOfExpression */:
27857                 return visitNode(cbNode, node.expression);
27858             case 212 /* VoidExpression */:
27859                 return visitNode(cbNode, node.expression);
27860             case 214 /* PrefixUnaryExpression */:
27861                 return visitNode(cbNode, node.operand);
27862             case 219 /* YieldExpression */:
27863                 return visitNode(cbNode, node.asteriskToken) ||
27864                     visitNode(cbNode, node.expression);
27865             case 213 /* AwaitExpression */:
27866                 return visitNode(cbNode, node.expression);
27867             case 215 /* PostfixUnaryExpression */:
27868                 return visitNode(cbNode, node.operand);
27869             case 216 /* BinaryExpression */:
27870                 return visitNode(cbNode, node.left) ||
27871                     visitNode(cbNode, node.operatorToken) ||
27872                     visitNode(cbNode, node.right);
27873             case 224 /* AsExpression */:
27874                 return visitNode(cbNode, node.expression) ||
27875                     visitNode(cbNode, node.type);
27876             case 225 /* NonNullExpression */:
27877                 return visitNode(cbNode, node.expression);
27878             case 226 /* MetaProperty */:
27879                 return visitNode(cbNode, node.name);
27880             case 217 /* ConditionalExpression */:
27881                 return visitNode(cbNode, node.condition) ||
27882                     visitNode(cbNode, node.questionToken) ||
27883                     visitNode(cbNode, node.whenTrue) ||
27884                     visitNode(cbNode, node.colonToken) ||
27885                     visitNode(cbNode, node.whenFalse);
27886             case 220 /* SpreadElement */:
27887                 return visitNode(cbNode, node.expression);
27888             case 230 /* Block */:
27889             case 257 /* ModuleBlock */:
27890                 return visitNodes(cbNode, cbNodes, node.statements);
27891             case 297 /* SourceFile */:
27892                 return visitNodes(cbNode, cbNodes, node.statements) ||
27893                     visitNode(cbNode, node.endOfFileToken);
27894             case 232 /* VariableStatement */:
27895                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27896                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27897                     visitNode(cbNode, node.declarationList);
27898             case 250 /* VariableDeclarationList */:
27899                 return visitNodes(cbNode, cbNodes, node.declarations);
27900             case 233 /* ExpressionStatement */:
27901                 return visitNode(cbNode, node.expression);
27902             case 234 /* IfStatement */:
27903                 return visitNode(cbNode, node.expression) ||
27904                     visitNode(cbNode, node.thenStatement) ||
27905                     visitNode(cbNode, node.elseStatement);
27906             case 235 /* DoStatement */:
27907                 return visitNode(cbNode, node.statement) ||
27908                     visitNode(cbNode, node.expression);
27909             case 236 /* WhileStatement */:
27910                 return visitNode(cbNode, node.expression) ||
27911                     visitNode(cbNode, node.statement);
27912             case 237 /* ForStatement */:
27913                 return visitNode(cbNode, node.initializer) ||
27914                     visitNode(cbNode, node.condition) ||
27915                     visitNode(cbNode, node.incrementor) ||
27916                     visitNode(cbNode, node.statement);
27917             case 238 /* ForInStatement */:
27918                 return visitNode(cbNode, node.initializer) ||
27919                     visitNode(cbNode, node.expression) ||
27920                     visitNode(cbNode, node.statement);
27921             case 239 /* ForOfStatement */:
27922                 return visitNode(cbNode, node.awaitModifier) ||
27923                     visitNode(cbNode, node.initializer) ||
27924                     visitNode(cbNode, node.expression) ||
27925                     visitNode(cbNode, node.statement);
27926             case 240 /* ContinueStatement */:
27927             case 241 /* BreakStatement */:
27928                 return visitNode(cbNode, node.label);
27929             case 242 /* ReturnStatement */:
27930                 return visitNode(cbNode, node.expression);
27931             case 243 /* WithStatement */:
27932                 return visitNode(cbNode, node.expression) ||
27933                     visitNode(cbNode, node.statement);
27934             case 244 /* SwitchStatement */:
27935                 return visitNode(cbNode, node.expression) ||
27936                     visitNode(cbNode, node.caseBlock);
27937             case 258 /* CaseBlock */:
27938                 return visitNodes(cbNode, cbNodes, node.clauses);
27939             case 284 /* CaseClause */:
27940                 return visitNode(cbNode, node.expression) ||
27941                     visitNodes(cbNode, cbNodes, node.statements);
27942             case 285 /* DefaultClause */:
27943                 return visitNodes(cbNode, cbNodes, node.statements);
27944             case 245 /* LabeledStatement */:
27945                 return visitNode(cbNode, node.label) ||
27946                     visitNode(cbNode, node.statement);
27947             case 246 /* ThrowStatement */:
27948                 return visitNode(cbNode, node.expression);
27949             case 247 /* TryStatement */:
27950                 return visitNode(cbNode, node.tryBlock) ||
27951                     visitNode(cbNode, node.catchClause) ||
27952                     visitNode(cbNode, node.finallyBlock);
27953             case 287 /* CatchClause */:
27954                 return visitNode(cbNode, node.variableDeclaration) ||
27955                     visitNode(cbNode, node.block);
27956             case 161 /* Decorator */:
27957                 return visitNode(cbNode, node.expression);
27958             case 252 /* ClassDeclaration */:
27959             case 221 /* ClassExpression */:
27960                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27961                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27962                     visitNode(cbNode, node.name) ||
27963                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27964                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
27965                     visitNodes(cbNode, cbNodes, node.members);
27966             case 253 /* InterfaceDeclaration */:
27967                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27968                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27969                     visitNode(cbNode, node.name) ||
27970                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27971                     visitNodes(cbNode, cbNodes, node.heritageClauses) ||
27972                     visitNodes(cbNode, cbNodes, node.members);
27973             case 254 /* TypeAliasDeclaration */:
27974                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27975                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27976                     visitNode(cbNode, node.name) ||
27977                     visitNodes(cbNode, cbNodes, node.typeParameters) ||
27978                     visitNode(cbNode, node.type);
27979             case 255 /* EnumDeclaration */:
27980                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27981                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27982                     visitNode(cbNode, node.name) ||
27983                     visitNodes(cbNode, cbNodes, node.members);
27984             case 291 /* EnumMember */:
27985                 return visitNode(cbNode, node.name) ||
27986                     visitNode(cbNode, node.initializer);
27987             case 256 /* ModuleDeclaration */:
27988                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27989                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27990                     visitNode(cbNode, node.name) ||
27991                     visitNode(cbNode, node.body);
27992             case 260 /* ImportEqualsDeclaration */:
27993                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27994                     visitNodes(cbNode, cbNodes, node.modifiers) ||
27995                     visitNode(cbNode, node.name) ||
27996                     visitNode(cbNode, node.moduleReference);
27997             case 261 /* ImportDeclaration */:
27998                 return visitNodes(cbNode, cbNodes, node.decorators) ||
27999                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28000                     visitNode(cbNode, node.importClause) ||
28001                     visitNode(cbNode, node.moduleSpecifier);
28002             case 262 /* ImportClause */:
28003                 return visitNode(cbNode, node.name) ||
28004                     visitNode(cbNode, node.namedBindings);
28005             case 259 /* NamespaceExportDeclaration */:
28006                 return visitNode(cbNode, node.name);
28007             case 263 /* NamespaceImport */:
28008                 return visitNode(cbNode, node.name);
28009             case 269 /* NamespaceExport */:
28010                 return visitNode(cbNode, node.name);
28011             case 264 /* NamedImports */:
28012             case 268 /* NamedExports */:
28013                 return visitNodes(cbNode, cbNodes, node.elements);
28014             case 267 /* ExportDeclaration */:
28015                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28016                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28017                     visitNode(cbNode, node.exportClause) ||
28018                     visitNode(cbNode, node.moduleSpecifier);
28019             case 265 /* ImportSpecifier */:
28020             case 270 /* ExportSpecifier */:
28021                 return visitNode(cbNode, node.propertyName) ||
28022                     visitNode(cbNode, node.name);
28023             case 266 /* ExportAssignment */:
28024                 return visitNodes(cbNode, cbNodes, node.decorators) ||
28025                     visitNodes(cbNode, cbNodes, node.modifiers) ||
28026                     visitNode(cbNode, node.expression);
28027             case 218 /* TemplateExpression */:
28028                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
28029             case 228 /* TemplateSpan */:
28030                 return visitNode(cbNode, node.expression) || visitNode(cbNode, node.literal);
28031             case 193 /* TemplateLiteralType */:
28032                 return visitNode(cbNode, node.head) || visitNodes(cbNode, cbNodes, node.templateSpans);
28033             case 194 /* TemplateLiteralTypeSpan */:
28034                 return visitNode(cbNode, node.type) || visitNode(cbNode, node.literal);
28035             case 158 /* ComputedPropertyName */:
28036                 return visitNode(cbNode, node.expression);
28037             case 286 /* HeritageClause */:
28038                 return visitNodes(cbNode, cbNodes, node.types);
28039             case 223 /* ExpressionWithTypeArguments */:
28040                 return visitNode(cbNode, node.expression) ||
28041                     visitNodes(cbNode, cbNodes, node.typeArguments);
28042             case 272 /* ExternalModuleReference */:
28043                 return visitNode(cbNode, node.expression);
28044             case 271 /* MissingDeclaration */:
28045                 return visitNodes(cbNode, cbNodes, node.decorators);
28046             case 337 /* CommaListExpression */:
28047                 return visitNodes(cbNode, cbNodes, node.elements);
28048             case 273 /* JsxElement */:
28049                 return visitNode(cbNode, node.openingElement) ||
28050                     visitNodes(cbNode, cbNodes, node.children) ||
28051                     visitNode(cbNode, node.closingElement);
28052             case 277 /* JsxFragment */:
28053                 return visitNode(cbNode, node.openingFragment) ||
28054                     visitNodes(cbNode, cbNodes, node.children) ||
28055                     visitNode(cbNode, node.closingFragment);
28056             case 274 /* JsxSelfClosingElement */:
28057             case 275 /* JsxOpeningElement */:
28058                 return visitNode(cbNode, node.tagName) ||
28059                     visitNodes(cbNode, cbNodes, node.typeArguments) ||
28060                     visitNode(cbNode, node.attributes);
28061             case 281 /* JsxAttributes */:
28062                 return visitNodes(cbNode, cbNodes, node.properties);
28063             case 280 /* JsxAttribute */:
28064                 return visitNode(cbNode, node.name) ||
28065                     visitNode(cbNode, node.initializer);
28066             case 282 /* JsxSpreadAttribute */:
28067                 return visitNode(cbNode, node.expression);
28068             case 283 /* JsxExpression */:
28069                 return visitNode(cbNode, node.dotDotDotToken) ||
28070                     visitNode(cbNode, node.expression);
28071             case 276 /* JsxClosingElement */:
28072                 return visitNode(cbNode, node.tagName);
28073             case 180 /* OptionalType */:
28074             case 181 /* RestType */:
28075             case 301 /* JSDocTypeExpression */:
28076             case 306 /* JSDocNonNullableType */:
28077             case 305 /* JSDocNullableType */:
28078             case 307 /* JSDocOptionalType */:
28079             case 309 /* JSDocVariadicType */:
28080                 return visitNode(cbNode, node.type);
28081             case 308 /* JSDocFunctionType */:
28082                 return visitNodes(cbNode, cbNodes, node.parameters) ||
28083                     visitNode(cbNode, node.type);
28084             case 311 /* JSDocComment */:
28085                 return visitNodes(cbNode, cbNodes, node.tags);
28086             case 332 /* JSDocSeeTag */:
28087                 return visitNode(cbNode, node.tagName) ||
28088                     visitNode(cbNode, node.name);
28089             case 302 /* JSDocNameReference */:
28090                 return visitNode(cbNode, node.name);
28091             case 326 /* JSDocParameterTag */:
28092             case 333 /* JSDocPropertyTag */:
28093                 return visitNode(cbNode, node.tagName) ||
28094                     (node.isNameFirst
28095                         ? visitNode(cbNode, node.name) ||
28096                             visitNode(cbNode, node.typeExpression)
28097                         : visitNode(cbNode, node.typeExpression) ||
28098                             visitNode(cbNode, node.name));
28099             case 317 /* JSDocAuthorTag */:
28100                 return visitNode(cbNode, node.tagName);
28101             case 316 /* JSDocImplementsTag */:
28102                 return visitNode(cbNode, node.tagName) ||
28103                     visitNode(cbNode, node.class);
28104             case 315 /* JSDocAugmentsTag */:
28105                 return visitNode(cbNode, node.tagName) ||
28106                     visitNode(cbNode, node.class);
28107             case 330 /* JSDocTemplateTag */:
28108                 return visitNode(cbNode, node.tagName) ||
28109                     visitNode(cbNode, node.constraint) ||
28110                     visitNodes(cbNode, cbNodes, node.typeParameters);
28111             case 331 /* JSDocTypedefTag */:
28112                 return visitNode(cbNode, node.tagName) ||
28113                     (node.typeExpression &&
28114                         node.typeExpression.kind === 301 /* JSDocTypeExpression */
28115                         ? visitNode(cbNode, node.typeExpression) ||
28116                             visitNode(cbNode, node.fullName)
28117                         : visitNode(cbNode, node.fullName) ||
28118                             visitNode(cbNode, node.typeExpression));
28119             case 324 /* JSDocCallbackTag */:
28120                 return visitNode(cbNode, node.tagName) ||
28121                     visitNode(cbNode, node.fullName) ||
28122                     visitNode(cbNode, node.typeExpression);
28123             case 327 /* JSDocReturnTag */:
28124             case 329 /* JSDocTypeTag */:
28125             case 328 /* JSDocThisTag */:
28126             case 325 /* JSDocEnumTag */:
28127                 return visitNode(cbNode, node.tagName) ||
28128                     visitNode(cbNode, node.typeExpression);
28129             case 313 /* JSDocSignature */:
28130                 return ts.forEach(node.typeParameters, cbNode) ||
28131                     ts.forEach(node.parameters, cbNode) ||
28132                     visitNode(cbNode, node.type);
28133             case 312 /* JSDocTypeLiteral */:
28134                 return ts.forEach(node.jsDocPropertyTags, cbNode);
28135             case 314 /* JSDocTag */:
28136             case 319 /* JSDocClassTag */:
28137             case 320 /* JSDocPublicTag */:
28138             case 321 /* JSDocPrivateTag */:
28139             case 322 /* JSDocProtectedTag */:
28140             case 323 /* JSDocReadonlyTag */:
28141                 return visitNode(cbNode, node.tagName);
28142             case 336 /* PartiallyEmittedExpression */:
28143                 return visitNode(cbNode, node.expression);
28144         }
28145     }
28146     ts.forEachChild = forEachChild;
28147     /** @internal */
28148     /**
28149      * Invokes a callback for each child of the given node. The 'cbNode' callback is invoked for all child nodes
28150      * stored in properties. If a 'cbNodes' callback is specified, it is invoked for embedded arrays; additionally,
28151      * unlike `forEachChild`, embedded arrays are flattened and the 'cbNode' callback is invoked for each element.
28152      *  If a callback returns a truthy value, iteration stops and that value is returned. Otherwise, undefined is returned.
28153      *
28154      * @param node a given node to visit its children
28155      * @param cbNode a callback to be invoked for all child nodes
28156      * @param cbNodes a callback to be invoked for embedded array
28157      *
28158      * @remarks Unlike `forEachChild`, `forEachChildRecursively` handles recursively invoking the traversal on each child node found,
28159      * and while doing so, handles traversing the structure without relying on the callstack to encode the tree structure.
28160      */
28161     function forEachChildRecursively(rootNode, cbNode, cbNodes) {
28162         var stack = [rootNode];
28163         while (stack.length) {
28164             var parent = stack.pop();
28165             var res = visitAllPossibleChildren(parent, gatherPossibleChildren(parent));
28166             if (res) {
28167                 return res;
28168             }
28169         }
28170         return;
28171         function gatherPossibleChildren(node) {
28172             var children = [];
28173             forEachChild(node, addWorkItem, addWorkItem); // By using a stack above and `unshift` here, we emulate a depth-first preorder traversal
28174             return children;
28175             function addWorkItem(n) {
28176                 children.unshift(n);
28177             }
28178         }
28179         function visitAllPossibleChildren(parent, children) {
28180             for (var _i = 0, children_5 = children; _i < children_5.length; _i++) {
28181                 var child = children_5[_i];
28182                 if (ts.isArray(child)) {
28183                     if (cbNodes) {
28184                         var res = cbNodes(child, parent);
28185                         if (res) {
28186                             if (res === "skip")
28187                                 continue;
28188                             return res;
28189                         }
28190                     }
28191                     for (var i = child.length - 1; i >= 0; i--) {
28192                         var realChild = child[i];
28193                         var res = cbNode(realChild, parent);
28194                         if (res) {
28195                             if (res === "skip")
28196                                 continue;
28197                             return res;
28198                         }
28199                         stack.push(realChild);
28200                     }
28201                 }
28202                 else {
28203                     stack.push(child);
28204                     var res = cbNode(child, parent);
28205                     if (res) {
28206                         if (res === "skip")
28207                             continue;
28208                         return res;
28209                     }
28210                 }
28211             }
28212         }
28213     }
28214     ts.forEachChildRecursively = forEachChildRecursively;
28215     function createSourceFile(fileName, sourceText, languageVersion, setParentNodes, scriptKind) {
28216         if (setParentNodes === void 0) { setParentNodes = false; }
28217         var tracingData = ["parse" /* Parse */, "createSourceFile", { path: fileName }];
28218         ts.tracing.begin.apply(ts.tracing, tracingData);
28219         ts.performance.mark("beforeParse");
28220         var result;
28221         ts.perfLogger.logStartParseSourceFile(fileName);
28222         if (languageVersion === 100 /* JSON */) {
28223             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, 6 /* JSON */);
28224         }
28225         else {
28226             result = Parser.parseSourceFile(fileName, sourceText, languageVersion, /*syntaxCursor*/ undefined, setParentNodes, scriptKind);
28227         }
28228         ts.perfLogger.logStopParseSourceFile();
28229         ts.performance.mark("afterParse");
28230         ts.performance.measure("Parse", "beforeParse", "afterParse");
28231         ts.tracing.end.apply(ts.tracing, tracingData);
28232         return result;
28233     }
28234     ts.createSourceFile = createSourceFile;
28235     function parseIsolatedEntityName(text, languageVersion) {
28236         return Parser.parseIsolatedEntityName(text, languageVersion);
28237     }
28238     ts.parseIsolatedEntityName = parseIsolatedEntityName;
28239     /**
28240      * Parse json text into SyntaxTree and return node and parse errors if any
28241      * @param fileName
28242      * @param sourceText
28243      */
28244     function parseJsonText(fileName, sourceText) {
28245         return Parser.parseJsonText(fileName, sourceText);
28246     }
28247     ts.parseJsonText = parseJsonText;
28248     // See also `isExternalOrCommonJsModule` in utilities.ts
28249     function isExternalModule(file) {
28250         return file.externalModuleIndicator !== undefined;
28251     }
28252     ts.isExternalModule = isExternalModule;
28253     // Produces a new SourceFile for the 'newText' provided. The 'textChangeRange' parameter
28254     // indicates what changed between the 'text' that this SourceFile has and the 'newText'.
28255     // The SourceFile will be created with the compiler attempting to reuse as many nodes from
28256     // this file as possible.
28257     //
28258     // Note: this function mutates nodes from this SourceFile. That means any existing nodes
28259     // from this SourceFile that are being held onto may change as a result (including
28260     // becoming detached from any SourceFile).  It is recommended that this SourceFile not
28261     // be used once 'update' is called on it.
28262     function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
28263         if (aggressiveChecks === void 0) { aggressiveChecks = false; }
28264         var newSourceFile = IncrementalParser.updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks);
28265         // 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.
28266         // We will manually port the flag to the new source file.
28267         newSourceFile.flags |= (sourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */);
28268         return newSourceFile;
28269     }
28270     ts.updateSourceFile = updateSourceFile;
28271     /* @internal */
28272     function parseIsolatedJSDocComment(content, start, length) {
28273         var result = Parser.JSDocParser.parseIsolatedJSDocComment(content, start, length);
28274         if (result && result.jsDoc) {
28275             // because the jsDocComment was parsed out of the source file, it might
28276             // not be covered by the fixupParentReferences.
28277             Parser.fixupParentReferences(result.jsDoc);
28278         }
28279         return result;
28280     }
28281     ts.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
28282     /* @internal */
28283     // Exposed only for testing.
28284     function parseJSDocTypeExpressionForTests(content, start, length) {
28285         return Parser.JSDocParser.parseJSDocTypeExpressionForTests(content, start, length);
28286     }
28287     ts.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
28288     // Implement the parser as a singleton module.  We do this for perf reasons because creating
28289     // parser instances can actually be expensive enough to impact us on projects with many source
28290     // files.
28291     var Parser;
28292     (function (Parser) {
28293         // Share a single scanner across all calls to parse a source file.  This helps speed things
28294         // up by avoiding the cost of creating/compiling scanners over and over again.
28295         var scanner = ts.createScanner(99 /* Latest */, /*skipTrivia*/ true);
28296         var disallowInAndDecoratorContext = 4096 /* DisallowInContext */ | 16384 /* DecoratorContext */;
28297         // capture constructors in 'initializeState' to avoid null checks
28298         // tslint:disable variable-name
28299         var NodeConstructor;
28300         var TokenConstructor;
28301         var IdentifierConstructor;
28302         var PrivateIdentifierConstructor;
28303         var SourceFileConstructor;
28304         // tslint:enable variable-name
28305         function countNode(node) {
28306             nodeCount++;
28307             return node;
28308         }
28309         // Rather than using `createBaseNodeFactory` here, we establish a `BaseNodeFactory` that closes over the
28310         // constructors above, which are reset each time `initializeState` is called.
28311         var baseNodeFactory = {
28312             createBaseSourceFileNode: function (kind) { return countNode(new SourceFileConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28313             createBaseIdentifierNode: function (kind) { return countNode(new IdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28314             createBasePrivateIdentifierNode: function (kind) { return countNode(new PrivateIdentifierConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28315             createBaseTokenNode: function (kind) { return countNode(new TokenConstructor(kind, /*pos*/ 0, /*end*/ 0)); },
28316             createBaseNode: function (kind) { return countNode(new NodeConstructor(kind, /*pos*/ 0, /*end*/ 0)); }
28317         };
28318         var factory = ts.createNodeFactory(1 /* NoParenthesizerRules */ | 2 /* NoNodeConverters */ | 8 /* NoOriginalNode */, baseNodeFactory);
28319         var fileName;
28320         var sourceFlags;
28321         var sourceText;
28322         var languageVersion;
28323         var scriptKind;
28324         var languageVariant;
28325         var parseDiagnostics;
28326         var jsDocDiagnostics;
28327         var syntaxCursor;
28328         var currentToken;
28329         var nodeCount;
28330         var identifiers;
28331         var privateIdentifiers;
28332         var identifierCount;
28333         var parsingContext;
28334         var notParenthesizedArrow;
28335         // Flags that dictate what parsing context we're in.  For example:
28336         // Whether or not we are in strict parsing mode.  All that changes in strict parsing mode is
28337         // that some tokens that would be considered identifiers may be considered keywords.
28338         //
28339         // When adding more parser context flags, consider which is the more common case that the
28340         // flag will be in.  This should be the 'false' state for that flag.  The reason for this is
28341         // that we don't store data in our nodes unless the value is in the *non-default* state.  So,
28342         // for example, more often than code 'allows-in' (or doesn't 'disallow-in').  We opt for
28343         // 'disallow-in' set to 'false'.  Otherwise, if we had 'allowsIn' set to 'true', then almost
28344         // all nodes would need extra state on them to store this info.
28345         //
28346         // Note: 'allowIn' and 'allowYield' track 1:1 with the [in] and [yield] concepts in the ES6
28347         // grammar specification.
28348         //
28349         // An important thing about these context concepts.  By default they are effectively inherited
28350         // while parsing through every grammar production.  i.e. if you don't change them, then when
28351         // you parse a sub-production, it will have the same context values as the parent production.
28352         // This is great most of the time.  After all, consider all the 'expression' grammar productions
28353         // and how nearly all of them pass along the 'in' and 'yield' context values:
28354         //
28355         // EqualityExpression[In, Yield] :
28356         //      RelationalExpression[?In, ?Yield]
28357         //      EqualityExpression[?In, ?Yield] == RelationalExpression[?In, ?Yield]
28358         //      EqualityExpression[?In, ?Yield] != RelationalExpression[?In, ?Yield]
28359         //      EqualityExpression[?In, ?Yield] === RelationalExpression[?In, ?Yield]
28360         //      EqualityExpression[?In, ?Yield] !== RelationalExpression[?In, ?Yield]
28361         //
28362         // Where you have to be careful is then understanding what the points are in the grammar
28363         // where the values are *not* passed along.  For example:
28364         //
28365         // SingleNameBinding[Yield,GeneratorParameter]
28366         //      [+GeneratorParameter]BindingIdentifier[Yield] Initializer[In]opt
28367         //      [~GeneratorParameter]BindingIdentifier[?Yield]Initializer[In, ?Yield]opt
28368         //
28369         // Here this is saying that if the GeneratorParameter context flag is set, that we should
28370         // explicitly set the 'yield' context flag to false before calling into the BindingIdentifier
28371         // and we should explicitly unset the 'yield' context flag before calling into the Initializer.
28372         // production.  Conversely, if the GeneratorParameter context flag is not set, then we
28373         // should leave the 'yield' context flag alone.
28374         //
28375         // Getting this all correct is tricky and requires careful reading of the grammar to
28376         // understand when these values should be changed versus when they should be inherited.
28377         //
28378         // Note: it should not be necessary to save/restore these flags during speculative/lookahead
28379         // parsing.  These context flags are naturally stored and restored through normal recursive
28380         // descent parsing and unwinding.
28381         var contextFlags;
28382         // Indicates whether we are currently parsing top-level statements.
28383         var topLevel = true;
28384         // Whether or not we've had a parse error since creating the last AST node.  If we have
28385         // encountered an error, it will be stored on the next AST node we create.  Parse errors
28386         // can be broken down into three categories:
28387         //
28388         // 1) An error that occurred during scanning.  For example, an unterminated literal, or a
28389         //    character that was completely not understood.
28390         //
28391         // 2) A token was expected, but was not present.  This type of error is commonly produced
28392         //    by the 'parseExpected' function.
28393         //
28394         // 3) A token was present that no parsing function was able to consume.  This type of error
28395         //    only occurs in the 'abortParsingListOrMoveToNextToken' function when the parser
28396         //    decides to skip the token.
28397         //
28398         // In all of these cases, we want to mark the next node as having had an error before it.
28399         // With this mark, we can know in incremental settings if this node can be reused, or if
28400         // we have to reparse it.  If we don't keep this information around, we may just reuse the
28401         // node.  in that event we would then not produce the same errors as we did before, causing
28402         // significant confusion problems.
28403         //
28404         // Note: it is necessary that this value be saved/restored during speculative/lookahead
28405         // parsing.  During lookahead parsing, we will often create a node.  That node will have
28406         // this value attached, and then this value will be set back to 'false'.  If we decide to
28407         // rewind, we must get back to the same value we had prior to the lookahead.
28408         //
28409         // Note: any errors at the end of the file that do not precede a regular node, should get
28410         // attached to the EOF token.
28411         var parseErrorBeforeNextFinishedNode = false;
28412         function parseSourceFile(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes, scriptKind) {
28413             if (setParentNodes === void 0) { setParentNodes = false; }
28414             scriptKind = ts.ensureScriptKind(fileName, scriptKind);
28415             if (scriptKind === 6 /* JSON */) {
28416                 var result_3 = parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes);
28417                 ts.convertToObjectWorker(result_3, result_3.parseDiagnostics, /*returnValue*/ false, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
28418                 result_3.referencedFiles = ts.emptyArray;
28419                 result_3.typeReferenceDirectives = ts.emptyArray;
28420                 result_3.libReferenceDirectives = ts.emptyArray;
28421                 result_3.amdDependencies = ts.emptyArray;
28422                 result_3.hasNoDefaultLib = false;
28423                 result_3.pragmas = ts.emptyMap;
28424                 return result_3;
28425             }
28426             initializeState(fileName, sourceText, languageVersion, syntaxCursor, scriptKind);
28427             var result = parseSourceFileWorker(languageVersion, setParentNodes, scriptKind);
28428             clearState();
28429             return result;
28430         }
28431         Parser.parseSourceFile = parseSourceFile;
28432         function parseIsolatedEntityName(content, languageVersion) {
28433             // Choice of `isDeclarationFile` should be arbitrary
28434             initializeState("", content, languageVersion, /*syntaxCursor*/ undefined, 1 /* JS */);
28435             // Prime the scanner.
28436             nextToken();
28437             var entityName = parseEntityName(/*allowReservedWords*/ true);
28438             var isInvalid = token() === 1 /* EndOfFileToken */ && !parseDiagnostics.length;
28439             clearState();
28440             return isInvalid ? entityName : undefined;
28441         }
28442         Parser.parseIsolatedEntityName = parseIsolatedEntityName;
28443         function parseJsonText(fileName, sourceText, languageVersion, syntaxCursor, setParentNodes) {
28444             if (languageVersion === void 0) { languageVersion = 2 /* ES2015 */; }
28445             if (setParentNodes === void 0) { setParentNodes = false; }
28446             initializeState(fileName, sourceText, languageVersion, syntaxCursor, 6 /* JSON */);
28447             sourceFlags = contextFlags;
28448             // Prime the scanner.
28449             nextToken();
28450             var pos = getNodePos();
28451             var statements, endOfFileToken;
28452             if (token() === 1 /* EndOfFileToken */) {
28453                 statements = createNodeArray([], pos, pos);
28454                 endOfFileToken = parseTokenNode();
28455             }
28456             else {
28457                 var expression = void 0;
28458                 switch (token()) {
28459                     case 22 /* OpenBracketToken */:
28460                         expression = parseArrayLiteralExpression();
28461                         break;
28462                     case 109 /* TrueKeyword */:
28463                     case 94 /* FalseKeyword */:
28464                     case 103 /* NullKeyword */:
28465                         expression = parseTokenNode();
28466                         break;
28467                     case 40 /* MinusToken */:
28468                         if (lookAhead(function () { return nextToken() === 8 /* NumericLiteral */ && nextToken() !== 58 /* ColonToken */; })) {
28469                             expression = parsePrefixUnaryExpression();
28470                         }
28471                         else {
28472                             expression = parseObjectLiteralExpression();
28473                         }
28474                         break;
28475                     case 8 /* NumericLiteral */:
28476                     case 10 /* StringLiteral */:
28477                         if (lookAhead(function () { return nextToken() !== 58 /* ColonToken */; })) {
28478                             expression = parseLiteralNode();
28479                             break;
28480                         }
28481                     // falls through
28482                     default:
28483                         expression = parseObjectLiteralExpression();
28484                         break;
28485                 }
28486                 var statement = factory.createExpressionStatement(expression);
28487                 finishNode(statement, pos);
28488                 statements = createNodeArray([statement], pos);
28489                 endOfFileToken = parseExpectedToken(1 /* EndOfFileToken */, ts.Diagnostics.Unexpected_token);
28490             }
28491             // Set source file so that errors will be reported with this file name
28492             var sourceFile = createSourceFile(fileName, 2 /* ES2015 */, 6 /* JSON */, /*isDeclaration*/ false, statements, endOfFileToken, sourceFlags);
28493             if (setParentNodes) {
28494                 fixupParentReferences(sourceFile);
28495             }
28496             sourceFile.nodeCount = nodeCount;
28497             sourceFile.identifierCount = identifierCount;
28498             sourceFile.identifiers = identifiers;
28499             sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
28500             if (jsDocDiagnostics) {
28501                 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
28502             }
28503             var result = sourceFile;
28504             clearState();
28505             return result;
28506         }
28507         Parser.parseJsonText = parseJsonText;
28508         function initializeState(_fileName, _sourceText, _languageVersion, _syntaxCursor, _scriptKind) {
28509             NodeConstructor = ts.objectAllocator.getNodeConstructor();
28510             TokenConstructor = ts.objectAllocator.getTokenConstructor();
28511             IdentifierConstructor = ts.objectAllocator.getIdentifierConstructor();
28512             PrivateIdentifierConstructor = ts.objectAllocator.getPrivateIdentifierConstructor();
28513             SourceFileConstructor = ts.objectAllocator.getSourceFileConstructor();
28514             fileName = ts.normalizePath(_fileName);
28515             sourceText = _sourceText;
28516             languageVersion = _languageVersion;
28517             syntaxCursor = _syntaxCursor;
28518             scriptKind = _scriptKind;
28519             languageVariant = ts.getLanguageVariant(_scriptKind);
28520             parseDiagnostics = [];
28521             parsingContext = 0;
28522             identifiers = new ts.Map();
28523             privateIdentifiers = new ts.Map();
28524             identifierCount = 0;
28525             nodeCount = 0;
28526             sourceFlags = 0;
28527             topLevel = true;
28528             switch (scriptKind) {
28529                 case 1 /* JS */:
28530                 case 2 /* JSX */:
28531                     contextFlags = 131072 /* JavaScriptFile */;
28532                     break;
28533                 case 6 /* JSON */:
28534                     contextFlags = 131072 /* JavaScriptFile */ | 33554432 /* JsonFile */;
28535                     break;
28536                 default:
28537                     contextFlags = 0 /* None */;
28538                     break;
28539             }
28540             parseErrorBeforeNextFinishedNode = false;
28541             // Initialize and prime the scanner before parsing the source elements.
28542             scanner.setText(sourceText);
28543             scanner.setOnError(scanError);
28544             scanner.setScriptTarget(languageVersion);
28545             scanner.setLanguageVariant(languageVariant);
28546         }
28547         function clearState() {
28548             // Clear out the text the scanner is pointing at, so it doesn't keep anything alive unnecessarily.
28549             scanner.clearCommentDirectives();
28550             scanner.setText("");
28551             scanner.setOnError(undefined);
28552             // Clear any data.  We don't want to accidentally hold onto it for too long.
28553             sourceText = undefined;
28554             languageVersion = undefined;
28555             syntaxCursor = undefined;
28556             scriptKind = undefined;
28557             languageVariant = undefined;
28558             sourceFlags = 0;
28559             parseDiagnostics = undefined;
28560             jsDocDiagnostics = undefined;
28561             parsingContext = 0;
28562             identifiers = undefined;
28563             notParenthesizedArrow = undefined;
28564             topLevel = true;
28565         }
28566         function parseSourceFileWorker(languageVersion, setParentNodes, scriptKind) {
28567             var isDeclarationFile = isDeclarationFileName(fileName);
28568             if (isDeclarationFile) {
28569                 contextFlags |= 8388608 /* Ambient */;
28570             }
28571             sourceFlags = contextFlags;
28572             // Prime the scanner.
28573             nextToken();
28574             var statements = parseList(0 /* SourceElements */, parseStatement);
28575             ts.Debug.assert(token() === 1 /* EndOfFileToken */);
28576             var endOfFileToken = addJSDocComment(parseTokenNode());
28577             var sourceFile = createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, sourceFlags);
28578             // 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
28579             processCommentPragmas(sourceFile, sourceText);
28580             processPragmasIntoFields(sourceFile, reportPragmaDiagnostic);
28581             sourceFile.commentDirectives = scanner.getCommentDirectives();
28582             sourceFile.nodeCount = nodeCount;
28583             sourceFile.identifierCount = identifierCount;
28584             sourceFile.identifiers = identifiers;
28585             sourceFile.parseDiagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
28586             if (jsDocDiagnostics) {
28587                 sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
28588             }
28589             if (setParentNodes) {
28590                 fixupParentReferences(sourceFile);
28591             }
28592             return sourceFile;
28593             function reportPragmaDiagnostic(pos, end, diagnostic) {
28594                 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, pos, end, diagnostic));
28595             }
28596         }
28597         function withJSDoc(node, hasJSDoc) {
28598             return hasJSDoc ? addJSDocComment(node) : node;
28599         }
28600         var hasDeprecatedTag = false;
28601         function addJSDocComment(node) {
28602             ts.Debug.assert(!node.jsDoc); // Should only be called once per node
28603             var jsDoc = ts.mapDefined(ts.getJSDocCommentRanges(node, sourceText), function (comment) { return JSDocParser.parseJSDocComment(node, comment.pos, comment.end - comment.pos); });
28604             if (jsDoc.length)
28605                 node.jsDoc = jsDoc;
28606             if (hasDeprecatedTag) {
28607                 hasDeprecatedTag = false;
28608                 node.flags |= 134217728 /* Deprecated */;
28609             }
28610             return node;
28611         }
28612         function reparseTopLevelAwait(sourceFile) {
28613             var savedSyntaxCursor = syntaxCursor;
28614             var baseSyntaxCursor = IncrementalParser.createSyntaxCursor(sourceFile);
28615             syntaxCursor = { currentNode: currentNode };
28616             var statements = [];
28617             var savedParseDiagnostics = parseDiagnostics;
28618             parseDiagnostics = [];
28619             var pos = 0;
28620             var start = findNextStatementWithAwait(sourceFile.statements, 0);
28621             var _loop_3 = function () {
28622                 // append all statements between pos and start
28623                 var prevStatement = sourceFile.statements[pos];
28624                 var nextStatement = sourceFile.statements[start];
28625                 ts.addRange(statements, sourceFile.statements, pos, start);
28626                 pos = findNextStatementWithoutAwait(sourceFile.statements, start);
28627                 // append all diagnostics associated with the copied range
28628                 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement.pos; });
28629                 var diagnosticEnd = diagnosticStart >= 0 ? ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= nextStatement.pos; }, diagnosticStart) : -1;
28630                 if (diagnosticStart >= 0) {
28631                     ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart, diagnosticEnd >= 0 ? diagnosticEnd : undefined);
28632                 }
28633                 // reparse all statements between start and pos. We skip existing diagnostics for the same range and allow the parser to generate new ones.
28634                 speculationHelper(function () {
28635                     var savedContextFlags = contextFlags;
28636                     contextFlags |= 32768 /* AwaitContext */;
28637                     scanner.setTextPos(nextStatement.pos);
28638                     nextToken();
28639                     while (token() !== 1 /* EndOfFileToken */) {
28640                         var startPos = scanner.getStartPos();
28641                         var statement = parseListElement(0 /* SourceElements */, parseStatement);
28642                         statements.push(statement);
28643                         if (startPos === scanner.getStartPos()) {
28644                             nextToken();
28645                         }
28646                         if (pos >= 0) {
28647                             var nonAwaitStatement = sourceFile.statements[pos];
28648                             if (statement.end === nonAwaitStatement.pos) {
28649                                 // done reparsing this section
28650                                 break;
28651                             }
28652                             if (statement.end > nonAwaitStatement.pos) {
28653                                 // we ate into the next statement, so we must reparse it.
28654                                 pos = findNextStatementWithoutAwait(sourceFile.statements, pos + 1);
28655                             }
28656                         }
28657                     }
28658                     contextFlags = savedContextFlags;
28659                 }, 2 /* Reparse */);
28660                 // find the next statement containing an `await`
28661                 start = pos >= 0 ? findNextStatementWithAwait(sourceFile.statements, pos) : -1;
28662             };
28663             while (start !== -1) {
28664                 _loop_3();
28665             }
28666             // append all statements between pos and the end of the list
28667             if (pos >= 0) {
28668                 var prevStatement_1 = sourceFile.statements[pos];
28669                 ts.addRange(statements, sourceFile.statements, pos);
28670                 // append all diagnostics associated with the copied range
28671                 var diagnosticStart = ts.findIndex(savedParseDiagnostics, function (diagnostic) { return diagnostic.start >= prevStatement_1.pos; });
28672                 if (diagnosticStart >= 0) {
28673                     ts.addRange(parseDiagnostics, savedParseDiagnostics, diagnosticStart);
28674                 }
28675             }
28676             syntaxCursor = savedSyntaxCursor;
28677             return factory.updateSourceFile(sourceFile, ts.setTextRange(factory.createNodeArray(statements), sourceFile.statements));
28678             function containsPossibleTopLevelAwait(node) {
28679                 return !(node.flags & 32768 /* AwaitContext */)
28680                     && !!(node.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */);
28681             }
28682             function findNextStatementWithAwait(statements, start) {
28683                 for (var i = start; i < statements.length; i++) {
28684                     if (containsPossibleTopLevelAwait(statements[i])) {
28685                         return i;
28686                     }
28687                 }
28688                 return -1;
28689             }
28690             function findNextStatementWithoutAwait(statements, start) {
28691                 for (var i = start; i < statements.length; i++) {
28692                     if (!containsPossibleTopLevelAwait(statements[i])) {
28693                         return i;
28694                     }
28695                 }
28696                 return -1;
28697             }
28698             function currentNode(position) {
28699                 var node = baseSyntaxCursor.currentNode(position);
28700                 if (topLevel && node && containsPossibleTopLevelAwait(node)) {
28701                     node.intersectsChange = true;
28702                 }
28703                 return node;
28704             }
28705         }
28706         function fixupParentReferences(rootNode) {
28707             // normally parent references are set during binding. However, for clients that only need
28708             // a syntax tree, and no semantic features, then the binding process is an unnecessary
28709             // overhead.  This functions allows us to set all the parents, without all the expense of
28710             // binding.
28711             ts.setParentRecursive(rootNode, /*incremental*/ true);
28712         }
28713         Parser.fixupParentReferences = fixupParentReferences;
28714         function createSourceFile(fileName, languageVersion, scriptKind, isDeclarationFile, statements, endOfFileToken, flags) {
28715             // code from createNode is inlined here so createNode won't have to deal with special case of creating source files
28716             // this is quite rare comparing to other nodes and createNode should be as fast as possible
28717             var sourceFile = factory.createSourceFile(statements, endOfFileToken, flags);
28718             ts.setTextRangePosWidth(sourceFile, 0, sourceText.length);
28719             setExternalModuleIndicator(sourceFile);
28720             // If we parsed this as an external module, it may contain top-level await
28721             if (!isDeclarationFile && isExternalModule(sourceFile) && sourceFile.transformFlags & 8388608 /* ContainsPossibleTopLevelAwait */) {
28722                 sourceFile = reparseTopLevelAwait(sourceFile);
28723             }
28724             sourceFile.text = sourceText;
28725             sourceFile.bindDiagnostics = [];
28726             sourceFile.bindSuggestionDiagnostics = undefined;
28727             sourceFile.languageVersion = languageVersion;
28728             sourceFile.fileName = fileName;
28729             sourceFile.languageVariant = ts.getLanguageVariant(scriptKind);
28730             sourceFile.isDeclarationFile = isDeclarationFile;
28731             sourceFile.scriptKind = scriptKind;
28732             return sourceFile;
28733         }
28734         function setContextFlag(val, flag) {
28735             if (val) {
28736                 contextFlags |= flag;
28737             }
28738             else {
28739                 contextFlags &= ~flag;
28740             }
28741         }
28742         function setDisallowInContext(val) {
28743             setContextFlag(val, 4096 /* DisallowInContext */);
28744         }
28745         function setYieldContext(val) {
28746             setContextFlag(val, 8192 /* YieldContext */);
28747         }
28748         function setDecoratorContext(val) {
28749             setContextFlag(val, 16384 /* DecoratorContext */);
28750         }
28751         function setAwaitContext(val) {
28752             setContextFlag(val, 32768 /* AwaitContext */);
28753         }
28754         function doOutsideOfContext(context, func) {
28755             // contextFlagsToClear will contain only the context flags that are
28756             // currently set that we need to temporarily clear
28757             // We don't just blindly reset to the previous flags to ensure
28758             // that we do not mutate cached flags for the incremental
28759             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
28760             // HasAggregatedChildData).
28761             var contextFlagsToClear = context & contextFlags;
28762             if (contextFlagsToClear) {
28763                 // clear the requested context flags
28764                 setContextFlag(/*val*/ false, contextFlagsToClear);
28765                 var result = func();
28766                 // restore the context flags we just cleared
28767                 setContextFlag(/*val*/ true, contextFlagsToClear);
28768                 return result;
28769             }
28770             // no need to do anything special as we are not in any of the requested contexts
28771             return func();
28772         }
28773         function doInsideOfContext(context, func) {
28774             // contextFlagsToSet will contain only the context flags that
28775             // are not currently set that we need to temporarily enable.
28776             // We don't just blindly reset to the previous flags to ensure
28777             // that we do not mutate cached flags for the incremental
28778             // parser (ThisNodeHasError, ThisNodeOrAnySubNodesHasError, and
28779             // HasAggregatedChildData).
28780             var contextFlagsToSet = context & ~contextFlags;
28781             if (contextFlagsToSet) {
28782                 // set the requested context flags
28783                 setContextFlag(/*val*/ true, contextFlagsToSet);
28784                 var result = func();
28785                 // reset the context flags we just set
28786                 setContextFlag(/*val*/ false, contextFlagsToSet);
28787                 return result;
28788             }
28789             // no need to do anything special as we are already in all of the requested contexts
28790             return func();
28791         }
28792         function allowInAnd(func) {
28793             return doOutsideOfContext(4096 /* DisallowInContext */, func);
28794         }
28795         function disallowInAnd(func) {
28796             return doInsideOfContext(4096 /* DisallowInContext */, func);
28797         }
28798         function doInYieldContext(func) {
28799             return doInsideOfContext(8192 /* YieldContext */, func);
28800         }
28801         function doInDecoratorContext(func) {
28802             return doInsideOfContext(16384 /* DecoratorContext */, func);
28803         }
28804         function doInAwaitContext(func) {
28805             return doInsideOfContext(32768 /* AwaitContext */, func);
28806         }
28807         function doOutsideOfAwaitContext(func) {
28808             return doOutsideOfContext(32768 /* AwaitContext */, func);
28809         }
28810         function doInYieldAndAwaitContext(func) {
28811             return doInsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
28812         }
28813         function doOutsideOfYieldAndAwaitContext(func) {
28814             return doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */, func);
28815         }
28816         function inContext(flags) {
28817             return (contextFlags & flags) !== 0;
28818         }
28819         function inYieldContext() {
28820             return inContext(8192 /* YieldContext */);
28821         }
28822         function inDisallowInContext() {
28823             return inContext(4096 /* DisallowInContext */);
28824         }
28825         function inDecoratorContext() {
28826             return inContext(16384 /* DecoratorContext */);
28827         }
28828         function inAwaitContext() {
28829             return inContext(32768 /* AwaitContext */);
28830         }
28831         function parseErrorAtCurrentToken(message, arg0) {
28832             parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), message, arg0);
28833         }
28834         function parseErrorAtPosition(start, length, message, arg0) {
28835             // Don't report another error if it would just be at the same position as the last error.
28836             var lastError = ts.lastOrUndefined(parseDiagnostics);
28837             if (!lastError || start !== lastError.start) {
28838                 parseDiagnostics.push(ts.createDetachedDiagnostic(fileName, start, length, message, arg0));
28839             }
28840             // Mark that we've encountered an error.  We'll set an appropriate bit on the next
28841             // node we finish so that it can't be reused incrementally.
28842             parseErrorBeforeNextFinishedNode = true;
28843         }
28844         function parseErrorAt(start, end, message, arg0) {
28845             parseErrorAtPosition(start, end - start, message, arg0);
28846         }
28847         function parseErrorAtRange(range, message, arg0) {
28848             parseErrorAt(range.pos, range.end, message, arg0);
28849         }
28850         function scanError(message, length) {
28851             parseErrorAtPosition(scanner.getTextPos(), length, message);
28852         }
28853         function getNodePos() {
28854             return scanner.getStartPos();
28855         }
28856         function hasPrecedingJSDocComment() {
28857             return scanner.hasPrecedingJSDocComment();
28858         }
28859         // Use this function to access the current token instead of reading the currentToken
28860         // variable. Since function results aren't narrowed in control flow analysis, this ensures
28861         // that the type checker doesn't make wrong assumptions about the type of the current
28862         // token (e.g. a call to nextToken() changes the current token but the checker doesn't
28863         // reason about this side effect).  Mainstream VMs inline simple functions like this, so
28864         // there is no performance penalty.
28865         function token() {
28866             return currentToken;
28867         }
28868         function nextTokenWithoutCheck() {
28869             return currentToken = scanner.scan();
28870         }
28871         function nextTokenAnd(func) {
28872             nextToken();
28873             return func();
28874         }
28875         function nextToken() {
28876             // if the keyword had an escape
28877             if (ts.isKeyword(currentToken) && (scanner.hasUnicodeEscape() || scanner.hasExtendedUnicodeEscape())) {
28878                 // issue a parse error for the escape
28879                 parseErrorAt(scanner.getTokenPos(), scanner.getTextPos(), ts.Diagnostics.Keywords_cannot_contain_escape_characters);
28880             }
28881             return nextTokenWithoutCheck();
28882         }
28883         function nextTokenJSDoc() {
28884             return currentToken = scanner.scanJsDocToken();
28885         }
28886         function reScanGreaterToken() {
28887             return currentToken = scanner.reScanGreaterToken();
28888         }
28889         function reScanSlashToken() {
28890             return currentToken = scanner.reScanSlashToken();
28891         }
28892         function reScanTemplateToken(isTaggedTemplate) {
28893             return currentToken = scanner.reScanTemplateToken(isTaggedTemplate);
28894         }
28895         function reScanTemplateHeadOrNoSubstitutionTemplate() {
28896             return currentToken = scanner.reScanTemplateHeadOrNoSubstitutionTemplate();
28897         }
28898         function reScanLessThanToken() {
28899             return currentToken = scanner.reScanLessThanToken();
28900         }
28901         function scanJsxIdentifier() {
28902             return currentToken = scanner.scanJsxIdentifier();
28903         }
28904         function scanJsxText() {
28905             return currentToken = scanner.scanJsxToken();
28906         }
28907         function scanJsxAttributeValue() {
28908             return currentToken = scanner.scanJsxAttributeValue();
28909         }
28910         function speculationHelper(callback, speculationKind) {
28911             // Keep track of the state we'll need to rollback to if lookahead fails (or if the
28912             // caller asked us to always reset our state).
28913             var saveToken = currentToken;
28914             var saveParseDiagnosticsLength = parseDiagnostics.length;
28915             var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
28916             // Note: it is not actually necessary to save/restore the context flags here.  That's
28917             // because the saving/restoring of these flags happens naturally through the recursive
28918             // descent nature of our parser.  However, we still store this here just so we can
28919             // assert that invariant holds.
28920             var saveContextFlags = contextFlags;
28921             // If we're only looking ahead, then tell the scanner to only lookahead as well.
28922             // Otherwise, if we're actually speculatively parsing, then tell the scanner to do the
28923             // same.
28924             var result = speculationKind !== 0 /* TryParse */
28925                 ? scanner.lookAhead(callback)
28926                 : scanner.tryScan(callback);
28927             ts.Debug.assert(saveContextFlags === contextFlags);
28928             // If our callback returned something 'falsy' or we're just looking ahead,
28929             // then unconditionally restore us to where we were.
28930             if (!result || speculationKind !== 0 /* TryParse */) {
28931                 currentToken = saveToken;
28932                 if (speculationKind !== 2 /* Reparse */) {
28933                     parseDiagnostics.length = saveParseDiagnosticsLength;
28934                 }
28935                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
28936             }
28937             return result;
28938         }
28939         /** Invokes the provided callback then unconditionally restores the parser to the state it
28940          * was in immediately prior to invoking the callback.  The result of invoking the callback
28941          * is returned from this function.
28942          */
28943         function lookAhead(callback) {
28944             return speculationHelper(callback, 1 /* Lookahead */);
28945         }
28946         /** Invokes the provided callback.  If the callback returns something falsy, then it restores
28947          * the parser to the state it was in immediately prior to invoking the callback.  If the
28948          * callback returns something truthy, then the parser state is not rolled back.  The result
28949          * of invoking the callback is returned from this function.
28950          */
28951         function tryParse(callback) {
28952             return speculationHelper(callback, 0 /* TryParse */);
28953         }
28954         function isBindingIdentifier() {
28955             if (token() === 78 /* Identifier */) {
28956                 return true;
28957             }
28958             return token() > 115 /* LastReservedWord */;
28959         }
28960         // Ignore strict mode flag because we will report an error in type checker instead.
28961         function isIdentifier() {
28962             if (token() === 78 /* Identifier */) {
28963                 return true;
28964             }
28965             // If we have a 'yield' keyword, and we're in the [yield] context, then 'yield' is
28966             // considered a keyword and is not an identifier.
28967             if (token() === 124 /* YieldKeyword */ && inYieldContext()) {
28968                 return false;
28969             }
28970             // If we have a 'await' keyword, and we're in the [Await] context, then 'await' is
28971             // considered a keyword and is not an identifier.
28972             if (token() === 130 /* AwaitKeyword */ && inAwaitContext()) {
28973                 return false;
28974             }
28975             return token() > 115 /* LastReservedWord */;
28976         }
28977         function parseExpected(kind, diagnosticMessage, shouldAdvance) {
28978             if (shouldAdvance === void 0) { shouldAdvance = true; }
28979             if (token() === kind) {
28980                 if (shouldAdvance) {
28981                     nextToken();
28982                 }
28983                 return true;
28984             }
28985             // Report specific message if provided with one.  Otherwise, report generic fallback message.
28986             if (diagnosticMessage) {
28987                 parseErrorAtCurrentToken(diagnosticMessage);
28988             }
28989             else {
28990                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
28991             }
28992             return false;
28993         }
28994         function parseExpectedJSDoc(kind) {
28995             if (token() === kind) {
28996                 nextTokenJSDoc();
28997                 return true;
28998             }
28999             parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(kind));
29000             return false;
29001         }
29002         function parseOptional(t) {
29003             if (token() === t) {
29004                 nextToken();
29005                 return true;
29006             }
29007             return false;
29008         }
29009         function parseOptionalToken(t) {
29010             if (token() === t) {
29011                 return parseTokenNode();
29012             }
29013             return undefined;
29014         }
29015         function parseOptionalTokenJSDoc(t) {
29016             if (token() === t) {
29017                 return parseTokenNodeJSDoc();
29018             }
29019             return undefined;
29020         }
29021         function parseExpectedToken(t, diagnosticMessage, arg0) {
29022             return parseOptionalToken(t) ||
29023                 createMissingNode(t, /*reportAtCurrentPosition*/ false, diagnosticMessage || ts.Diagnostics._0_expected, arg0 || ts.tokenToString(t));
29024         }
29025         function parseExpectedTokenJSDoc(t) {
29026             return parseOptionalTokenJSDoc(t) ||
29027                 createMissingNode(t, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(t));
29028         }
29029         function parseTokenNode() {
29030             var pos = getNodePos();
29031             var kind = token();
29032             nextToken();
29033             return finishNode(factory.createToken(kind), pos);
29034         }
29035         function parseTokenNodeJSDoc() {
29036             var pos = getNodePos();
29037             var kind = token();
29038             nextTokenJSDoc();
29039             return finishNode(factory.createToken(kind), pos);
29040         }
29041         function canParseSemicolon() {
29042             // If there's a real semicolon, then we can always parse it out.
29043             if (token() === 26 /* SemicolonToken */) {
29044                 return true;
29045             }
29046             // We can parse out an optional semicolon in ASI cases in the following cases.
29047             return token() === 19 /* CloseBraceToken */ || token() === 1 /* EndOfFileToken */ || scanner.hasPrecedingLineBreak();
29048         }
29049         function parseSemicolon() {
29050             if (canParseSemicolon()) {
29051                 if (token() === 26 /* SemicolonToken */) {
29052                     // consume the semicolon if it was explicitly provided.
29053                     nextToken();
29054                 }
29055                 return true;
29056             }
29057             else {
29058                 return parseExpected(26 /* SemicolonToken */);
29059             }
29060         }
29061         function createNodeArray(elements, pos, end, hasTrailingComma) {
29062             var array = factory.createNodeArray(elements, hasTrailingComma);
29063             ts.setTextRangePosEnd(array, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
29064             return array;
29065         }
29066         function finishNode(node, pos, end) {
29067             ts.setTextRangePosEnd(node, pos, end !== null && end !== void 0 ? end : scanner.getStartPos());
29068             if (contextFlags) {
29069                 node.flags |= contextFlags;
29070             }
29071             // Keep track on the node if we encountered an error while parsing it.  If we did, then
29072             // we cannot reuse the node incrementally.  Once we've marked this node, clear out the
29073             // flag so that we don't mark any subsequent nodes.
29074             if (parseErrorBeforeNextFinishedNode) {
29075                 parseErrorBeforeNextFinishedNode = false;
29076                 node.flags |= 65536 /* ThisNodeHasError */;
29077             }
29078             return node;
29079         }
29080         function createMissingNode(kind, reportAtCurrentPosition, diagnosticMessage, arg0) {
29081             if (reportAtCurrentPosition) {
29082                 parseErrorAtPosition(scanner.getStartPos(), 0, diagnosticMessage, arg0);
29083             }
29084             else if (diagnosticMessage) {
29085                 parseErrorAtCurrentToken(diagnosticMessage, arg0);
29086             }
29087             var pos = getNodePos();
29088             var result = kind === 78 /* Identifier */ ? factory.createIdentifier("", /*typeArguments*/ undefined, /*originalKeywordKind*/ undefined) :
29089                 ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, "", "", /*templateFlags*/ undefined) :
29090                     kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral("", /*numericLiteralFlags*/ undefined) :
29091                         kind === 10 /* StringLiteral */ ? factory.createStringLiteral("", /*isSingleQuote*/ undefined) :
29092                             kind === 271 /* MissingDeclaration */ ? factory.createMissingDeclaration() :
29093                                 factory.createToken(kind);
29094             return finishNode(result, pos);
29095         }
29096         function internIdentifier(text) {
29097             var identifier = identifiers.get(text);
29098             if (identifier === undefined) {
29099                 identifiers.set(text, identifier = text);
29100             }
29101             return identifier;
29102         }
29103         // An identifier that starts with two underscores has an extra underscore character prepended to it to avoid issues
29104         // with magic property names like '__proto__'. The 'identifiers' object is used to share a single string instance for
29105         // each identifier in order to reduce memory consumption.
29106         function createIdentifier(isIdentifier, diagnosticMessage, privateIdentifierDiagnosticMessage) {
29107             identifierCount++;
29108             if (isIdentifier) {
29109                 var pos = getNodePos();
29110                 // Store original token kind if it is not just an Identifier so we can report appropriate error later in type checker
29111                 var originalKeywordKind = token();
29112                 var text = internIdentifier(scanner.getTokenValue());
29113                 nextTokenWithoutCheck();
29114                 return finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos);
29115             }
29116             if (token() === 79 /* PrivateIdentifier */) {
29117                 parseErrorAtCurrentToken(privateIdentifierDiagnosticMessage || ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
29118                 return createIdentifier(/*isIdentifier*/ true);
29119             }
29120             // Only for end of file because the error gets reported incorrectly on embedded script tags.
29121             var reportAtCurrentPosition = token() === 1 /* EndOfFileToken */;
29122             var isReservedWord = scanner.isReservedWord();
29123             var msgArg = scanner.getTokenText();
29124             var defaultMessage = isReservedWord ?
29125                 ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here :
29126                 ts.Diagnostics.Identifier_expected;
29127             return createMissingNode(78 /* Identifier */, reportAtCurrentPosition, diagnosticMessage || defaultMessage, msgArg);
29128         }
29129         function parseBindingIdentifier(privateIdentifierDiagnosticMessage) {
29130             return createIdentifier(isBindingIdentifier(), /*diagnosticMessage*/ undefined, privateIdentifierDiagnosticMessage);
29131         }
29132         function parseIdentifier(diagnosticMessage, privateIdentifierDiagnosticMessage) {
29133             return createIdentifier(isIdentifier(), diagnosticMessage, privateIdentifierDiagnosticMessage);
29134         }
29135         function parseIdentifierName(diagnosticMessage) {
29136             return createIdentifier(ts.tokenIsIdentifierOrKeyword(token()), diagnosticMessage);
29137         }
29138         function isLiteralPropertyName() {
29139             return ts.tokenIsIdentifierOrKeyword(token()) ||
29140                 token() === 10 /* StringLiteral */ ||
29141                 token() === 8 /* NumericLiteral */;
29142         }
29143         function parsePropertyNameWorker(allowComputedPropertyNames) {
29144             if (token() === 10 /* StringLiteral */ || token() === 8 /* NumericLiteral */) {
29145                 var node = parseLiteralNode();
29146                 node.text = internIdentifier(node.text);
29147                 return node;
29148             }
29149             if (allowComputedPropertyNames && token() === 22 /* OpenBracketToken */) {
29150                 return parseComputedPropertyName();
29151             }
29152             if (token() === 79 /* PrivateIdentifier */) {
29153                 return parsePrivateIdentifier();
29154             }
29155             return parseIdentifierName();
29156         }
29157         function parsePropertyName() {
29158             return parsePropertyNameWorker(/*allowComputedPropertyNames*/ true);
29159         }
29160         function parseComputedPropertyName() {
29161             // PropertyName [Yield]:
29162             //      LiteralPropertyName
29163             //      ComputedPropertyName[?Yield]
29164             var pos = getNodePos();
29165             parseExpected(22 /* OpenBracketToken */);
29166             // We parse any expression (including a comma expression). But the grammar
29167             // says that only an assignment expression is allowed, so the grammar checker
29168             // will error if it sees a comma expression.
29169             var expression = allowInAnd(parseExpression);
29170             parseExpected(23 /* CloseBracketToken */);
29171             return finishNode(factory.createComputedPropertyName(expression), pos);
29172         }
29173         function internPrivateIdentifier(text) {
29174             var privateIdentifier = privateIdentifiers.get(text);
29175             if (privateIdentifier === undefined) {
29176                 privateIdentifiers.set(text, privateIdentifier = text);
29177             }
29178             return privateIdentifier;
29179         }
29180         function parsePrivateIdentifier() {
29181             var pos = getNodePos();
29182             var node = factory.createPrivateIdentifier(internPrivateIdentifier(scanner.getTokenText()));
29183             nextToken();
29184             return finishNode(node, pos);
29185         }
29186         function parseContextualModifier(t) {
29187             return token() === t && tryParse(nextTokenCanFollowModifier);
29188         }
29189         function nextTokenIsOnSameLineAndCanFollowModifier() {
29190             nextToken();
29191             if (scanner.hasPrecedingLineBreak()) {
29192                 return false;
29193             }
29194             return canFollowModifier();
29195         }
29196         function nextTokenCanFollowModifier() {
29197             switch (token()) {
29198                 case 84 /* ConstKeyword */:
29199                     // 'const' is only a modifier if followed by 'enum'.
29200                     return nextToken() === 91 /* EnumKeyword */;
29201                 case 92 /* ExportKeyword */:
29202                     nextToken();
29203                     if (token() === 87 /* DefaultKeyword */) {
29204                         return lookAhead(nextTokenCanFollowDefaultKeyword);
29205                     }
29206                     if (token() === 149 /* TypeKeyword */) {
29207                         return lookAhead(nextTokenCanFollowExportModifier);
29208                     }
29209                     return canFollowExportModifier();
29210                 case 87 /* DefaultKeyword */:
29211                     return nextTokenCanFollowDefaultKeyword();
29212                 case 123 /* StaticKeyword */:
29213                 case 134 /* GetKeyword */:
29214                 case 146 /* SetKeyword */:
29215                     nextToken();
29216                     return canFollowModifier();
29217                 default:
29218                     return nextTokenIsOnSameLineAndCanFollowModifier();
29219             }
29220         }
29221         function canFollowExportModifier() {
29222             return token() !== 41 /* AsteriskToken */
29223                 && token() !== 126 /* AsKeyword */
29224                 && token() !== 18 /* OpenBraceToken */
29225                 && canFollowModifier();
29226         }
29227         function nextTokenCanFollowExportModifier() {
29228             nextToken();
29229             return canFollowExportModifier();
29230         }
29231         function parseAnyContextualModifier() {
29232             return ts.isModifierKind(token()) && tryParse(nextTokenCanFollowModifier);
29233         }
29234         function canFollowModifier() {
29235             return token() === 22 /* OpenBracketToken */
29236                 || token() === 18 /* OpenBraceToken */
29237                 || token() === 41 /* AsteriskToken */
29238                 || token() === 25 /* DotDotDotToken */
29239                 || isLiteralPropertyName();
29240         }
29241         function nextTokenCanFollowDefaultKeyword() {
29242             nextToken();
29243             return token() === 83 /* ClassKeyword */ || token() === 97 /* FunctionKeyword */ ||
29244                 token() === 117 /* InterfaceKeyword */ ||
29245                 (token() === 125 /* AbstractKeyword */ && lookAhead(nextTokenIsClassKeywordOnSameLine)) ||
29246                 (token() === 129 /* AsyncKeyword */ && lookAhead(nextTokenIsFunctionKeywordOnSameLine));
29247         }
29248         // True if positioned at the start of a list element
29249         function isListElement(parsingContext, inErrorRecovery) {
29250             var node = currentNode(parsingContext);
29251             if (node) {
29252                 return true;
29253             }
29254             switch (parsingContext) {
29255                 case 0 /* SourceElements */:
29256                 case 1 /* BlockStatements */:
29257                 case 3 /* SwitchClauseStatements */:
29258                     // If we're in error recovery, then we don't want to treat ';' as an empty statement.
29259                     // The problem is that ';' can show up in far too many contexts, and if we see one
29260                     // and assume it's a statement, then we may bail out inappropriately from whatever
29261                     // we're parsing.  For example, if we have a semicolon in the middle of a class, then
29262                     // we really don't want to assume the class is over and we're on a statement in the
29263                     // outer module.  We just want to consume and move on.
29264                     return !(token() === 26 /* SemicolonToken */ && inErrorRecovery) && isStartOfStatement();
29265                 case 2 /* SwitchClauses */:
29266                     return token() === 81 /* CaseKeyword */ || token() === 87 /* DefaultKeyword */;
29267                 case 4 /* TypeMembers */:
29268                     return lookAhead(isTypeMemberStart);
29269                 case 5 /* ClassMembers */:
29270                     // We allow semicolons as class elements (as specified by ES6) as long as we're
29271                     // not in error recovery.  If we're in error recovery, we don't want an errant
29272                     // semicolon to be treated as a class member (since they're almost always used
29273                     // for statements.
29274                     return lookAhead(isClassMemberStart) || (token() === 26 /* SemicolonToken */ && !inErrorRecovery);
29275                 case 6 /* EnumMembers */:
29276                     // Include open bracket computed properties. This technically also lets in indexers,
29277                     // which would be a candidate for improved error reporting.
29278                     return token() === 22 /* OpenBracketToken */ || isLiteralPropertyName();
29279                 case 12 /* ObjectLiteralMembers */:
29280                     switch (token()) {
29281                         case 22 /* OpenBracketToken */:
29282                         case 41 /* AsteriskToken */:
29283                         case 25 /* DotDotDotToken */:
29284                         case 24 /* DotToken */: // Not an object literal member, but don't want to close the object (see `tests/cases/fourslash/completionsDotInObjectLiteral.ts`)
29285                             return true;
29286                         default:
29287                             return isLiteralPropertyName();
29288                     }
29289                 case 18 /* RestProperties */:
29290                     return isLiteralPropertyName();
29291                 case 9 /* ObjectBindingElements */:
29292                     return token() === 22 /* OpenBracketToken */ || token() === 25 /* DotDotDotToken */ || isLiteralPropertyName();
29293                 case 7 /* HeritageClauseElement */:
29294                     // If we see `{ ... }` then only consume it as an expression if it is followed by `,` or `{`
29295                     // That way we won't consume the body of a class in its heritage clause.
29296                     if (token() === 18 /* OpenBraceToken */) {
29297                         return lookAhead(isValidHeritageClauseObjectLiteral);
29298                     }
29299                     if (!inErrorRecovery) {
29300                         return isStartOfLeftHandSideExpression() && !isHeritageClauseExtendsOrImplementsKeyword();
29301                     }
29302                     else {
29303                         // If we're in error recovery we tighten up what we're willing to match.
29304                         // That way we don't treat something like "this" as a valid heritage clause
29305                         // element during recovery.
29306                         return isIdentifier() && !isHeritageClauseExtendsOrImplementsKeyword();
29307                     }
29308                 case 8 /* VariableDeclarations */:
29309                     return isBindingIdentifierOrPrivateIdentifierOrPattern();
29310                 case 10 /* ArrayBindingElements */:
29311                     return token() === 27 /* CommaToken */ || token() === 25 /* DotDotDotToken */ || isBindingIdentifierOrPrivateIdentifierOrPattern();
29312                 case 19 /* TypeParameters */:
29313                     return isIdentifier();
29314                 case 15 /* ArrayLiteralMembers */:
29315                     switch (token()) {
29316                         case 27 /* CommaToken */:
29317                         case 24 /* DotToken */: // Not an array literal member, but don't want to close the array (see `tests/cases/fourslash/completionsDotInArrayLiteralInObjectLiteral.ts`)
29318                             return true;
29319                     }
29320                 // falls through
29321                 case 11 /* ArgumentExpressions */:
29322                     return token() === 25 /* DotDotDotToken */ || isStartOfExpression();
29323                 case 16 /* Parameters */:
29324                     return isStartOfParameter(/*isJSDocParameter*/ false);
29325                 case 17 /* JSDocParameters */:
29326                     return isStartOfParameter(/*isJSDocParameter*/ true);
29327                 case 20 /* TypeArguments */:
29328                 case 21 /* TupleElementTypes */:
29329                     return token() === 27 /* CommaToken */ || isStartOfType();
29330                 case 22 /* HeritageClauses */:
29331                     return isHeritageClause();
29332                 case 23 /* ImportOrExportSpecifiers */:
29333                     return ts.tokenIsIdentifierOrKeyword(token());
29334                 case 13 /* JsxAttributes */:
29335                     return ts.tokenIsIdentifierOrKeyword(token()) || token() === 18 /* OpenBraceToken */;
29336                 case 14 /* JsxChildren */:
29337                     return true;
29338             }
29339             return ts.Debug.fail("Non-exhaustive case in 'isListElement'.");
29340         }
29341         function isValidHeritageClauseObjectLiteral() {
29342             ts.Debug.assert(token() === 18 /* OpenBraceToken */);
29343             if (nextToken() === 19 /* CloseBraceToken */) {
29344                 // if we see "extends {}" then only treat the {} as what we're extending (and not
29345                 // the class body) if we have:
29346                 //
29347                 //      extends {} {
29348                 //      extends {},
29349                 //      extends {} extends
29350                 //      extends {} implements
29351                 var next = nextToken();
29352                 return next === 27 /* CommaToken */ || next === 18 /* OpenBraceToken */ || next === 93 /* ExtendsKeyword */ || next === 116 /* ImplementsKeyword */;
29353             }
29354             return true;
29355         }
29356         function nextTokenIsIdentifier() {
29357             nextToken();
29358             return isIdentifier();
29359         }
29360         function nextTokenIsIdentifierOrKeyword() {
29361             nextToken();
29362             return ts.tokenIsIdentifierOrKeyword(token());
29363         }
29364         function nextTokenIsIdentifierOrKeywordOrGreaterThan() {
29365             nextToken();
29366             return ts.tokenIsIdentifierOrKeywordOrGreaterThan(token());
29367         }
29368         function isHeritageClauseExtendsOrImplementsKeyword() {
29369             if (token() === 116 /* ImplementsKeyword */ ||
29370                 token() === 93 /* ExtendsKeyword */) {
29371                 return lookAhead(nextTokenIsStartOfExpression);
29372             }
29373             return false;
29374         }
29375         function nextTokenIsStartOfExpression() {
29376             nextToken();
29377             return isStartOfExpression();
29378         }
29379         function nextTokenIsStartOfType() {
29380             nextToken();
29381             return isStartOfType();
29382         }
29383         // True if positioned at a list terminator
29384         function isListTerminator(kind) {
29385             if (token() === 1 /* EndOfFileToken */) {
29386                 // Being at the end of the file ends all lists.
29387                 return true;
29388             }
29389             switch (kind) {
29390                 case 1 /* BlockStatements */:
29391                 case 2 /* SwitchClauses */:
29392                 case 4 /* TypeMembers */:
29393                 case 5 /* ClassMembers */:
29394                 case 6 /* EnumMembers */:
29395                 case 12 /* ObjectLiteralMembers */:
29396                 case 9 /* ObjectBindingElements */:
29397                 case 23 /* ImportOrExportSpecifiers */:
29398                     return token() === 19 /* CloseBraceToken */;
29399                 case 3 /* SwitchClauseStatements */:
29400                     return token() === 19 /* CloseBraceToken */ || token() === 81 /* CaseKeyword */ || token() === 87 /* DefaultKeyword */;
29401                 case 7 /* HeritageClauseElement */:
29402                     return token() === 18 /* OpenBraceToken */ || token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
29403                 case 8 /* VariableDeclarations */:
29404                     return isVariableDeclaratorListTerminator();
29405                 case 19 /* TypeParameters */:
29406                     // Tokens other than '>' are here for better error recovery
29407                     return token() === 31 /* GreaterThanToken */ || token() === 20 /* OpenParenToken */ || token() === 18 /* OpenBraceToken */ || token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
29408                 case 11 /* ArgumentExpressions */:
29409                     // Tokens other than ')' are here for better error recovery
29410                     return token() === 21 /* CloseParenToken */ || token() === 26 /* SemicolonToken */;
29411                 case 15 /* ArrayLiteralMembers */:
29412                 case 21 /* TupleElementTypes */:
29413                 case 10 /* ArrayBindingElements */:
29414                     return token() === 23 /* CloseBracketToken */;
29415                 case 17 /* JSDocParameters */:
29416                 case 16 /* Parameters */:
29417                 case 18 /* RestProperties */:
29418                     // Tokens other than ')' and ']' (the latter for index signatures) are here for better error recovery
29419                     return token() === 21 /* CloseParenToken */ || token() === 23 /* CloseBracketToken */ /*|| token === SyntaxKind.OpenBraceToken*/;
29420                 case 20 /* TypeArguments */:
29421                     // All other tokens should cause the type-argument to terminate except comma token
29422                     return token() !== 27 /* CommaToken */;
29423                 case 22 /* HeritageClauses */:
29424                     return token() === 18 /* OpenBraceToken */ || token() === 19 /* CloseBraceToken */;
29425                 case 13 /* JsxAttributes */:
29426                     return token() === 31 /* GreaterThanToken */ || token() === 43 /* SlashToken */;
29427                 case 14 /* JsxChildren */:
29428                     return token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsSlash);
29429                 default:
29430                     return false;
29431             }
29432         }
29433         function isVariableDeclaratorListTerminator() {
29434             // If we can consume a semicolon (either explicitly, or with ASI), then consider us done
29435             // with parsing the list of variable declarators.
29436             if (canParseSemicolon()) {
29437                 return true;
29438             }
29439             // in the case where we're parsing the variable declarator of a 'for-in' statement, we
29440             // are done if we see an 'in' keyword in front of us. Same with for-of
29441             if (isInOrOfKeyword(token())) {
29442                 return true;
29443             }
29444             // ERROR RECOVERY TWEAK:
29445             // For better error recovery, if we see an '=>' then we just stop immediately.  We've got an
29446             // arrow function here and it's going to be very unlikely that we'll resynchronize and get
29447             // another variable declaration.
29448             if (token() === 38 /* EqualsGreaterThanToken */) {
29449                 return true;
29450             }
29451             // Keep trying to parse out variable declarators.
29452             return false;
29453         }
29454         // True if positioned at element or terminator of the current list or any enclosing list
29455         function isInSomeParsingContext() {
29456             for (var kind = 0; kind < 24 /* Count */; kind++) {
29457                 if (parsingContext & (1 << kind)) {
29458                     if (isListElement(kind, /*inErrorRecovery*/ true) || isListTerminator(kind)) {
29459                         return true;
29460                     }
29461                 }
29462             }
29463             return false;
29464         }
29465         // Parses a list of elements
29466         function parseList(kind, parseElement) {
29467             var saveParsingContext = parsingContext;
29468             parsingContext |= 1 << kind;
29469             var list = [];
29470             var listPos = getNodePos();
29471             while (!isListTerminator(kind)) {
29472                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
29473                     var element = parseListElement(kind, parseElement);
29474                     list.push(element);
29475                     continue;
29476                 }
29477                 if (abortParsingListOrMoveToNextToken(kind)) {
29478                     break;
29479                 }
29480             }
29481             parsingContext = saveParsingContext;
29482             return createNodeArray(list, listPos);
29483         }
29484         function parseListElement(parsingContext, parseElement) {
29485             var node = currentNode(parsingContext);
29486             if (node) {
29487                 return consumeNode(node);
29488             }
29489             return parseElement();
29490         }
29491         function currentNode(parsingContext) {
29492             // If we don't have a cursor or the parsing context isn't reusable, there's nothing to reuse.
29493             //
29494             // If there is an outstanding parse error that we've encountered, but not attached to
29495             // some node, then we cannot get a node from the old source tree.  This is because we
29496             // want to mark the next node we encounter as being unusable.
29497             //
29498             // Note: This may be too conservative.  Perhaps we could reuse the node and set the bit
29499             // on it (or its leftmost child) as having the error.  For now though, being conservative
29500             // is nice and likely won't ever affect perf.
29501             if (!syntaxCursor || !isReusableParsingContext(parsingContext) || parseErrorBeforeNextFinishedNode) {
29502                 return undefined;
29503             }
29504             var node = syntaxCursor.currentNode(scanner.getStartPos());
29505             // Can't reuse a missing node.
29506             // Can't reuse a node that intersected the change range.
29507             // Can't reuse a node that contains a parse error.  This is necessary so that we
29508             // produce the same set of errors again.
29509             if (ts.nodeIsMissing(node) || node.intersectsChange || ts.containsParseError(node)) {
29510                 return undefined;
29511             }
29512             // We can only reuse a node if it was parsed under the same strict mode that we're
29513             // currently in.  i.e. if we originally parsed a node in non-strict mode, but then
29514             // the user added 'using strict' at the top of the file, then we can't use that node
29515             // again as the presence of strict mode may cause us to parse the tokens in the file
29516             // differently.
29517             //
29518             // Note: we *can* reuse tokens when the strict mode changes.  That's because tokens
29519             // are unaffected by strict mode.  It's just the parser will decide what to do with it
29520             // differently depending on what mode it is in.
29521             //
29522             // This also applies to all our other context flags as well.
29523             var nodeContextFlags = node.flags & 25358336 /* ContextFlags */;
29524             if (nodeContextFlags !== contextFlags) {
29525                 return undefined;
29526             }
29527             // Ok, we have a node that looks like it could be reused.  Now verify that it is valid
29528             // in the current list parsing context that we're currently at.
29529             if (!canReuseNode(node, parsingContext)) {
29530                 return undefined;
29531             }
29532             if (node.jsDocCache) {
29533                 // jsDocCache may include tags from parent nodes, which might have been modified.
29534                 node.jsDocCache = undefined;
29535             }
29536             return node;
29537         }
29538         function consumeNode(node) {
29539             // Move the scanner so it is after the node we just consumed.
29540             scanner.setTextPos(node.end);
29541             nextToken();
29542             return node;
29543         }
29544         function isReusableParsingContext(parsingContext) {
29545             switch (parsingContext) {
29546                 case 5 /* ClassMembers */:
29547                 case 2 /* SwitchClauses */:
29548                 case 0 /* SourceElements */:
29549                 case 1 /* BlockStatements */:
29550                 case 3 /* SwitchClauseStatements */:
29551                 case 6 /* EnumMembers */:
29552                 case 4 /* TypeMembers */:
29553                 case 8 /* VariableDeclarations */:
29554                 case 17 /* JSDocParameters */:
29555                 case 16 /* Parameters */:
29556                     return true;
29557             }
29558             return false;
29559         }
29560         function canReuseNode(node, parsingContext) {
29561             switch (parsingContext) {
29562                 case 5 /* ClassMembers */:
29563                     return isReusableClassMember(node);
29564                 case 2 /* SwitchClauses */:
29565                     return isReusableSwitchClause(node);
29566                 case 0 /* SourceElements */:
29567                 case 1 /* BlockStatements */:
29568                 case 3 /* SwitchClauseStatements */:
29569                     return isReusableStatement(node);
29570                 case 6 /* EnumMembers */:
29571                     return isReusableEnumMember(node);
29572                 case 4 /* TypeMembers */:
29573                     return isReusableTypeMember(node);
29574                 case 8 /* VariableDeclarations */:
29575                     return isReusableVariableDeclaration(node);
29576                 case 17 /* JSDocParameters */:
29577                 case 16 /* Parameters */:
29578                     return isReusableParameter(node);
29579                 // Any other lists we do not care about reusing nodes in.  But feel free to add if
29580                 // you can do so safely.  Danger areas involve nodes that may involve speculative
29581                 // parsing.  If speculative parsing is involved with the node, then the range the
29582                 // parser reached while looking ahead might be in the edited range (see the example
29583                 // in canReuseVariableDeclaratorNode for a good case of this).
29584                 // case ParsingContext.HeritageClauses:
29585                 // This would probably be safe to reuse.  There is no speculative parsing with
29586                 // heritage clauses.
29587                 // case ParsingContext.TypeParameters:
29588                 // This would probably be safe to reuse.  There is no speculative parsing with
29589                 // type parameters.  Note that that's because type *parameters* only occur in
29590                 // unambiguous *type* contexts.  While type *arguments* occur in very ambiguous
29591                 // *expression* contexts.
29592                 // case ParsingContext.TupleElementTypes:
29593                 // This would probably be safe to reuse.  There is no speculative parsing with
29594                 // tuple types.
29595                 // Technically, type argument list types are probably safe to reuse.  While
29596                 // speculative parsing is involved with them (since type argument lists are only
29597                 // produced from speculative parsing a < as a type argument list), we only have
29598                 // the types because speculative parsing succeeded.  Thus, the lookahead never
29599                 // went past the end of the list and rewound.
29600                 // case ParsingContext.TypeArguments:
29601                 // Note: these are almost certainly not safe to ever reuse.  Expressions commonly
29602                 // need a large amount of lookahead, and we should not reuse them as they may
29603                 // have actually intersected the edit.
29604                 // case ParsingContext.ArgumentExpressions:
29605                 // This is not safe to reuse for the same reason as the 'AssignmentExpression'
29606                 // cases.  i.e. a property assignment may end with an expression, and thus might
29607                 // have lookahead far beyond it's old node.
29608                 // case ParsingContext.ObjectLiteralMembers:
29609                 // This is probably not safe to reuse.  There can be speculative parsing with
29610                 // type names in a heritage clause.  There can be generic names in the type
29611                 // name list, and there can be left hand side expressions (which can have type
29612                 // arguments.)
29613                 // case ParsingContext.HeritageClauseElement:
29614                 // Perhaps safe to reuse, but it's unlikely we'd see more than a dozen attributes
29615                 // on any given element. Same for children.
29616                 // case ParsingContext.JsxAttributes:
29617                 // case ParsingContext.JsxChildren:
29618             }
29619             return false;
29620         }
29621         function isReusableClassMember(node) {
29622             if (node) {
29623                 switch (node.kind) {
29624                     case 166 /* Constructor */:
29625                     case 171 /* IndexSignature */:
29626                     case 167 /* GetAccessor */:
29627                     case 168 /* SetAccessor */:
29628                     case 163 /* PropertyDeclaration */:
29629                     case 229 /* SemicolonClassElement */:
29630                         return true;
29631                     case 165 /* MethodDeclaration */:
29632                         // Method declarations are not necessarily reusable.  An object-literal
29633                         // may have a method calls "constructor(...)" and we must reparse that
29634                         // into an actual .ConstructorDeclaration.
29635                         var methodDeclaration = node;
29636                         var nameIsConstructor = methodDeclaration.name.kind === 78 /* Identifier */ &&
29637                             methodDeclaration.name.originalKeywordKind === 132 /* ConstructorKeyword */;
29638                         return !nameIsConstructor;
29639                 }
29640             }
29641             return false;
29642         }
29643         function isReusableSwitchClause(node) {
29644             if (node) {
29645                 switch (node.kind) {
29646                     case 284 /* CaseClause */:
29647                     case 285 /* DefaultClause */:
29648                         return true;
29649                 }
29650             }
29651             return false;
29652         }
29653         function isReusableStatement(node) {
29654             if (node) {
29655                 switch (node.kind) {
29656                     case 251 /* FunctionDeclaration */:
29657                     case 232 /* VariableStatement */:
29658                     case 230 /* Block */:
29659                     case 234 /* IfStatement */:
29660                     case 233 /* ExpressionStatement */:
29661                     case 246 /* ThrowStatement */:
29662                     case 242 /* ReturnStatement */:
29663                     case 244 /* SwitchStatement */:
29664                     case 241 /* BreakStatement */:
29665                     case 240 /* ContinueStatement */:
29666                     case 238 /* ForInStatement */:
29667                     case 239 /* ForOfStatement */:
29668                     case 237 /* ForStatement */:
29669                     case 236 /* WhileStatement */:
29670                     case 243 /* WithStatement */:
29671                     case 231 /* EmptyStatement */:
29672                     case 247 /* TryStatement */:
29673                     case 245 /* LabeledStatement */:
29674                     case 235 /* DoStatement */:
29675                     case 248 /* DebuggerStatement */:
29676                     case 261 /* ImportDeclaration */:
29677                     case 260 /* ImportEqualsDeclaration */:
29678                     case 267 /* ExportDeclaration */:
29679                     case 266 /* ExportAssignment */:
29680                     case 256 /* ModuleDeclaration */:
29681                     case 252 /* ClassDeclaration */:
29682                     case 253 /* InterfaceDeclaration */:
29683                     case 255 /* EnumDeclaration */:
29684                     case 254 /* TypeAliasDeclaration */:
29685                         return true;
29686                 }
29687             }
29688             return false;
29689         }
29690         function isReusableEnumMember(node) {
29691             return node.kind === 291 /* EnumMember */;
29692         }
29693         function isReusableTypeMember(node) {
29694             if (node) {
29695                 switch (node.kind) {
29696                     case 170 /* ConstructSignature */:
29697                     case 164 /* MethodSignature */:
29698                     case 171 /* IndexSignature */:
29699                     case 162 /* PropertySignature */:
29700                     case 169 /* CallSignature */:
29701                         return true;
29702                 }
29703             }
29704             return false;
29705         }
29706         function isReusableVariableDeclaration(node) {
29707             if (node.kind !== 249 /* VariableDeclaration */) {
29708                 return false;
29709             }
29710             // Very subtle incremental parsing bug.  Consider the following code:
29711             //
29712             //      let v = new List < A, B
29713             //
29714             // This is actually legal code.  It's a list of variable declarators "v = new List<A"
29715             // on one side and "B" on the other. If you then change that to:
29716             //
29717             //      let v = new List < A, B >()
29718             //
29719             // then we have a problem.  "v = new List<A" doesn't intersect the change range, so we
29720             // start reparsing at "B" and we completely fail to handle this properly.
29721             //
29722             // In order to prevent this, we do not allow a variable declarator to be reused if it
29723             // has an initializer.
29724             var variableDeclarator = node;
29725             return variableDeclarator.initializer === undefined;
29726         }
29727         function isReusableParameter(node) {
29728             if (node.kind !== 160 /* Parameter */) {
29729                 return false;
29730             }
29731             // See the comment in isReusableVariableDeclaration for why we do this.
29732             var parameter = node;
29733             return parameter.initializer === undefined;
29734         }
29735         // Returns true if we should abort parsing.
29736         function abortParsingListOrMoveToNextToken(kind) {
29737             parsingContextErrors(kind);
29738             if (isInSomeParsingContext()) {
29739                 return true;
29740             }
29741             nextToken();
29742             return false;
29743         }
29744         function parsingContextErrors(context) {
29745             switch (context) {
29746                 case 0 /* SourceElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected);
29747                 case 1 /* BlockStatements */: return parseErrorAtCurrentToken(ts.Diagnostics.Declaration_or_statement_expected);
29748                 case 2 /* SwitchClauses */: return parseErrorAtCurrentToken(ts.Diagnostics.case_or_default_expected);
29749                 case 3 /* SwitchClauseStatements */: return parseErrorAtCurrentToken(ts.Diagnostics.Statement_expected);
29750                 case 18 /* RestProperties */: // fallthrough
29751                 case 4 /* TypeMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_or_signature_expected);
29752                 case 5 /* ClassMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token_A_constructor_method_accessor_or_property_was_expected);
29753                 case 6 /* EnumMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Enum_member_expected);
29754                 case 7 /* HeritageClauseElement */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_expected);
29755                 case 8 /* VariableDeclarations */:
29756                     return ts.isKeyword(token())
29757                         ? parseErrorAtCurrentToken(ts.Diagnostics._0_is_not_allowed_as_a_variable_declaration_name, ts.tokenToString(token()))
29758                         : parseErrorAtCurrentToken(ts.Diagnostics.Variable_declaration_expected);
29759                 case 9 /* ObjectBindingElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_destructuring_pattern_expected);
29760                 case 10 /* ArrayBindingElements */: return parseErrorAtCurrentToken(ts.Diagnostics.Array_element_destructuring_pattern_expected);
29761                 case 11 /* ArgumentExpressions */: return parseErrorAtCurrentToken(ts.Diagnostics.Argument_expression_expected);
29762                 case 12 /* ObjectLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Property_assignment_expected);
29763                 case 15 /* ArrayLiteralMembers */: return parseErrorAtCurrentToken(ts.Diagnostics.Expression_or_comma_expected);
29764                 case 17 /* JSDocParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected);
29765                 case 16 /* Parameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Parameter_declaration_expected);
29766                 case 19 /* TypeParameters */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_parameter_declaration_expected);
29767                 case 20 /* TypeArguments */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_argument_expected);
29768                 case 21 /* TupleElementTypes */: return parseErrorAtCurrentToken(ts.Diagnostics.Type_expected);
29769                 case 22 /* HeritageClauses */: return parseErrorAtCurrentToken(ts.Diagnostics.Unexpected_token_expected);
29770                 case 23 /* ImportOrExportSpecifiers */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
29771                 case 13 /* JsxAttributes */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
29772                 case 14 /* JsxChildren */: return parseErrorAtCurrentToken(ts.Diagnostics.Identifier_expected);
29773                 default: return [undefined]; // TODO: GH#18217 `default: Debug.assertNever(context);`
29774             }
29775         }
29776         // Parses a comma-delimited list of elements
29777         function parseDelimitedList(kind, parseElement, considerSemicolonAsDelimiter) {
29778             var saveParsingContext = parsingContext;
29779             parsingContext |= 1 << kind;
29780             var list = [];
29781             var listPos = getNodePos();
29782             var commaStart = -1; // Meaning the previous token was not a comma
29783             while (true) {
29784                 if (isListElement(kind, /*inErrorRecovery*/ false)) {
29785                     var startPos = scanner.getStartPos();
29786                     list.push(parseListElement(kind, parseElement));
29787                     commaStart = scanner.getTokenPos();
29788                     if (parseOptional(27 /* CommaToken */)) {
29789                         // No need to check for a zero length node since we know we parsed a comma
29790                         continue;
29791                     }
29792                     commaStart = -1; // Back to the state where the last token was not a comma
29793                     if (isListTerminator(kind)) {
29794                         break;
29795                     }
29796                     // We didn't get a comma, and the list wasn't terminated, explicitly parse
29797                     // out a comma so we give a good error message.
29798                     parseExpected(27 /* CommaToken */, getExpectedCommaDiagnostic(kind));
29799                     // If the token was a semicolon, and the caller allows that, then skip it and
29800                     // continue.  This ensures we get back on track and don't result in tons of
29801                     // parse errors.  For example, this can happen when people do things like use
29802                     // a semicolon to delimit object literal members.   Note: we'll have already
29803                     // reported an error when we called parseExpected above.
29804                     if (considerSemicolonAsDelimiter && token() === 26 /* SemicolonToken */ && !scanner.hasPrecedingLineBreak()) {
29805                         nextToken();
29806                     }
29807                     if (startPos === scanner.getStartPos()) {
29808                         // What we're parsing isn't actually remotely recognizable as a element and we've consumed no tokens whatsoever
29809                         // Consume a token to advance the parser in some way and avoid an infinite loop
29810                         // This can happen when we're speculatively parsing parenthesized expressions which we think may be arrow functions,
29811                         // or when a modifier keyword which is disallowed as a parameter name (ie, `static` in strict mode) is supplied
29812                         nextToken();
29813                     }
29814                     continue;
29815                 }
29816                 if (isListTerminator(kind)) {
29817                     break;
29818                 }
29819                 if (abortParsingListOrMoveToNextToken(kind)) {
29820                     break;
29821                 }
29822             }
29823             parsingContext = saveParsingContext;
29824             // Recording the trailing comma is deliberately done after the previous
29825             // loop, and not just if we see a list terminator. This is because the list
29826             // may have ended incorrectly, but it is still important to know if there
29827             // was a trailing comma.
29828             // Check if the last token was a comma.
29829             // Always preserve a trailing comma by marking it on the NodeArray
29830             return createNodeArray(list, listPos, /*end*/ undefined, commaStart >= 0);
29831         }
29832         function getExpectedCommaDiagnostic(kind) {
29833             return kind === 6 /* EnumMembers */ ? ts.Diagnostics.An_enum_member_name_must_be_followed_by_a_or : undefined;
29834         }
29835         function createMissingList() {
29836             var list = createNodeArray([], getNodePos());
29837             list.isMissingList = true;
29838             return list;
29839         }
29840         function isMissingList(arr) {
29841             return !!arr.isMissingList;
29842         }
29843         function parseBracketedList(kind, parseElement, open, close) {
29844             if (parseExpected(open)) {
29845                 var result = parseDelimitedList(kind, parseElement);
29846                 parseExpected(close);
29847                 return result;
29848             }
29849             return createMissingList();
29850         }
29851         function parseEntityName(allowReservedWords, diagnosticMessage) {
29852             var pos = getNodePos();
29853             var entity = allowReservedWords ? parseIdentifierName(diagnosticMessage) : parseIdentifier(diagnosticMessage);
29854             var dotPos = getNodePos();
29855             while (parseOptional(24 /* DotToken */)) {
29856                 if (token() === 29 /* LessThanToken */) {
29857                     // the entity is part of a JSDoc-style generic, so record the trailing dot for later error reporting
29858                     entity.jsdocDotPos = dotPos;
29859                     break;
29860                 }
29861                 dotPos = getNodePos();
29862                 entity = finishNode(factory.createQualifiedName(entity, parseRightSideOfDot(allowReservedWords, /* allowPrivateIdentifiers */ false)), pos);
29863             }
29864             return entity;
29865         }
29866         function createQualifiedName(entity, name) {
29867             return finishNode(factory.createQualifiedName(entity, name), entity.pos);
29868         }
29869         function parseRightSideOfDot(allowIdentifierNames, allowPrivateIdentifiers) {
29870             // Technically a keyword is valid here as all identifiers and keywords are identifier names.
29871             // However, often we'll encounter this in error situations when the identifier or keyword
29872             // is actually starting another valid construct.
29873             //
29874             // So, we check for the following specific case:
29875             //
29876             //      name.
29877             //      identifierOrKeyword identifierNameOrKeyword
29878             //
29879             // Note: the newlines are important here.  For example, if that above code
29880             // were rewritten into:
29881             //
29882             //      name.identifierOrKeyword
29883             //      identifierNameOrKeyword
29884             //
29885             // Then we would consider it valid.  That's because ASI would take effect and
29886             // the code would be implicitly: "name.identifierOrKeyword; identifierNameOrKeyword".
29887             // In the first case though, ASI will not take effect because there is not a
29888             // line terminator after the identifier or keyword.
29889             if (scanner.hasPrecedingLineBreak() && ts.tokenIsIdentifierOrKeyword(token())) {
29890                 var matchesPattern = lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
29891                 if (matchesPattern) {
29892                     // Report that we need an identifier.  However, report it right after the dot,
29893                     // and not on the next token.  This is because the next token might actually
29894                     // be an identifier and the error would be quite confusing.
29895                     return createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
29896                 }
29897             }
29898             if (token() === 79 /* PrivateIdentifier */) {
29899                 var node = parsePrivateIdentifier();
29900                 return allowPrivateIdentifiers ? node : createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Identifier_expected);
29901             }
29902             return allowIdentifierNames ? parseIdentifierName() : parseIdentifier();
29903         }
29904         function parseTemplateSpans(isTaggedTemplate) {
29905             var pos = getNodePos();
29906             var list = [];
29907             var node;
29908             do {
29909                 node = parseTemplateSpan(isTaggedTemplate);
29910                 list.push(node);
29911             } while (node.literal.kind === 16 /* TemplateMiddle */);
29912             return createNodeArray(list, pos);
29913         }
29914         function parseTemplateExpression(isTaggedTemplate) {
29915             var pos = getNodePos();
29916             return finishNode(factory.createTemplateExpression(parseTemplateHead(isTaggedTemplate), parseTemplateSpans(isTaggedTemplate)), pos);
29917         }
29918         function parseTemplateType() {
29919             var pos = getNodePos();
29920             return finishNode(factory.createTemplateLiteralType(parseTemplateHead(/*isTaggedTemplate*/ false), parseTemplateTypeSpans()), pos);
29921         }
29922         function parseTemplateTypeSpans() {
29923             var pos = getNodePos();
29924             var list = [];
29925             var node;
29926             do {
29927                 node = parseTemplateTypeSpan();
29928                 list.push(node);
29929             } while (node.literal.kind === 16 /* TemplateMiddle */);
29930             return createNodeArray(list, pos);
29931         }
29932         function parseTemplateTypeSpan() {
29933             var pos = getNodePos();
29934             return finishNode(factory.createTemplateLiteralTypeSpan(parseType(), parseLiteralOfTemplateSpan(/*isTaggedTemplate*/ false)), pos);
29935         }
29936         function parseLiteralOfTemplateSpan(isTaggedTemplate) {
29937             if (token() === 19 /* CloseBraceToken */) {
29938                 reScanTemplateToken(isTaggedTemplate);
29939                 return parseTemplateMiddleOrTemplateTail();
29940             }
29941             else {
29942                 // TODO(rbuckton): Do we need to call `parseExpectedToken` or can we just call `createMissingNode` directly?
29943                 return parseExpectedToken(17 /* TemplateTail */, ts.Diagnostics._0_expected, ts.tokenToString(19 /* CloseBraceToken */));
29944             }
29945         }
29946         function parseTemplateSpan(isTaggedTemplate) {
29947             var pos = getNodePos();
29948             return finishNode(factory.createTemplateSpan(allowInAnd(parseExpression), parseLiteralOfTemplateSpan(isTaggedTemplate)), pos);
29949         }
29950         function parseLiteralNode() {
29951             return parseLiteralLikeNode(token());
29952         }
29953         function parseTemplateHead(isTaggedTemplate) {
29954             if (isTaggedTemplate) {
29955                 reScanTemplateHeadOrNoSubstitutionTemplate();
29956             }
29957             var fragment = parseLiteralLikeNode(token());
29958             ts.Debug.assert(fragment.kind === 15 /* TemplateHead */, "Template head has wrong token kind");
29959             return fragment;
29960         }
29961         function parseTemplateMiddleOrTemplateTail() {
29962             var fragment = parseLiteralLikeNode(token());
29963             ts.Debug.assert(fragment.kind === 16 /* TemplateMiddle */ || fragment.kind === 17 /* TemplateTail */, "Template fragment has wrong token kind");
29964             return fragment;
29965         }
29966         function getTemplateLiteralRawText(kind) {
29967             var isLast = kind === 14 /* NoSubstitutionTemplateLiteral */ || kind === 17 /* TemplateTail */;
29968             var tokenText = scanner.getTokenText();
29969             return tokenText.substring(1, tokenText.length - (scanner.isUnterminated() ? 0 : isLast ? 1 : 2));
29970         }
29971         function parseLiteralLikeNode(kind) {
29972             var pos = getNodePos();
29973             var node = ts.isTemplateLiteralKind(kind) ? factory.createTemplateLiteralLikeNode(kind, scanner.getTokenValue(), getTemplateLiteralRawText(kind), scanner.getTokenFlags() & 2048 /* TemplateLiteralLikeFlags */) :
29974                 // Octal literals are not allowed in strict mode or ES5
29975                 // Note that theoretically the following condition would hold true literals like 009,
29976                 // which is not octal. But because of how the scanner separates the tokens, we would
29977                 // never get a token like this. Instead, we would get 00 and 9 as two separate tokens.
29978                 // We also do not need to check for negatives because any prefix operator would be part of a
29979                 // parent unary expression.
29980                 kind === 8 /* NumericLiteral */ ? factory.createNumericLiteral(scanner.getTokenValue(), scanner.getNumericLiteralFlags()) :
29981                     kind === 10 /* StringLiteral */ ? factory.createStringLiteral(scanner.getTokenValue(), /*isSingleQuote*/ undefined, scanner.hasExtendedUnicodeEscape()) :
29982                         ts.isLiteralKind(kind) ? factory.createLiteralLikeNode(kind, scanner.getTokenValue()) :
29983                             ts.Debug.fail();
29984             if (scanner.hasExtendedUnicodeEscape()) {
29985                 node.hasExtendedUnicodeEscape = true;
29986             }
29987             if (scanner.isUnterminated()) {
29988                 node.isUnterminated = true;
29989             }
29990             nextToken();
29991             return finishNode(node, pos);
29992         }
29993         // TYPES
29994         function parseEntityNameOfTypeReference() {
29995             return parseEntityName(/*allowReservedWords*/ true, ts.Diagnostics.Type_expected);
29996         }
29997         function parseTypeArgumentsOfTypeReference() {
29998             if (!scanner.hasPrecedingLineBreak() && reScanLessThanToken() === 29 /* LessThanToken */) {
29999                 return parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
30000             }
30001         }
30002         function parseTypeReference() {
30003             var pos = getNodePos();
30004             return finishNode(factory.createTypeReferenceNode(parseEntityNameOfTypeReference(), parseTypeArgumentsOfTypeReference()), pos);
30005         }
30006         // If true, we should abort parsing an error function.
30007         function typeHasArrowFunctionBlockingParseError(node) {
30008             switch (node.kind) {
30009                 case 173 /* TypeReference */:
30010                     return ts.nodeIsMissing(node.typeName);
30011                 case 174 /* FunctionType */:
30012                 case 175 /* ConstructorType */: {
30013                     var _a = node, parameters = _a.parameters, type = _a.type;
30014                     return isMissingList(parameters) || typeHasArrowFunctionBlockingParseError(type);
30015                 }
30016                 case 186 /* ParenthesizedType */:
30017                     return typeHasArrowFunctionBlockingParseError(node.type);
30018                 default:
30019                     return false;
30020             }
30021         }
30022         function parseThisTypePredicate(lhs) {
30023             nextToken();
30024             return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, lhs, parseType()), lhs.pos);
30025         }
30026         function parseThisTypeNode() {
30027             var pos = getNodePos();
30028             nextToken();
30029             return finishNode(factory.createThisTypeNode(), pos);
30030         }
30031         function parseJSDocAllType() {
30032             var pos = getNodePos();
30033             nextToken();
30034             return finishNode(factory.createJSDocAllType(), pos);
30035         }
30036         function parseJSDocNonNullableType() {
30037             var pos = getNodePos();
30038             nextToken();
30039             return finishNode(factory.createJSDocNonNullableType(parseNonArrayType()), pos);
30040         }
30041         function parseJSDocUnknownOrNullableType() {
30042             var pos = getNodePos();
30043             // skip the ?
30044             nextToken();
30045             // Need to lookahead to decide if this is a nullable or unknown type.
30046             // Here are cases where we'll pick the unknown type:
30047             //
30048             //      Foo(?,
30049             //      { a: ? }
30050             //      Foo(?)
30051             //      Foo<?>
30052             //      Foo(?=
30053             //      (?|
30054             if (token() === 27 /* CommaToken */ ||
30055                 token() === 19 /* CloseBraceToken */ ||
30056                 token() === 21 /* CloseParenToken */ ||
30057                 token() === 31 /* GreaterThanToken */ ||
30058                 token() === 62 /* EqualsToken */ ||
30059                 token() === 51 /* BarToken */) {
30060                 return finishNode(factory.createJSDocUnknownType(), pos);
30061             }
30062             else {
30063                 return finishNode(factory.createJSDocNullableType(parseType()), pos);
30064             }
30065         }
30066         function parseJSDocFunctionType() {
30067             var pos = getNodePos();
30068             var hasJSDoc = hasPrecedingJSDocComment();
30069             if (lookAhead(nextTokenIsOpenParen)) {
30070                 nextToken();
30071                 var parameters = parseParameters(4 /* Type */ | 32 /* JSDoc */);
30072                 var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
30073                 return withJSDoc(finishNode(factory.createJSDocFunctionType(parameters, type), pos), hasJSDoc);
30074             }
30075             return finishNode(factory.createTypeReferenceNode(parseIdentifierName(), /*typeArguments*/ undefined), pos);
30076         }
30077         function parseJSDocParameter() {
30078             var pos = getNodePos();
30079             var name;
30080             if (token() === 107 /* ThisKeyword */ || token() === 102 /* NewKeyword */) {
30081                 name = parseIdentifierName();
30082                 parseExpected(58 /* ColonToken */);
30083             }
30084             return finishNode(factory.createParameterDeclaration(
30085             /*decorators*/ undefined, 
30086             /*modifiers*/ undefined, 
30087             /*dotDotDotToken*/ undefined, 
30088             // TODO(rbuckton): JSDoc parameters don't have names (except `this`/`new`), should we manufacture an empty identifier?
30089             name, 
30090             /*questionToken*/ undefined, parseJSDocType(), 
30091             /*initializer*/ undefined), pos);
30092         }
30093         function parseJSDocType() {
30094             scanner.setInJSDocType(true);
30095             var pos = getNodePos();
30096             if (parseOptional(139 /* ModuleKeyword */)) {
30097                 // TODO(rbuckton): We never set the type for a JSDocNamepathType. What should we put here?
30098                 var moduleTag = factory.createJSDocNamepathType(/*type*/ undefined);
30099                 terminate: while (true) {
30100                     switch (token()) {
30101                         case 19 /* CloseBraceToken */:
30102                         case 1 /* EndOfFileToken */:
30103                         case 27 /* CommaToken */:
30104                         case 5 /* WhitespaceTrivia */:
30105                             break terminate;
30106                         default:
30107                             nextTokenJSDoc();
30108                     }
30109                 }
30110                 scanner.setInJSDocType(false);
30111                 return finishNode(moduleTag, pos);
30112             }
30113             var hasDotDotDot = parseOptional(25 /* DotDotDotToken */);
30114             var type = parseTypeOrTypePredicate();
30115             scanner.setInJSDocType(false);
30116             if (hasDotDotDot) {
30117                 type = finishNode(factory.createJSDocVariadicType(type), pos);
30118             }
30119             if (token() === 62 /* EqualsToken */) {
30120                 nextToken();
30121                 return finishNode(factory.createJSDocOptionalType(type), pos);
30122             }
30123             return type;
30124         }
30125         function parseTypeQuery() {
30126             var pos = getNodePos();
30127             parseExpected(111 /* TypeOfKeyword */);
30128             return finishNode(factory.createTypeQueryNode(parseEntityName(/*allowReservedWords*/ true)), pos);
30129         }
30130         function parseTypeParameter() {
30131             var pos = getNodePos();
30132             var name = parseIdentifier();
30133             var constraint;
30134             var expression;
30135             if (parseOptional(93 /* ExtendsKeyword */)) {
30136                 // It's not uncommon for people to write improper constraints to a generic.  If the
30137                 // user writes a constraint that is an expression and not an actual type, then parse
30138                 // it out as an expression (so we can recover well), but report that a type is needed
30139                 // instead.
30140                 if (isStartOfType() || !isStartOfExpression()) {
30141                     constraint = parseType();
30142                 }
30143                 else {
30144                     // It was not a type, and it looked like an expression.  Parse out an expression
30145                     // here so we recover well.  Note: it is important that we call parseUnaryExpression
30146                     // and not parseExpression here.  If the user has:
30147                     //
30148                     //      <T extends "">
30149                     //
30150                     // We do *not* want to consume the `>` as we're consuming the expression for "".
30151                     expression = parseUnaryExpressionOrHigher();
30152                 }
30153             }
30154             var defaultType = parseOptional(62 /* EqualsToken */) ? parseType() : undefined;
30155             var node = factory.createTypeParameterDeclaration(name, constraint, defaultType);
30156             node.expression = expression;
30157             return finishNode(node, pos);
30158         }
30159         function parseTypeParameters() {
30160             if (token() === 29 /* LessThanToken */) {
30161                 return parseBracketedList(19 /* TypeParameters */, parseTypeParameter, 29 /* LessThanToken */, 31 /* GreaterThanToken */);
30162             }
30163         }
30164         function isStartOfParameter(isJSDocParameter) {
30165             return token() === 25 /* DotDotDotToken */ ||
30166                 isBindingIdentifierOrPrivateIdentifierOrPattern() ||
30167                 ts.isModifierKind(token()) ||
30168                 token() === 59 /* AtToken */ ||
30169                 isStartOfType(/*inStartOfParameter*/ !isJSDocParameter);
30170         }
30171         function parseNameOfParameter(modifiers) {
30172             // FormalParameter [Yield,Await]:
30173             //      BindingElement[?Yield,?Await]
30174             var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_cannot_be_used_as_parameters);
30175             if (ts.getFullWidth(name) === 0 && !ts.some(modifiers) && ts.isModifierKind(token())) {
30176                 // in cases like
30177                 // 'use strict'
30178                 // function foo(static)
30179                 // isParameter('static') === true, because of isModifier('static')
30180                 // however 'static' is not a legal identifier in a strict mode.
30181                 // so result of this function will be ParameterDeclaration (flags = 0, name = missing, type = undefined, initializer = undefined)
30182                 // and current token will not change => parsing of the enclosing parameter list will last till the end of time (or OOM)
30183                 // to avoid this we'll advance cursor to the next token.
30184                 nextToken();
30185             }
30186             return name;
30187         }
30188         function parseParameterInOuterAwaitContext() {
30189             return parseParameterWorker(/*inOuterAwaitContext*/ true);
30190         }
30191         function parseParameter() {
30192             return parseParameterWorker(/*inOuterAwaitContext*/ false);
30193         }
30194         function parseParameterWorker(inOuterAwaitContext) {
30195             var pos = getNodePos();
30196             var hasJSDoc = hasPrecedingJSDocComment();
30197             if (token() === 107 /* ThisKeyword */) {
30198                 var node_1 = factory.createParameterDeclaration(
30199                 /*decorators*/ undefined, 
30200                 /*modifiers*/ undefined, 
30201                 /*dotDotDotToken*/ undefined, createIdentifier(/*isIdentifier*/ true), 
30202                 /*questionToken*/ undefined, parseTypeAnnotation(), 
30203                 /*initializer*/ undefined);
30204                 return withJSDoc(finishNode(node_1, pos), hasJSDoc);
30205             }
30206             // FormalParameter [Yield,Await]:
30207             //      BindingElement[?Yield,?Await]
30208             // Decorators are parsed in the outer [Await] context, the rest of the parameter is parsed in the function's [Await] context.
30209             var decorators = inOuterAwaitContext ? doInAwaitContext(parseDecorators) : parseDecorators();
30210             var savedTopLevel = topLevel;
30211             topLevel = false;
30212             var modifiers = parseModifiers();
30213             var node = withJSDoc(finishNode(factory.createParameterDeclaration(decorators, modifiers, parseOptionalToken(25 /* DotDotDotToken */), parseNameOfParameter(modifiers), parseOptionalToken(57 /* QuestionToken */), parseTypeAnnotation(), parseInitializer()), pos), hasJSDoc);
30214             topLevel = savedTopLevel;
30215             return node;
30216         }
30217         function parseReturnType(returnToken, isType) {
30218             if (shouldParseReturnType(returnToken, isType)) {
30219                 return parseTypeOrTypePredicate();
30220             }
30221         }
30222         function shouldParseReturnType(returnToken, isType) {
30223             if (returnToken === 38 /* EqualsGreaterThanToken */) {
30224                 parseExpected(returnToken);
30225                 return true;
30226             }
30227             else if (parseOptional(58 /* ColonToken */)) {
30228                 return true;
30229             }
30230             else if (isType && token() === 38 /* EqualsGreaterThanToken */) {
30231                 // This is easy to get backward, especially in type contexts, so parse the type anyway
30232                 parseErrorAtCurrentToken(ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */));
30233                 nextToken();
30234                 return true;
30235             }
30236             return false;
30237         }
30238         function parseParametersWorker(flags) {
30239             // FormalParameters [Yield,Await]: (modified)
30240             //      [empty]
30241             //      FormalParameterList[?Yield,Await]
30242             //
30243             // FormalParameter[Yield,Await]: (modified)
30244             //      BindingElement[?Yield,Await]
30245             //
30246             // BindingElement [Yield,Await]: (modified)
30247             //      SingleNameBinding[?Yield,?Await]
30248             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30249             //
30250             // SingleNameBinding [Yield,Await]:
30251             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30252             var savedYieldContext = inYieldContext();
30253             var savedAwaitContext = inAwaitContext();
30254             setYieldContext(!!(flags & 1 /* Yield */));
30255             setAwaitContext(!!(flags & 2 /* Await */));
30256             var parameters = flags & 32 /* JSDoc */ ?
30257                 parseDelimitedList(17 /* JSDocParameters */, parseJSDocParameter) :
30258                 parseDelimitedList(16 /* Parameters */, savedAwaitContext ? parseParameterInOuterAwaitContext : parseParameter);
30259             setYieldContext(savedYieldContext);
30260             setAwaitContext(savedAwaitContext);
30261             return parameters;
30262         }
30263         function parseParameters(flags) {
30264             // FormalParameters [Yield,Await]: (modified)
30265             //      [empty]
30266             //      FormalParameterList[?Yield,Await]
30267             //
30268             // FormalParameter[Yield,Await]: (modified)
30269             //      BindingElement[?Yield,Await]
30270             //
30271             // BindingElement [Yield,Await]: (modified)
30272             //      SingleNameBinding[?Yield,?Await]
30273             //      BindingPattern[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30274             //
30275             // SingleNameBinding [Yield,Await]:
30276             //      BindingIdentifier[?Yield,?Await]Initializer [In, ?Yield,?Await] opt
30277             if (!parseExpected(20 /* OpenParenToken */)) {
30278                 return createMissingList();
30279             }
30280             var parameters = parseParametersWorker(flags);
30281             parseExpected(21 /* CloseParenToken */);
30282             return parameters;
30283         }
30284         function parseTypeMemberSemicolon() {
30285             // We allow type members to be separated by commas or (possibly ASI) semicolons.
30286             // First check if it was a comma.  If so, we're done with the member.
30287             if (parseOptional(27 /* CommaToken */)) {
30288                 return;
30289             }
30290             // Didn't have a comma.  We must have a (possible ASI) semicolon.
30291             parseSemicolon();
30292         }
30293         function parseSignatureMember(kind) {
30294             var pos = getNodePos();
30295             var hasJSDoc = hasPrecedingJSDocComment();
30296             if (kind === 170 /* ConstructSignature */) {
30297                 parseExpected(102 /* NewKeyword */);
30298             }
30299             var typeParameters = parseTypeParameters();
30300             var parameters = parseParameters(4 /* Type */);
30301             var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
30302             parseTypeMemberSemicolon();
30303             var node = kind === 169 /* CallSignature */
30304                 ? factory.createCallSignature(typeParameters, parameters, type)
30305                 : factory.createConstructSignature(typeParameters, parameters, type);
30306             return withJSDoc(finishNode(node, pos), hasJSDoc);
30307         }
30308         function isIndexSignature() {
30309             return token() === 22 /* OpenBracketToken */ && lookAhead(isUnambiguouslyIndexSignature);
30310         }
30311         function isUnambiguouslyIndexSignature() {
30312             // The only allowed sequence is:
30313             //
30314             //   [id:
30315             //
30316             // However, for error recovery, we also check the following cases:
30317             //
30318             //   [...
30319             //   [id,
30320             //   [id?,
30321             //   [id?:
30322             //   [id?]
30323             //   [public id
30324             //   [private id
30325             //   [protected id
30326             //   []
30327             //
30328             nextToken();
30329             if (token() === 25 /* DotDotDotToken */ || token() === 23 /* CloseBracketToken */) {
30330                 return true;
30331             }
30332             if (ts.isModifierKind(token())) {
30333                 nextToken();
30334                 if (isIdentifier()) {
30335                     return true;
30336                 }
30337             }
30338             else if (!isIdentifier()) {
30339                 return false;
30340             }
30341             else {
30342                 // Skip the identifier
30343                 nextToken();
30344             }
30345             // A colon signifies a well formed indexer
30346             // A comma should be a badly formed indexer because comma expressions are not allowed
30347             // in computed properties.
30348             if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */) {
30349                 return true;
30350             }
30351             // Question mark could be an indexer with an optional property,
30352             // or it could be a conditional expression in a computed property.
30353             if (token() !== 57 /* QuestionToken */) {
30354                 return false;
30355             }
30356             // If any of the following tokens are after the question mark, it cannot
30357             // be a conditional expression, so treat it as an indexer.
30358             nextToken();
30359             return token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 23 /* CloseBracketToken */;
30360         }
30361         function parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers) {
30362             var parameters = parseBracketedList(16 /* Parameters */, parseParameter, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */);
30363             var type = parseTypeAnnotation();
30364             parseTypeMemberSemicolon();
30365             var node = factory.createIndexSignature(decorators, modifiers, parameters, type);
30366             return withJSDoc(finishNode(node, pos), hasJSDoc);
30367         }
30368         function parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers) {
30369             var name = parsePropertyName();
30370             var questionToken = parseOptionalToken(57 /* QuestionToken */);
30371             var node;
30372             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
30373                 // Method signatures don't exist in expression contexts.  So they have neither
30374                 // [Yield] nor [Await]
30375                 var typeParameters = parseTypeParameters();
30376                 var parameters = parseParameters(4 /* Type */);
30377                 var type = parseReturnType(58 /* ColonToken */, /*isType*/ true);
30378                 node = factory.createMethodSignature(modifiers, name, questionToken, typeParameters, parameters, type);
30379             }
30380             else {
30381                 var type = parseTypeAnnotation();
30382                 node = factory.createPropertySignature(modifiers, name, questionToken, type);
30383                 // Although type literal properties cannot not have initializers, we attempt
30384                 // to parse an initializer so we can report in the checker that an interface
30385                 // property or type literal property cannot have an initializer.
30386                 if (token() === 62 /* EqualsToken */)
30387                     node.initializer = parseInitializer();
30388             }
30389             parseTypeMemberSemicolon();
30390             return withJSDoc(finishNode(node, pos), hasJSDoc);
30391         }
30392         function isTypeMemberStart() {
30393             // Return true if we have the start of a signature member
30394             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
30395                 return true;
30396             }
30397             var idToken = false;
30398             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier
30399             while (ts.isModifierKind(token())) {
30400                 idToken = true;
30401                 nextToken();
30402             }
30403             // Index signatures and computed property names are type members
30404             if (token() === 22 /* OpenBracketToken */) {
30405                 return true;
30406             }
30407             // Try to get the first property-like token following all modifiers
30408             if (isLiteralPropertyName()) {
30409                 idToken = true;
30410                 nextToken();
30411             }
30412             // If we were able to get any potential identifier, check that it is
30413             // the start of a member declaration
30414             if (idToken) {
30415                 return token() === 20 /* OpenParenToken */ ||
30416                     token() === 29 /* LessThanToken */ ||
30417                     token() === 57 /* QuestionToken */ ||
30418                     token() === 58 /* ColonToken */ ||
30419                     token() === 27 /* CommaToken */ ||
30420                     canParseSemicolon();
30421             }
30422             return false;
30423         }
30424         function parseTypeMember() {
30425             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
30426                 return parseSignatureMember(169 /* CallSignature */);
30427             }
30428             if (token() === 102 /* NewKeyword */ && lookAhead(nextTokenIsOpenParenOrLessThan)) {
30429                 return parseSignatureMember(170 /* ConstructSignature */);
30430             }
30431             var pos = getNodePos();
30432             var hasJSDoc = hasPrecedingJSDocComment();
30433             var modifiers = parseModifiers();
30434             if (isIndexSignature()) {
30435                 return parseIndexSignatureDeclaration(pos, hasJSDoc, /*decorators*/ undefined, modifiers);
30436             }
30437             return parsePropertyOrMethodSignature(pos, hasJSDoc, modifiers);
30438         }
30439         function nextTokenIsOpenParenOrLessThan() {
30440             nextToken();
30441             return token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */;
30442         }
30443         function nextTokenIsDot() {
30444             return nextToken() === 24 /* DotToken */;
30445         }
30446         function nextTokenIsOpenParenOrLessThanOrDot() {
30447             switch (nextToken()) {
30448                 case 20 /* OpenParenToken */:
30449                 case 29 /* LessThanToken */:
30450                 case 24 /* DotToken */:
30451                     return true;
30452             }
30453             return false;
30454         }
30455         function parseTypeLiteral() {
30456             var pos = getNodePos();
30457             return finishNode(factory.createTypeLiteralNode(parseObjectTypeMembers()), pos);
30458         }
30459         function parseObjectTypeMembers() {
30460             var members;
30461             if (parseExpected(18 /* OpenBraceToken */)) {
30462                 members = parseList(4 /* TypeMembers */, parseTypeMember);
30463                 parseExpected(19 /* CloseBraceToken */);
30464             }
30465             else {
30466                 members = createMissingList();
30467             }
30468             return members;
30469         }
30470         function isStartOfMappedType() {
30471             nextToken();
30472             if (token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
30473                 return nextToken() === 142 /* ReadonlyKeyword */;
30474             }
30475             if (token() === 142 /* ReadonlyKeyword */) {
30476                 nextToken();
30477             }
30478             return token() === 22 /* OpenBracketToken */ && nextTokenIsIdentifier() && nextToken() === 100 /* InKeyword */;
30479         }
30480         function parseMappedTypeParameter() {
30481             var pos = getNodePos();
30482             var name = parseIdentifierName();
30483             parseExpected(100 /* InKeyword */);
30484             var type = parseType();
30485             return finishNode(factory.createTypeParameterDeclaration(name, type, /*defaultType*/ undefined), pos);
30486         }
30487         function parseMappedType() {
30488             var pos = getNodePos();
30489             parseExpected(18 /* OpenBraceToken */);
30490             var readonlyToken;
30491             if (token() === 142 /* ReadonlyKeyword */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
30492                 readonlyToken = parseTokenNode();
30493                 if (readonlyToken.kind !== 142 /* ReadonlyKeyword */) {
30494                     parseExpected(142 /* ReadonlyKeyword */);
30495                 }
30496             }
30497             parseExpected(22 /* OpenBracketToken */);
30498             var typeParameter = parseMappedTypeParameter();
30499             var nameType = parseOptional(126 /* AsKeyword */) ? parseType() : undefined;
30500             parseExpected(23 /* CloseBracketToken */);
30501             var questionToken;
30502             if (token() === 57 /* QuestionToken */ || token() === 39 /* PlusToken */ || token() === 40 /* MinusToken */) {
30503                 questionToken = parseTokenNode();
30504                 if (questionToken.kind !== 57 /* QuestionToken */) {
30505                     parseExpected(57 /* QuestionToken */);
30506                 }
30507             }
30508             var type = parseTypeAnnotation();
30509             parseSemicolon();
30510             parseExpected(19 /* CloseBraceToken */);
30511             return finishNode(factory.createMappedTypeNode(readonlyToken, typeParameter, nameType, questionToken, type), pos);
30512         }
30513         function parseTupleElementType() {
30514             var pos = getNodePos();
30515             if (parseOptional(25 /* DotDotDotToken */)) {
30516                 return finishNode(factory.createRestTypeNode(parseType()), pos);
30517             }
30518             var type = parseType();
30519             if (ts.isJSDocNullableType(type) && type.pos === type.type.pos) {
30520                 var node = factory.createOptionalTypeNode(type.type);
30521                 ts.setTextRange(node, type);
30522                 node.flags = type.flags;
30523                 return node;
30524             }
30525             return type;
30526         }
30527         function isNextTokenColonOrQuestionColon() {
30528             return nextToken() === 58 /* ColonToken */ || (token() === 57 /* QuestionToken */ && nextToken() === 58 /* ColonToken */);
30529         }
30530         function isTupleElementName() {
30531             if (token() === 25 /* DotDotDotToken */) {
30532                 return ts.tokenIsIdentifierOrKeyword(nextToken()) && isNextTokenColonOrQuestionColon();
30533             }
30534             return ts.tokenIsIdentifierOrKeyword(token()) && isNextTokenColonOrQuestionColon();
30535         }
30536         function parseTupleElementNameOrTupleElementType() {
30537             if (lookAhead(isTupleElementName)) {
30538                 var pos = getNodePos();
30539                 var hasJSDoc = hasPrecedingJSDocComment();
30540                 var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
30541                 var name = parseIdentifierName();
30542                 var questionToken = parseOptionalToken(57 /* QuestionToken */);
30543                 parseExpected(58 /* ColonToken */);
30544                 var type = parseTupleElementType();
30545                 var node = factory.createNamedTupleMember(dotDotDotToken, name, questionToken, type);
30546                 return withJSDoc(finishNode(node, pos), hasJSDoc);
30547             }
30548             return parseTupleElementType();
30549         }
30550         function parseTupleType() {
30551             var pos = getNodePos();
30552             return finishNode(factory.createTupleTypeNode(parseBracketedList(21 /* TupleElementTypes */, parseTupleElementNameOrTupleElementType, 22 /* OpenBracketToken */, 23 /* CloseBracketToken */)), pos);
30553         }
30554         function parseParenthesizedType() {
30555             var pos = getNodePos();
30556             parseExpected(20 /* OpenParenToken */);
30557             var type = parseType();
30558             parseExpected(21 /* CloseParenToken */);
30559             return finishNode(factory.createParenthesizedType(type), pos);
30560         }
30561         function parseFunctionOrConstructorType() {
30562             var pos = getNodePos();
30563             var hasJSDoc = hasPrecedingJSDocComment();
30564             var isConstructorType = parseOptional(102 /* NewKeyword */);
30565             var typeParameters = parseTypeParameters();
30566             var parameters = parseParameters(4 /* Type */);
30567             var type = parseReturnType(38 /* EqualsGreaterThanToken */, /*isType*/ false);
30568             var node = isConstructorType
30569                 ? factory.createConstructorTypeNode(typeParameters, parameters, type)
30570                 : factory.createFunctionTypeNode(typeParameters, parameters, type);
30571             return withJSDoc(finishNode(node, pos), hasJSDoc);
30572         }
30573         function parseKeywordAndNoDot() {
30574             var node = parseTokenNode();
30575             return token() === 24 /* DotToken */ ? undefined : node;
30576         }
30577         function parseLiteralTypeNode(negative) {
30578             var pos = getNodePos();
30579             if (negative) {
30580                 nextToken();
30581             }
30582             var expression = token() === 109 /* TrueKeyword */ || token() === 94 /* FalseKeyword */ || token() === 103 /* NullKeyword */ ?
30583                 parseTokenNode() :
30584                 parseLiteralLikeNode(token());
30585             if (negative) {
30586                 expression = finishNode(factory.createPrefixUnaryExpression(40 /* MinusToken */, expression), pos);
30587             }
30588             return finishNode(factory.createLiteralTypeNode(expression), pos);
30589         }
30590         function isStartOfTypeOfImportType() {
30591             nextToken();
30592             return token() === 99 /* ImportKeyword */;
30593         }
30594         function parseImportType() {
30595             sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
30596             var pos = getNodePos();
30597             var isTypeOf = parseOptional(111 /* TypeOfKeyword */);
30598             parseExpected(99 /* ImportKeyword */);
30599             parseExpected(20 /* OpenParenToken */);
30600             var type = parseType();
30601             parseExpected(21 /* CloseParenToken */);
30602             var qualifier = parseOptional(24 /* DotToken */) ? parseEntityNameOfTypeReference() : undefined;
30603             var typeArguments = parseTypeArgumentsOfTypeReference();
30604             return finishNode(factory.createImportTypeNode(type, qualifier, typeArguments, isTypeOf), pos);
30605         }
30606         function nextTokenIsNumericOrBigIntLiteral() {
30607             nextToken();
30608             return token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */;
30609         }
30610         function parseNonArrayType() {
30611             switch (token()) {
30612                 case 128 /* AnyKeyword */:
30613                 case 152 /* UnknownKeyword */:
30614                 case 147 /* StringKeyword */:
30615                 case 144 /* NumberKeyword */:
30616                 case 155 /* BigIntKeyword */:
30617                 case 148 /* SymbolKeyword */:
30618                 case 131 /* BooleanKeyword */:
30619                 case 150 /* UndefinedKeyword */:
30620                 case 141 /* NeverKeyword */:
30621                 case 145 /* ObjectKeyword */:
30622                     // If these are followed by a dot, then parse these out as a dotted type reference instead.
30623                     return tryParse(parseKeywordAndNoDot) || parseTypeReference();
30624                 case 65 /* AsteriskEqualsToken */:
30625                     // If there is '*=', treat it as * followed by postfix =
30626                     scanner.reScanAsteriskEqualsToken();
30627                 // falls through
30628                 case 41 /* AsteriskToken */:
30629                     return parseJSDocAllType();
30630                 case 60 /* QuestionQuestionToken */:
30631                     // If there is '??', treat it as prefix-'?' in JSDoc type.
30632                     scanner.reScanQuestionToken();
30633                 // falls through
30634                 case 57 /* QuestionToken */:
30635                     return parseJSDocUnknownOrNullableType();
30636                 case 97 /* FunctionKeyword */:
30637                     return parseJSDocFunctionType();
30638                 case 53 /* ExclamationToken */:
30639                     return parseJSDocNonNullableType();
30640                 case 14 /* NoSubstitutionTemplateLiteral */:
30641                 case 10 /* StringLiteral */:
30642                 case 8 /* NumericLiteral */:
30643                 case 9 /* BigIntLiteral */:
30644                 case 109 /* TrueKeyword */:
30645                 case 94 /* FalseKeyword */:
30646                 case 103 /* NullKeyword */:
30647                     return parseLiteralTypeNode();
30648                 case 40 /* MinusToken */:
30649                     return lookAhead(nextTokenIsNumericOrBigIntLiteral) ? parseLiteralTypeNode(/*negative*/ true) : parseTypeReference();
30650                 case 113 /* VoidKeyword */:
30651                     return parseTokenNode();
30652                 case 107 /* ThisKeyword */: {
30653                     var thisKeyword = parseThisTypeNode();
30654                     if (token() === 137 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
30655                         return parseThisTypePredicate(thisKeyword);
30656                     }
30657                     else {
30658                         return thisKeyword;
30659                     }
30660                 }
30661                 case 111 /* TypeOfKeyword */:
30662                     return lookAhead(isStartOfTypeOfImportType) ? parseImportType() : parseTypeQuery();
30663                 case 18 /* OpenBraceToken */:
30664                     return lookAhead(isStartOfMappedType) ? parseMappedType() : parseTypeLiteral();
30665                 case 22 /* OpenBracketToken */:
30666                     return parseTupleType();
30667                 case 20 /* OpenParenToken */:
30668                     return parseParenthesizedType();
30669                 case 99 /* ImportKeyword */:
30670                     return parseImportType();
30671                 case 127 /* AssertsKeyword */:
30672                     return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
30673                 case 15 /* TemplateHead */:
30674                     return parseTemplateType();
30675                 default:
30676                     return parseTypeReference();
30677             }
30678         }
30679         function isStartOfType(inStartOfParameter) {
30680             switch (token()) {
30681                 case 128 /* AnyKeyword */:
30682                 case 152 /* UnknownKeyword */:
30683                 case 147 /* StringKeyword */:
30684                 case 144 /* NumberKeyword */:
30685                 case 155 /* BigIntKeyword */:
30686                 case 131 /* BooleanKeyword */:
30687                 case 142 /* ReadonlyKeyword */:
30688                 case 148 /* SymbolKeyword */:
30689                 case 151 /* UniqueKeyword */:
30690                 case 113 /* VoidKeyword */:
30691                 case 150 /* UndefinedKeyword */:
30692                 case 103 /* NullKeyword */:
30693                 case 107 /* ThisKeyword */:
30694                 case 111 /* TypeOfKeyword */:
30695                 case 141 /* NeverKeyword */:
30696                 case 18 /* OpenBraceToken */:
30697                 case 22 /* OpenBracketToken */:
30698                 case 29 /* LessThanToken */:
30699                 case 51 /* BarToken */:
30700                 case 50 /* AmpersandToken */:
30701                 case 102 /* NewKeyword */:
30702                 case 10 /* StringLiteral */:
30703                 case 8 /* NumericLiteral */:
30704                 case 9 /* BigIntLiteral */:
30705                 case 109 /* TrueKeyword */:
30706                 case 94 /* FalseKeyword */:
30707                 case 145 /* ObjectKeyword */:
30708                 case 41 /* AsteriskToken */:
30709                 case 57 /* QuestionToken */:
30710                 case 53 /* ExclamationToken */:
30711                 case 25 /* DotDotDotToken */:
30712                 case 135 /* InferKeyword */:
30713                 case 99 /* ImportKeyword */:
30714                 case 127 /* AssertsKeyword */:
30715                 case 14 /* NoSubstitutionTemplateLiteral */:
30716                 case 15 /* TemplateHead */:
30717                     return true;
30718                 case 97 /* FunctionKeyword */:
30719                     return !inStartOfParameter;
30720                 case 40 /* MinusToken */:
30721                     return !inStartOfParameter && lookAhead(nextTokenIsNumericOrBigIntLiteral);
30722                 case 20 /* OpenParenToken */:
30723                     // Only consider '(' the start of a type if followed by ')', '...', an identifier, a modifier,
30724                     // or something that starts a type. We don't want to consider things like '(1)' a type.
30725                     return !inStartOfParameter && lookAhead(isStartOfParenthesizedOrFunctionType);
30726                 default:
30727                     return isIdentifier();
30728             }
30729         }
30730         function isStartOfParenthesizedOrFunctionType() {
30731             nextToken();
30732             return token() === 21 /* CloseParenToken */ || isStartOfParameter(/*isJSDocParameter*/ false) || isStartOfType();
30733         }
30734         function parsePostfixTypeOrHigher() {
30735             var pos = getNodePos();
30736             var type = parseNonArrayType();
30737             while (!scanner.hasPrecedingLineBreak()) {
30738                 switch (token()) {
30739                     case 53 /* ExclamationToken */:
30740                         nextToken();
30741                         type = finishNode(factory.createJSDocNonNullableType(type), pos);
30742                         break;
30743                     case 57 /* QuestionToken */:
30744                         // If next token is start of a type we have a conditional type
30745                         if (lookAhead(nextTokenIsStartOfType)) {
30746                             return type;
30747                         }
30748                         nextToken();
30749                         type = finishNode(factory.createJSDocNullableType(type), pos);
30750                         break;
30751                     case 22 /* OpenBracketToken */:
30752                         parseExpected(22 /* OpenBracketToken */);
30753                         if (isStartOfType()) {
30754                             var indexType = parseType();
30755                             parseExpected(23 /* CloseBracketToken */);
30756                             type = finishNode(factory.createIndexedAccessTypeNode(type, indexType), pos);
30757                         }
30758                         else {
30759                             parseExpected(23 /* CloseBracketToken */);
30760                             type = finishNode(factory.createArrayTypeNode(type), pos);
30761                         }
30762                         break;
30763                     default:
30764                         return type;
30765                 }
30766             }
30767             return type;
30768         }
30769         function parseTypeOperator(operator) {
30770             var pos = getNodePos();
30771             parseExpected(operator);
30772             return finishNode(factory.createTypeOperatorNode(operator, parseTypeOperatorOrHigher()), pos);
30773         }
30774         function parseTypeParameterOfInferType() {
30775             var pos = getNodePos();
30776             return finishNode(factory.createTypeParameterDeclaration(parseIdentifier(), 
30777             /*constraint*/ undefined, 
30778             /*defaultType*/ undefined), pos);
30779         }
30780         function parseInferType() {
30781             var pos = getNodePos();
30782             parseExpected(135 /* InferKeyword */);
30783             return finishNode(factory.createInferTypeNode(parseTypeParameterOfInferType()), pos);
30784         }
30785         function parseTypeOperatorOrHigher() {
30786             var operator = token();
30787             switch (operator) {
30788                 case 138 /* KeyOfKeyword */:
30789                 case 151 /* UniqueKeyword */:
30790                 case 142 /* ReadonlyKeyword */:
30791                     return parseTypeOperator(operator);
30792                 case 135 /* InferKeyword */:
30793                     return parseInferType();
30794             }
30795             return parsePostfixTypeOrHigher();
30796         }
30797         function parseFunctionOrConstructorTypeToError(isInUnionType) {
30798             // the function type and constructor type shorthand notation
30799             // are not allowed directly in unions and intersections, but we'll
30800             // try to parse them gracefully and issue a helpful message.
30801             if (isStartOfFunctionTypeOrConstructorType()) {
30802                 var type = parseFunctionOrConstructorType();
30803                 var diagnostic = void 0;
30804                 if (ts.isFunctionTypeNode(type)) {
30805                     diagnostic = isInUnionType
30806                         ? ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_a_union_type
30807                         : ts.Diagnostics.Function_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
30808                 }
30809                 else {
30810                     diagnostic = isInUnionType
30811                         ? ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_a_union_type
30812                         : ts.Diagnostics.Constructor_type_notation_must_be_parenthesized_when_used_in_an_intersection_type;
30813                 }
30814                 parseErrorAtRange(type, diagnostic);
30815                 return type;
30816             }
30817             return undefined;
30818         }
30819         function parseUnionOrIntersectionType(operator, parseConstituentType, createTypeNode) {
30820             var pos = getNodePos();
30821             var isUnionType = operator === 51 /* BarToken */;
30822             var hasLeadingOperator = parseOptional(operator);
30823             var type = hasLeadingOperator && parseFunctionOrConstructorTypeToError(isUnionType)
30824                 || parseConstituentType();
30825             if (token() === operator || hasLeadingOperator) {
30826                 var types = [type];
30827                 while (parseOptional(operator)) {
30828                     types.push(parseFunctionOrConstructorTypeToError(isUnionType) || parseConstituentType());
30829                 }
30830                 type = finishNode(createTypeNode(createNodeArray(types, pos)), pos);
30831             }
30832             return type;
30833         }
30834         function parseIntersectionTypeOrHigher() {
30835             return parseUnionOrIntersectionType(50 /* AmpersandToken */, parseTypeOperatorOrHigher, factory.createIntersectionTypeNode);
30836         }
30837         function parseUnionTypeOrHigher() {
30838             return parseUnionOrIntersectionType(51 /* BarToken */, parseIntersectionTypeOrHigher, factory.createUnionTypeNode);
30839         }
30840         function isStartOfFunctionTypeOrConstructorType() {
30841             if (token() === 29 /* LessThanToken */) {
30842                 return true;
30843             }
30844             if (token() === 20 /* OpenParenToken */ && lookAhead(isUnambiguouslyStartOfFunctionType)) {
30845                 return true;
30846             }
30847             return token() === 102 /* NewKeyword */;
30848         }
30849         function skipParameterStart() {
30850             if (ts.isModifierKind(token())) {
30851                 // Skip modifiers
30852                 parseModifiers();
30853             }
30854             if (isIdentifier() || token() === 107 /* ThisKeyword */) {
30855                 nextToken();
30856                 return true;
30857             }
30858             if (token() === 22 /* OpenBracketToken */ || token() === 18 /* OpenBraceToken */) {
30859                 // Return true if we can parse an array or object binding pattern with no errors
30860                 var previousErrorCount = parseDiagnostics.length;
30861                 parseIdentifierOrPattern();
30862                 return previousErrorCount === parseDiagnostics.length;
30863             }
30864             return false;
30865         }
30866         function isUnambiguouslyStartOfFunctionType() {
30867             nextToken();
30868             if (token() === 21 /* CloseParenToken */ || token() === 25 /* DotDotDotToken */) {
30869                 // ( )
30870                 // ( ...
30871                 return true;
30872             }
30873             if (skipParameterStart()) {
30874                 // We successfully skipped modifiers (if any) and an identifier or binding pattern,
30875                 // now see if we have something that indicates a parameter declaration
30876                 if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ ||
30877                     token() === 57 /* QuestionToken */ || token() === 62 /* EqualsToken */) {
30878                     // ( xxx :
30879                     // ( xxx ,
30880                     // ( xxx ?
30881                     // ( xxx =
30882                     return true;
30883                 }
30884                 if (token() === 21 /* CloseParenToken */) {
30885                     nextToken();
30886                     if (token() === 38 /* EqualsGreaterThanToken */) {
30887                         // ( xxx ) =>
30888                         return true;
30889                     }
30890                 }
30891             }
30892             return false;
30893         }
30894         function parseTypeOrTypePredicate() {
30895             var pos = getNodePos();
30896             var typePredicateVariable = isIdentifier() && tryParse(parseTypePredicatePrefix);
30897             var type = parseType();
30898             if (typePredicateVariable) {
30899                 return finishNode(factory.createTypePredicateNode(/*assertsModifier*/ undefined, typePredicateVariable, type), pos);
30900             }
30901             else {
30902                 return type;
30903             }
30904         }
30905         function parseTypePredicatePrefix() {
30906             var id = parseIdentifier();
30907             if (token() === 137 /* IsKeyword */ && !scanner.hasPrecedingLineBreak()) {
30908                 nextToken();
30909                 return id;
30910             }
30911         }
30912         function parseAssertsTypePredicate() {
30913             var pos = getNodePos();
30914             var assertsModifier = parseExpectedToken(127 /* AssertsKeyword */);
30915             var parameterName = token() === 107 /* ThisKeyword */ ? parseThisTypeNode() : parseIdentifier();
30916             var type = parseOptional(137 /* IsKeyword */) ? parseType() : undefined;
30917             return finishNode(factory.createTypePredicateNode(assertsModifier, parameterName, type), pos);
30918         }
30919         function parseType() {
30920             // The rules about 'yield' only apply to actual code/expression contexts.  They don't
30921             // apply to 'type' contexts.  So we disable these parameters here before moving on.
30922             return doOutsideOfContext(40960 /* TypeExcludesFlags */, parseTypeWorker);
30923         }
30924         function parseTypeWorker(noConditionalTypes) {
30925             if (isStartOfFunctionTypeOrConstructorType()) {
30926                 return parseFunctionOrConstructorType();
30927             }
30928             var pos = getNodePos();
30929             var type = parseUnionTypeOrHigher();
30930             if (!noConditionalTypes && !scanner.hasPrecedingLineBreak() && parseOptional(93 /* ExtendsKeyword */)) {
30931                 // The type following 'extends' is not permitted to be another conditional type
30932                 var extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
30933                 parseExpected(57 /* QuestionToken */);
30934                 var trueType = parseTypeWorker();
30935                 parseExpected(58 /* ColonToken */);
30936                 var falseType = parseTypeWorker();
30937                 return finishNode(factory.createConditionalTypeNode(type, extendsType, trueType, falseType), pos);
30938             }
30939             return type;
30940         }
30941         function parseTypeAnnotation() {
30942             return parseOptional(58 /* ColonToken */) ? parseType() : undefined;
30943         }
30944         // EXPRESSIONS
30945         function isStartOfLeftHandSideExpression() {
30946             switch (token()) {
30947                 case 107 /* ThisKeyword */:
30948                 case 105 /* SuperKeyword */:
30949                 case 103 /* NullKeyword */:
30950                 case 109 /* TrueKeyword */:
30951                 case 94 /* FalseKeyword */:
30952                 case 8 /* NumericLiteral */:
30953                 case 9 /* BigIntLiteral */:
30954                 case 10 /* StringLiteral */:
30955                 case 14 /* NoSubstitutionTemplateLiteral */:
30956                 case 15 /* TemplateHead */:
30957                 case 20 /* OpenParenToken */:
30958                 case 22 /* OpenBracketToken */:
30959                 case 18 /* OpenBraceToken */:
30960                 case 97 /* FunctionKeyword */:
30961                 case 83 /* ClassKeyword */:
30962                 case 102 /* NewKeyword */:
30963                 case 43 /* SlashToken */:
30964                 case 67 /* SlashEqualsToken */:
30965                 case 78 /* Identifier */:
30966                     return true;
30967                 case 99 /* ImportKeyword */:
30968                     return lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
30969                 default:
30970                     return isIdentifier();
30971             }
30972         }
30973         function isStartOfExpression() {
30974             if (isStartOfLeftHandSideExpression()) {
30975                 return true;
30976             }
30977             switch (token()) {
30978                 case 39 /* PlusToken */:
30979                 case 40 /* MinusToken */:
30980                 case 54 /* TildeToken */:
30981                 case 53 /* ExclamationToken */:
30982                 case 88 /* DeleteKeyword */:
30983                 case 111 /* TypeOfKeyword */:
30984                 case 113 /* VoidKeyword */:
30985                 case 45 /* PlusPlusToken */:
30986                 case 46 /* MinusMinusToken */:
30987                 case 29 /* LessThanToken */:
30988                 case 130 /* AwaitKeyword */:
30989                 case 124 /* YieldKeyword */:
30990                 case 79 /* PrivateIdentifier */:
30991                     // Yield/await always starts an expression.  Either it is an identifier (in which case
30992                     // it is definitely an expression).  Or it's a keyword (either because we're in
30993                     // a generator or async function, or in strict mode (or both)) and it started a yield or await expression.
30994                     return true;
30995                 default:
30996                     // Error tolerance.  If we see the start of some binary operator, we consider
30997                     // that the start of an expression.  That way we'll parse out a missing identifier,
30998                     // give a good message about an identifier being missing, and then consume the
30999                     // rest of the binary expression.
31000                     if (isBinaryOperator()) {
31001                         return true;
31002                     }
31003                     return isIdentifier();
31004             }
31005         }
31006         function isStartOfExpressionStatement() {
31007             // As per the grammar, none of '{' or 'function' or 'class' can start an expression statement.
31008             return token() !== 18 /* OpenBraceToken */ &&
31009                 token() !== 97 /* FunctionKeyword */ &&
31010                 token() !== 83 /* ClassKeyword */ &&
31011                 token() !== 59 /* AtToken */ &&
31012                 isStartOfExpression();
31013         }
31014         function parseExpression() {
31015             // Expression[in]:
31016             //      AssignmentExpression[in]
31017             //      Expression[in] , AssignmentExpression[in]
31018             // clear the decorator context when parsing Expression, as it should be unambiguous when parsing a decorator
31019             var saveDecoratorContext = inDecoratorContext();
31020             if (saveDecoratorContext) {
31021                 setDecoratorContext(/*val*/ false);
31022             }
31023             var pos = getNodePos();
31024             var expr = parseAssignmentExpressionOrHigher();
31025             var operatorToken;
31026             while ((operatorToken = parseOptionalToken(27 /* CommaToken */))) {
31027                 expr = makeBinaryExpression(expr, operatorToken, parseAssignmentExpressionOrHigher(), pos);
31028             }
31029             if (saveDecoratorContext) {
31030                 setDecoratorContext(/*val*/ true);
31031             }
31032             return expr;
31033         }
31034         function parseInitializer() {
31035             return parseOptional(62 /* EqualsToken */) ? parseAssignmentExpressionOrHigher() : undefined;
31036         }
31037         function parseAssignmentExpressionOrHigher() {
31038             //  AssignmentExpression[in,yield]:
31039             //      1) ConditionalExpression[?in,?yield]
31040             //      2) LeftHandSideExpression = AssignmentExpression[?in,?yield]
31041             //      3) LeftHandSideExpression AssignmentOperator AssignmentExpression[?in,?yield]
31042             //      4) ArrowFunctionExpression[?in,?yield]
31043             //      5) AsyncArrowFunctionExpression[in,yield,await]
31044             //      6) [+Yield] YieldExpression[?In]
31045             //
31046             // Note: for ease of implementation we treat productions '2' and '3' as the same thing.
31047             // (i.e. they're both BinaryExpressions with an assignment operator in it).
31048             // First, do the simple check if we have a YieldExpression (production '6').
31049             if (isYieldExpression()) {
31050                 return parseYieldExpression();
31051             }
31052             // Then, check if we have an arrow function (production '4' and '5') that starts with a parenthesized
31053             // parameter list or is an async arrow function.
31054             // AsyncArrowFunctionExpression:
31055             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
31056             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
31057             // Production (1) of AsyncArrowFunctionExpression is parsed in "tryParseAsyncSimpleArrowFunctionExpression".
31058             // And production (2) is parsed in "tryParseParenthesizedArrowFunctionExpression".
31059             //
31060             // If we do successfully parse arrow-function, we must *not* recurse for productions 1, 2 or 3. An ArrowFunction is
31061             // not a LeftHandSideExpression, nor does it start a ConditionalExpression.  So we are done
31062             // with AssignmentExpression if we see one.
31063             var arrowExpression = tryParseParenthesizedArrowFunctionExpression() || tryParseAsyncSimpleArrowFunctionExpression();
31064             if (arrowExpression) {
31065                 return arrowExpression;
31066             }
31067             // Now try to see if we're in production '1', '2' or '3'.  A conditional expression can
31068             // start with a LogicalOrExpression, while the assignment productions can only start with
31069             // LeftHandSideExpressions.
31070             //
31071             // So, first, we try to just parse out a BinaryExpression.  If we get something that is a
31072             // LeftHandSide or higher, then we can try to parse out the assignment expression part.
31073             // Otherwise, we try to parse out the conditional expression bit.  We want to allow any
31074             // binary expression here, so we pass in the 'lowest' precedence here so that it matches
31075             // and consumes anything.
31076             var pos = getNodePos();
31077             var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
31078             // To avoid a look-ahead, we did not handle the case of an arrow function with a single un-parenthesized
31079             // parameter ('x => ...') above. We handle it here by checking if the parsed expression was a single
31080             // identifier and the current token is an arrow.
31081             if (expr.kind === 78 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
31082                 return parseSimpleArrowFunctionExpression(pos, expr, /*asyncModifier*/ undefined);
31083             }
31084             // Now see if we might be in cases '2' or '3'.
31085             // If the expression was a LHS expression, and we have an assignment operator, then
31086             // we're in '2' or '3'. Consume the assignment and return.
31087             //
31088             // Note: we call reScanGreaterToken so that we get an appropriately merged token
31089             // for cases like `> > =` becoming `>>=`
31090             if (ts.isLeftHandSideExpression(expr) && ts.isAssignmentOperator(reScanGreaterToken())) {
31091                 return makeBinaryExpression(expr, parseTokenNode(), parseAssignmentExpressionOrHigher(), pos);
31092             }
31093             // It wasn't an assignment or a lambda.  This is a conditional expression:
31094             return parseConditionalExpressionRest(expr, pos);
31095         }
31096         function isYieldExpression() {
31097             if (token() === 124 /* YieldKeyword */) {
31098                 // If we have a 'yield' keyword, and this is a context where yield expressions are
31099                 // allowed, then definitely parse out a yield expression.
31100                 if (inYieldContext()) {
31101                     return true;
31102                 }
31103                 // We're in a context where 'yield expr' is not allowed.  However, if we can
31104                 // definitely tell that the user was trying to parse a 'yield expr' and not
31105                 // just a normal expr that start with a 'yield' identifier, then parse out
31106                 // a 'yield expr'.  We can then report an error later that they are only
31107                 // allowed in generator expressions.
31108                 //
31109                 // for example, if we see 'yield(foo)', then we'll have to treat that as an
31110                 // invocation expression of something called 'yield'.  However, if we have
31111                 // 'yield foo' then that is not legal as a normal expression, so we can
31112                 // definitely recognize this as a yield expression.
31113                 //
31114                 // for now we just check if the next token is an identifier.  More heuristics
31115                 // can be added here later as necessary.  We just need to make sure that we
31116                 // don't accidentally consume something legal.
31117                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
31118             }
31119             return false;
31120         }
31121         function nextTokenIsIdentifierOnSameLine() {
31122             nextToken();
31123             return !scanner.hasPrecedingLineBreak() && isIdentifier();
31124         }
31125         function parseYieldExpression() {
31126             var pos = getNodePos();
31127             // YieldExpression[In] :
31128             //      yield
31129             //      yield [no LineTerminator here] [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
31130             //      yield [no LineTerminator here] * [Lexical goal InputElementRegExp]AssignmentExpression[?In, Yield]
31131             nextToken();
31132             if (!scanner.hasPrecedingLineBreak() &&
31133                 (token() === 41 /* AsteriskToken */ || isStartOfExpression())) {
31134                 return finishNode(factory.createYieldExpression(parseOptionalToken(41 /* AsteriskToken */), parseAssignmentExpressionOrHigher()), pos);
31135             }
31136             else {
31137                 // if the next token is not on the same line as yield.  or we don't have an '*' or
31138                 // the start of an expression, then this is just a simple "yield" expression.
31139                 return finishNode(factory.createYieldExpression(/*asteriskToken*/ undefined, /*expression*/ undefined), pos);
31140             }
31141         }
31142         function parseSimpleArrowFunctionExpression(pos, identifier, asyncModifier) {
31143             ts.Debug.assert(token() === 38 /* EqualsGreaterThanToken */, "parseSimpleArrowFunctionExpression should only have been called if we had a =>");
31144             var parameter = factory.createParameterDeclaration(
31145             /*decorators*/ undefined, 
31146             /*modifiers*/ undefined, 
31147             /*dotDotDotToken*/ undefined, identifier, 
31148             /*questionToken*/ undefined, 
31149             /*type*/ undefined, 
31150             /*initializer*/ undefined);
31151             finishNode(parameter, identifier.pos);
31152             var parameters = createNodeArray([parameter], parameter.pos, parameter.end);
31153             var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
31154             var body = parseArrowFunctionExpressionBody(/*isAsync*/ !!asyncModifier);
31155             var node = factory.createArrowFunction(asyncModifier, /*typeParameters*/ undefined, parameters, /*type*/ undefined, equalsGreaterThanToken, body);
31156             return addJSDocComment(finishNode(node, pos));
31157         }
31158         function tryParseParenthesizedArrowFunctionExpression() {
31159             var triState = isParenthesizedArrowFunctionExpression();
31160             if (triState === 0 /* False */) {
31161                 // It's definitely not a parenthesized arrow function expression.
31162                 return undefined;
31163             }
31164             // If we definitely have an arrow function, then we can just parse one, not requiring a
31165             // following => or { token. Otherwise, we *might* have an arrow function.  Try to parse
31166             // it out, but don't allow any ambiguity, and return 'undefined' if this could be an
31167             // expression instead.
31168             return triState === 1 /* True */ ?
31169                 parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ true) :
31170                 tryParse(parsePossibleParenthesizedArrowFunctionExpression);
31171         }
31172         //  True        -> We definitely expect a parenthesized arrow function here.
31173         //  False       -> There *cannot* be a parenthesized arrow function here.
31174         //  Unknown     -> There *might* be a parenthesized arrow function here.
31175         //                 Speculatively look ahead to be sure, and rollback if not.
31176         function isParenthesizedArrowFunctionExpression() {
31177             if (token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */ || token() === 129 /* AsyncKeyword */) {
31178                 return lookAhead(isParenthesizedArrowFunctionExpressionWorker);
31179             }
31180             if (token() === 38 /* EqualsGreaterThanToken */) {
31181                 // ERROR RECOVERY TWEAK:
31182                 // If we see a standalone => try to parse it as an arrow function expression as that's
31183                 // likely what the user intended to write.
31184                 return 1 /* True */;
31185             }
31186             // Definitely not a parenthesized arrow function.
31187             return 0 /* False */;
31188         }
31189         function isParenthesizedArrowFunctionExpressionWorker() {
31190             if (token() === 129 /* AsyncKeyword */) {
31191                 nextToken();
31192                 if (scanner.hasPrecedingLineBreak()) {
31193                     return 0 /* False */;
31194                 }
31195                 if (token() !== 20 /* OpenParenToken */ && token() !== 29 /* LessThanToken */) {
31196                     return 0 /* False */;
31197                 }
31198             }
31199             var first = token();
31200             var second = nextToken();
31201             if (first === 20 /* OpenParenToken */) {
31202                 if (second === 21 /* CloseParenToken */) {
31203                     // Simple cases: "() =>", "(): ", and "() {".
31204                     // This is an arrow function with no parameters.
31205                     // The last one is not actually an arrow function,
31206                     // but this is probably what the user intended.
31207                     var third = nextToken();
31208                     switch (third) {
31209                         case 38 /* EqualsGreaterThanToken */:
31210                         case 58 /* ColonToken */:
31211                         case 18 /* OpenBraceToken */:
31212                             return 1 /* True */;
31213                         default:
31214                             return 0 /* False */;
31215                     }
31216                 }
31217                 // If encounter "([" or "({", this could be the start of a binding pattern.
31218                 // Examples:
31219                 //      ([ x ]) => { }
31220                 //      ({ x }) => { }
31221                 //      ([ x ])
31222                 //      ({ x })
31223                 if (second === 22 /* OpenBracketToken */ || second === 18 /* OpenBraceToken */) {
31224                     return 2 /* Unknown */;
31225                 }
31226                 // Simple case: "(..."
31227                 // This is an arrow function with a rest parameter.
31228                 if (second === 25 /* DotDotDotToken */) {
31229                     return 1 /* True */;
31230                 }
31231                 // Check for "(xxx yyy", where xxx is a modifier and yyy is an identifier. This
31232                 // isn't actually allowed, but we want to treat it as a lambda so we can provide
31233                 // a good error message.
31234                 if (ts.isModifierKind(second) && second !== 129 /* AsyncKeyword */ && lookAhead(nextTokenIsIdentifier)) {
31235                     return 1 /* True */;
31236                 }
31237                 // If we had "(" followed by something that's not an identifier,
31238                 // then this definitely doesn't look like a lambda.  "this" is not
31239                 // valid, but we want to parse it and then give a semantic error.
31240                 if (!isIdentifier() && second !== 107 /* ThisKeyword */) {
31241                     return 0 /* False */;
31242                 }
31243                 switch (nextToken()) {
31244                     case 58 /* ColonToken */:
31245                         // If we have something like "(a:", then we must have a
31246                         // type-annotated parameter in an arrow function expression.
31247                         return 1 /* True */;
31248                     case 57 /* QuestionToken */:
31249                         nextToken();
31250                         // If we have "(a?:" or "(a?," or "(a?=" or "(a?)" then it is definitely a lambda.
31251                         if (token() === 58 /* ColonToken */ || token() === 27 /* CommaToken */ || token() === 62 /* EqualsToken */ || token() === 21 /* CloseParenToken */) {
31252                             return 1 /* True */;
31253                         }
31254                         // Otherwise it is definitely not a lambda.
31255                         return 0 /* False */;
31256                     case 27 /* CommaToken */:
31257                     case 62 /* EqualsToken */:
31258                     case 21 /* CloseParenToken */:
31259                         // If we have "(a," or "(a=" or "(a)" this *could* be an arrow function
31260                         return 2 /* Unknown */;
31261                 }
31262                 // It is definitely not an arrow function
31263                 return 0 /* False */;
31264             }
31265             else {
31266                 ts.Debug.assert(first === 29 /* LessThanToken */);
31267                 // If we have "<" not followed by an identifier,
31268                 // then this definitely is not an arrow function.
31269                 if (!isIdentifier()) {
31270                     return 0 /* False */;
31271                 }
31272                 // JSX overrides
31273                 if (languageVariant === 1 /* JSX */) {
31274                     var isArrowFunctionInJsx = lookAhead(function () {
31275                         var third = nextToken();
31276                         if (third === 93 /* ExtendsKeyword */) {
31277                             var fourth = nextToken();
31278                             switch (fourth) {
31279                                 case 62 /* EqualsToken */:
31280                                 case 31 /* GreaterThanToken */:
31281                                     return false;
31282                                 default:
31283                                     return true;
31284                             }
31285                         }
31286                         else if (third === 27 /* CommaToken */) {
31287                             return true;
31288                         }
31289                         return false;
31290                     });
31291                     if (isArrowFunctionInJsx) {
31292                         return 1 /* True */;
31293                     }
31294                     return 0 /* False */;
31295                 }
31296                 // This *could* be a parenthesized arrow function.
31297                 return 2 /* Unknown */;
31298             }
31299         }
31300         function parsePossibleParenthesizedArrowFunctionExpression() {
31301             var tokenPos = scanner.getTokenPos();
31302             if (notParenthesizedArrow === null || notParenthesizedArrow === void 0 ? void 0 : notParenthesizedArrow.has(tokenPos)) {
31303                 return undefined;
31304             }
31305             var result = parseParenthesizedArrowFunctionExpression(/*allowAmbiguity*/ false);
31306             if (!result) {
31307                 (notParenthesizedArrow || (notParenthesizedArrow = new ts.Set())).add(tokenPos);
31308             }
31309             return result;
31310         }
31311         function tryParseAsyncSimpleArrowFunctionExpression() {
31312             // We do a check here so that we won't be doing unnecessarily call to "lookAhead"
31313             if (token() === 129 /* AsyncKeyword */) {
31314                 if (lookAhead(isUnParenthesizedAsyncArrowFunctionWorker) === 1 /* True */) {
31315                     var pos = getNodePos();
31316                     var asyncModifier = parseModifiersForArrowFunction();
31317                     var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
31318                     return parseSimpleArrowFunctionExpression(pos, expr, asyncModifier);
31319                 }
31320             }
31321             return undefined;
31322         }
31323         function isUnParenthesizedAsyncArrowFunctionWorker() {
31324             // AsyncArrowFunctionExpression:
31325             //      1) async[no LineTerminator here]AsyncArrowBindingIdentifier[?Yield][no LineTerminator here]=>AsyncConciseBody[?In]
31326             //      2) CoverCallExpressionAndAsyncArrowHead[?Yield, ?Await][no LineTerminator here]=>AsyncConciseBody[?In]
31327             if (token() === 129 /* AsyncKeyword */) {
31328                 nextToken();
31329                 // If the "async" is followed by "=>" token then it is not a beginning of an async arrow-function
31330                 // but instead a simple arrow-function which will be parsed inside "parseAssignmentExpressionOrHigher"
31331                 if (scanner.hasPrecedingLineBreak() || token() === 38 /* EqualsGreaterThanToken */) {
31332                     return 0 /* False */;
31333                 }
31334                 // Check for un-parenthesized AsyncArrowFunction
31335                 var expr = parseBinaryExpressionOrHigher(0 /* Lowest */);
31336                 if (!scanner.hasPrecedingLineBreak() && expr.kind === 78 /* Identifier */ && token() === 38 /* EqualsGreaterThanToken */) {
31337                     return 1 /* True */;
31338                 }
31339             }
31340             return 0 /* False */;
31341         }
31342         function parseParenthesizedArrowFunctionExpression(allowAmbiguity) {
31343             var pos = getNodePos();
31344             var hasJSDoc = hasPrecedingJSDocComment();
31345             var modifiers = parseModifiersForArrowFunction();
31346             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
31347             // Arrow functions are never generators.
31348             //
31349             // If we're speculatively parsing a signature for a parenthesized arrow function, then
31350             // we have to have a complete parameter list.  Otherwise we might see something like
31351             // a => (b => c)
31352             // And think that "(b =>" was actually a parenthesized arrow function with a missing
31353             // close paren.
31354             var typeParameters = parseTypeParameters();
31355             var parameters;
31356             if (!parseExpected(20 /* OpenParenToken */)) {
31357                 if (!allowAmbiguity) {
31358                     return undefined;
31359                 }
31360                 parameters = createMissingList();
31361             }
31362             else {
31363                 parameters = parseParametersWorker(isAsync);
31364                 if (!parseExpected(21 /* CloseParenToken */) && !allowAmbiguity) {
31365                     return undefined;
31366                 }
31367             }
31368             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
31369             if (type && !allowAmbiguity && typeHasArrowFunctionBlockingParseError(type)) {
31370                 return undefined;
31371             }
31372             // Parsing a signature isn't enough.
31373             // Parenthesized arrow signatures often look like other valid expressions.
31374             // For instance:
31375             //  - "(x = 10)" is an assignment expression parsed as a signature with a default parameter value.
31376             //  - "(x,y)" is a comma expression parsed as a signature with two parameters.
31377             //  - "a ? (b): c" will have "(b):" parsed as a signature with a return type annotation.
31378             //  - "a ? (b): function() {}" will too, since function() is a valid JSDoc function type.
31379             //
31380             // So we need just a bit of lookahead to ensure that it can only be a signature.
31381             var hasJSDocFunctionType = type && ts.isJSDocFunctionType(type);
31382             if (!allowAmbiguity && token() !== 38 /* EqualsGreaterThanToken */ && (hasJSDocFunctionType || token() !== 18 /* OpenBraceToken */)) {
31383                 // Returning undefined here will cause our caller to rewind to where we started from.
31384                 return undefined;
31385             }
31386             // If we have an arrow, then try to parse the body. Even if not, try to parse if we
31387             // have an opening brace, just in case we're in an error state.
31388             var lastToken = token();
31389             var equalsGreaterThanToken = parseExpectedToken(38 /* EqualsGreaterThanToken */);
31390             var body = (lastToken === 38 /* EqualsGreaterThanToken */ || lastToken === 18 /* OpenBraceToken */)
31391                 ? parseArrowFunctionExpressionBody(ts.some(modifiers, ts.isAsyncModifier))
31392                 : parseIdentifier();
31393             var node = factory.createArrowFunction(modifiers, typeParameters, parameters, type, equalsGreaterThanToken, body);
31394             return withJSDoc(finishNode(node, pos), hasJSDoc);
31395         }
31396         function parseArrowFunctionExpressionBody(isAsync) {
31397             if (token() === 18 /* OpenBraceToken */) {
31398                 return parseFunctionBlock(isAsync ? 2 /* Await */ : 0 /* None */);
31399             }
31400             if (token() !== 26 /* SemicolonToken */ &&
31401                 token() !== 97 /* FunctionKeyword */ &&
31402                 token() !== 83 /* ClassKeyword */ &&
31403                 isStartOfStatement() &&
31404                 !isStartOfExpressionStatement()) {
31405                 // Check if we got a plain statement (i.e. no expression-statements, no function/class expressions/declarations)
31406                 //
31407                 // Here we try to recover from a potential error situation in the case where the
31408                 // user meant to supply a block. For example, if the user wrote:
31409                 //
31410                 //  a =>
31411                 //      let v = 0;
31412                 //  }
31413                 //
31414                 // they may be missing an open brace.  Check to see if that's the case so we can
31415                 // try to recover better.  If we don't do this, then the next close curly we see may end
31416                 // up preemptively closing the containing construct.
31417                 //
31418                 // Note: even when 'IgnoreMissingOpenBrace' is passed, parseBody will still error.
31419                 return parseFunctionBlock(16 /* IgnoreMissingOpenBrace */ | (isAsync ? 2 /* Await */ : 0 /* None */));
31420             }
31421             var savedTopLevel = topLevel;
31422             topLevel = false;
31423             var node = isAsync
31424                 ? doInAwaitContext(parseAssignmentExpressionOrHigher)
31425                 : doOutsideOfAwaitContext(parseAssignmentExpressionOrHigher);
31426             topLevel = savedTopLevel;
31427             return node;
31428         }
31429         function parseConditionalExpressionRest(leftOperand, pos) {
31430             // Note: we are passed in an expression which was produced from parseBinaryExpressionOrHigher.
31431             var questionToken = parseOptionalToken(57 /* QuestionToken */);
31432             if (!questionToken) {
31433                 return leftOperand;
31434             }
31435             // Note: we explicitly 'allowIn' in the whenTrue part of the condition expression, and
31436             // we do not that for the 'whenFalse' part.
31437             var colonToken;
31438             return finishNode(factory.createConditionalExpression(leftOperand, questionToken, doOutsideOfContext(disallowInAndDecoratorContext, parseAssignmentExpressionOrHigher), colonToken = parseExpectedToken(58 /* ColonToken */), ts.nodeIsPresent(colonToken)
31439                 ? parseAssignmentExpressionOrHigher()
31440                 : createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics._0_expected, ts.tokenToString(58 /* ColonToken */))), pos);
31441         }
31442         function parseBinaryExpressionOrHigher(precedence) {
31443             var pos = getNodePos();
31444             var leftOperand = parseUnaryExpressionOrHigher();
31445             return parseBinaryExpressionRest(precedence, leftOperand, pos);
31446         }
31447         function isInOrOfKeyword(t) {
31448             return t === 100 /* InKeyword */ || t === 156 /* OfKeyword */;
31449         }
31450         function parseBinaryExpressionRest(precedence, leftOperand, pos) {
31451             while (true) {
31452                 // We either have a binary operator here, or we're finished.  We call
31453                 // reScanGreaterToken so that we merge token sequences like > and = into >=
31454                 reScanGreaterToken();
31455                 var newPrecedence = ts.getBinaryOperatorPrecedence(token());
31456                 // Check the precedence to see if we should "take" this operator
31457                 // - For left associative operator (all operator but **), consume the operator,
31458                 //   recursively call the function below, and parse binaryExpression as a rightOperand
31459                 //   of the caller if the new precedence of the operator is greater then or equal to the current precedence.
31460                 //   For example:
31461                 //      a - b - c;
31462                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
31463                 //      a * b - c
31464                 //            ^token; leftOperand = b. Return b to the caller as a rightOperand
31465                 //      a - b * c;
31466                 //            ^token; leftOperand = b. Return b * c to the caller as a rightOperand
31467                 // - For right associative operator (**), consume the operator, recursively call the function
31468                 //   and parse binaryExpression as a rightOperand of the caller if the new precedence of
31469                 //   the operator is strictly grater than the current precedence
31470                 //   For example:
31471                 //      a ** b ** c;
31472                 //             ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
31473                 //      a - b ** c;
31474                 //            ^^token; leftOperand = b. Return b ** c to the caller as a rightOperand
31475                 //      a ** b - c
31476                 //             ^token; leftOperand = b. Return b to the caller as a rightOperand
31477                 var consumeCurrentOperator = token() === 42 /* AsteriskAsteriskToken */ ?
31478                     newPrecedence >= precedence :
31479                     newPrecedence > precedence;
31480                 if (!consumeCurrentOperator) {
31481                     break;
31482                 }
31483                 if (token() === 100 /* InKeyword */ && inDisallowInContext()) {
31484                     break;
31485                 }
31486                 if (token() === 126 /* AsKeyword */) {
31487                     // Make sure we *do* perform ASI for constructs like this:
31488                     //    var x = foo
31489                     //    as (Bar)
31490                     // This should be parsed as an initialized variable, followed
31491                     // by a function call to 'as' with the argument 'Bar'
31492                     if (scanner.hasPrecedingLineBreak()) {
31493                         break;
31494                     }
31495                     else {
31496                         nextToken();
31497                         leftOperand = makeAsExpression(leftOperand, parseType());
31498                     }
31499                 }
31500                 else {
31501                     leftOperand = makeBinaryExpression(leftOperand, parseTokenNode(), parseBinaryExpressionOrHigher(newPrecedence), pos);
31502                 }
31503             }
31504             return leftOperand;
31505         }
31506         function isBinaryOperator() {
31507             if (inDisallowInContext() && token() === 100 /* InKeyword */) {
31508                 return false;
31509             }
31510             return ts.getBinaryOperatorPrecedence(token()) > 0;
31511         }
31512         function makeBinaryExpression(left, operatorToken, right, pos) {
31513             return finishNode(factory.createBinaryExpression(left, operatorToken, right), pos);
31514         }
31515         function makeAsExpression(left, right) {
31516             return finishNode(factory.createAsExpression(left, right), left.pos);
31517         }
31518         function parsePrefixUnaryExpression() {
31519             var pos = getNodePos();
31520             return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseSimpleUnaryExpression)), pos);
31521         }
31522         function parseDeleteExpression() {
31523             var pos = getNodePos();
31524             return finishNode(factory.createDeleteExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31525         }
31526         function parseTypeOfExpression() {
31527             var pos = getNodePos();
31528             return finishNode(factory.createTypeOfExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31529         }
31530         function parseVoidExpression() {
31531             var pos = getNodePos();
31532             return finishNode(factory.createVoidExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31533         }
31534         function isAwaitExpression() {
31535             if (token() === 130 /* AwaitKeyword */) {
31536                 if (inAwaitContext()) {
31537                     return true;
31538                 }
31539                 // here we are using similar heuristics as 'isYieldExpression'
31540                 return lookAhead(nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine);
31541             }
31542             return false;
31543         }
31544         function parseAwaitExpression() {
31545             var pos = getNodePos();
31546             return finishNode(factory.createAwaitExpression(nextTokenAnd(parseSimpleUnaryExpression)), pos);
31547         }
31548         /**
31549          * Parse ES7 exponential expression and await expression
31550          *
31551          * ES7 ExponentiationExpression:
31552          *      1) UnaryExpression[?Yield]
31553          *      2) UpdateExpression[?Yield] ** ExponentiationExpression[?Yield]
31554          *
31555          */
31556         function parseUnaryExpressionOrHigher() {
31557             /**
31558              * ES7 UpdateExpression:
31559              *      1) LeftHandSideExpression[?Yield]
31560              *      2) LeftHandSideExpression[?Yield][no LineTerminator here]++
31561              *      3) LeftHandSideExpression[?Yield][no LineTerminator here]--
31562              *      4) ++UnaryExpression[?Yield]
31563              *      5) --UnaryExpression[?Yield]
31564              */
31565             if (isUpdateExpression()) {
31566                 var pos = getNodePos();
31567                 var updateExpression = parseUpdateExpression();
31568                 return token() === 42 /* AsteriskAsteriskToken */ ?
31569                     parseBinaryExpressionRest(ts.getBinaryOperatorPrecedence(token()), updateExpression, pos) :
31570                     updateExpression;
31571             }
31572             /**
31573              * ES7 UnaryExpression:
31574              *      1) UpdateExpression[?yield]
31575              *      2) delete UpdateExpression[?yield]
31576              *      3) void UpdateExpression[?yield]
31577              *      4) typeof UpdateExpression[?yield]
31578              *      5) + UpdateExpression[?yield]
31579              *      6) - UpdateExpression[?yield]
31580              *      7) ~ UpdateExpression[?yield]
31581              *      8) ! UpdateExpression[?yield]
31582              */
31583             var unaryOperator = token();
31584             var simpleUnaryExpression = parseSimpleUnaryExpression();
31585             if (token() === 42 /* AsteriskAsteriskToken */) {
31586                 var pos = ts.skipTrivia(sourceText, simpleUnaryExpression.pos);
31587                 var end = simpleUnaryExpression.end;
31588                 if (simpleUnaryExpression.kind === 206 /* TypeAssertionExpression */) {
31589                     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);
31590                 }
31591                 else {
31592                     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));
31593                 }
31594             }
31595             return simpleUnaryExpression;
31596         }
31597         /**
31598          * Parse ES7 simple-unary expression or higher:
31599          *
31600          * ES7 UnaryExpression:
31601          *      1) UpdateExpression[?yield]
31602          *      2) delete UnaryExpression[?yield]
31603          *      3) void UnaryExpression[?yield]
31604          *      4) typeof UnaryExpression[?yield]
31605          *      5) + UnaryExpression[?yield]
31606          *      6) - UnaryExpression[?yield]
31607          *      7) ~ UnaryExpression[?yield]
31608          *      8) ! UnaryExpression[?yield]
31609          *      9) [+Await] await UnaryExpression[?yield]
31610          */
31611         function parseSimpleUnaryExpression() {
31612             switch (token()) {
31613                 case 39 /* PlusToken */:
31614                 case 40 /* MinusToken */:
31615                 case 54 /* TildeToken */:
31616                 case 53 /* ExclamationToken */:
31617                     return parsePrefixUnaryExpression();
31618                 case 88 /* DeleteKeyword */:
31619                     return parseDeleteExpression();
31620                 case 111 /* TypeOfKeyword */:
31621                     return parseTypeOfExpression();
31622                 case 113 /* VoidKeyword */:
31623                     return parseVoidExpression();
31624                 case 29 /* LessThanToken */:
31625                     // This is modified UnaryExpression grammar in TypeScript
31626                     //  UnaryExpression (modified):
31627                     //      < type > UnaryExpression
31628                     return parseTypeAssertion();
31629                 case 130 /* AwaitKeyword */:
31630                     if (isAwaitExpression()) {
31631                         return parseAwaitExpression();
31632                     }
31633                 // falls through
31634                 default:
31635                     return parseUpdateExpression();
31636             }
31637         }
31638         /**
31639          * Check if the current token can possibly be an ES7 increment expression.
31640          *
31641          * ES7 UpdateExpression:
31642          *      LeftHandSideExpression[?Yield]
31643          *      LeftHandSideExpression[?Yield][no LineTerminator here]++
31644          *      LeftHandSideExpression[?Yield][no LineTerminator here]--
31645          *      ++LeftHandSideExpression[?Yield]
31646          *      --LeftHandSideExpression[?Yield]
31647          */
31648         function isUpdateExpression() {
31649             // This function is called inside parseUnaryExpression to decide
31650             // whether to call parseSimpleUnaryExpression or call parseUpdateExpression directly
31651             switch (token()) {
31652                 case 39 /* PlusToken */:
31653                 case 40 /* MinusToken */:
31654                 case 54 /* TildeToken */:
31655                 case 53 /* ExclamationToken */:
31656                 case 88 /* DeleteKeyword */:
31657                 case 111 /* TypeOfKeyword */:
31658                 case 113 /* VoidKeyword */:
31659                 case 130 /* AwaitKeyword */:
31660                     return false;
31661                 case 29 /* LessThanToken */:
31662                     // If we are not in JSX context, we are parsing TypeAssertion which is an UnaryExpression
31663                     if (languageVariant !== 1 /* JSX */) {
31664                         return false;
31665                     }
31666                 // We are in JSX context and the token is part of JSXElement.
31667                 // falls through
31668                 default:
31669                     return true;
31670             }
31671         }
31672         /**
31673          * Parse ES7 UpdateExpression. UpdateExpression is used instead of ES6's PostFixExpression.
31674          *
31675          * ES7 UpdateExpression[yield]:
31676          *      1) LeftHandSideExpression[?yield]
31677          *      2) LeftHandSideExpression[?yield] [[no LineTerminator here]]++
31678          *      3) LeftHandSideExpression[?yield] [[no LineTerminator here]]--
31679          *      4) ++LeftHandSideExpression[?yield]
31680          *      5) --LeftHandSideExpression[?yield]
31681          * In TypeScript (2), (3) are parsed as PostfixUnaryExpression. (4), (5) are parsed as PrefixUnaryExpression
31682          */
31683         function parseUpdateExpression() {
31684             if (token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) {
31685                 var pos = getNodePos();
31686                 return finishNode(factory.createPrefixUnaryExpression(token(), nextTokenAnd(parseLeftHandSideExpressionOrHigher)), pos);
31687             }
31688             else if (languageVariant === 1 /* JSX */ && token() === 29 /* LessThanToken */ && lookAhead(nextTokenIsIdentifierOrKeywordOrGreaterThan)) {
31689                 // JSXElement is part of primaryExpression
31690                 return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true);
31691             }
31692             var expression = parseLeftHandSideExpressionOrHigher();
31693             ts.Debug.assert(ts.isLeftHandSideExpression(expression));
31694             if ((token() === 45 /* PlusPlusToken */ || token() === 46 /* MinusMinusToken */) && !scanner.hasPrecedingLineBreak()) {
31695                 var operator = token();
31696                 nextToken();
31697                 return finishNode(factory.createPostfixUnaryExpression(expression, operator), expression.pos);
31698             }
31699             return expression;
31700         }
31701         function parseLeftHandSideExpressionOrHigher() {
31702             // Original Ecma:
31703             // LeftHandSideExpression: See 11.2
31704             //      NewExpression
31705             //      CallExpression
31706             //
31707             // Our simplification:
31708             //
31709             // LeftHandSideExpression: See 11.2
31710             //      MemberExpression
31711             //      CallExpression
31712             //
31713             // See comment in parseMemberExpressionOrHigher on how we replaced NewExpression with
31714             // MemberExpression to make our lives easier.
31715             //
31716             // to best understand the below code, it's important to see how CallExpression expands
31717             // out into its own productions:
31718             //
31719             // CallExpression:
31720             //      MemberExpression Arguments
31721             //      CallExpression Arguments
31722             //      CallExpression[Expression]
31723             //      CallExpression.IdentifierName
31724             //      import (AssignmentExpression)
31725             //      super Arguments
31726             //      super.IdentifierName
31727             //
31728             // Because of the recursion in these calls, we need to bottom out first. There are three
31729             // bottom out states we can run into: 1) We see 'super' which must start either of
31730             // the last two CallExpression productions. 2) We see 'import' which must start import call.
31731             // 3)we have a MemberExpression which either completes the LeftHandSideExpression,
31732             // or starts the beginning of the first four CallExpression productions.
31733             var pos = getNodePos();
31734             var expression;
31735             if (token() === 99 /* ImportKeyword */) {
31736                 if (lookAhead(nextTokenIsOpenParenOrLessThan)) {
31737                     // We don't want to eagerly consume all import keyword as import call expression so we look ahead to find "("
31738                     // For example:
31739                     //      var foo3 = require("subfolder
31740                     //      import * as foo1 from "module-from-node
31741                     // We want this import to be a statement rather than import call expression
31742                     sourceFlags |= 1048576 /* PossiblyContainsDynamicImport */;
31743                     expression = parseTokenNode();
31744                 }
31745                 else if (lookAhead(nextTokenIsDot)) {
31746                     // This is an 'import.*' metaproperty (i.e. 'import.meta')
31747                     nextToken(); // advance past the 'import'
31748                     nextToken(); // advance past the dot
31749                     expression = finishNode(factory.createMetaProperty(99 /* ImportKeyword */, parseIdentifierName()), pos);
31750                     sourceFlags |= 2097152 /* PossiblyContainsImportMeta */;
31751                 }
31752                 else {
31753                     expression = parseMemberExpressionOrHigher();
31754                 }
31755             }
31756             else {
31757                 expression = token() === 105 /* SuperKeyword */ ? parseSuperExpression() : parseMemberExpressionOrHigher();
31758             }
31759             // Now, we *may* be complete.  However, we might have consumed the start of a
31760             // CallExpression or OptionalExpression.  As such, we need to consume the rest
31761             // of it here to be complete.
31762             return parseCallExpressionRest(pos, expression);
31763         }
31764         function parseMemberExpressionOrHigher() {
31765             // Note: to make our lives simpler, we decompose the NewExpression productions and
31766             // place ObjectCreationExpression and FunctionExpression into PrimaryExpression.
31767             // like so:
31768             //
31769             //   PrimaryExpression : See 11.1
31770             //      this
31771             //      Identifier
31772             //      Literal
31773             //      ArrayLiteral
31774             //      ObjectLiteral
31775             //      (Expression)
31776             //      FunctionExpression
31777             //      new MemberExpression Arguments?
31778             //
31779             //   MemberExpression : See 11.2
31780             //      PrimaryExpression
31781             //      MemberExpression[Expression]
31782             //      MemberExpression.IdentifierName
31783             //
31784             //   CallExpression : See 11.2
31785             //      MemberExpression
31786             //      CallExpression Arguments
31787             //      CallExpression[Expression]
31788             //      CallExpression.IdentifierName
31789             //
31790             // Technically this is ambiguous.  i.e. CallExpression defines:
31791             //
31792             //   CallExpression:
31793             //      CallExpression Arguments
31794             //
31795             // If you see: "new Foo()"
31796             //
31797             // Then that could be treated as a single ObjectCreationExpression, or it could be
31798             // treated as the invocation of "new Foo".  We disambiguate that in code (to match
31799             // the original grammar) by making sure that if we see an ObjectCreationExpression
31800             // we always consume arguments if they are there. So we treat "new Foo()" as an
31801             // object creation only, and not at all as an invocation.  Another way to think
31802             // about this is that for every "new" that we see, we will consume an argument list if
31803             // it is there as part of the *associated* object creation node.  Any additional
31804             // argument lists we see, will become invocation expressions.
31805             //
31806             // Because there are no other places in the grammar now that refer to FunctionExpression
31807             // or ObjectCreationExpression, it is safe to push down into the PrimaryExpression
31808             // production.
31809             //
31810             // Because CallExpression and MemberExpression are left recursive, we need to bottom out
31811             // of the recursion immediately.  So we parse out a primary expression to start with.
31812             var pos = getNodePos();
31813             var expression = parsePrimaryExpression();
31814             return parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
31815         }
31816         function parseSuperExpression() {
31817             var pos = getNodePos();
31818             var expression = parseTokenNode();
31819             if (token() === 29 /* LessThanToken */) {
31820                 var startPos = getNodePos();
31821                 var typeArguments = tryParse(parseTypeArgumentsInExpression);
31822                 if (typeArguments !== undefined) {
31823                     parseErrorAt(startPos, getNodePos(), ts.Diagnostics.super_may_not_use_type_arguments);
31824                 }
31825             }
31826             if (token() === 20 /* OpenParenToken */ || token() === 24 /* DotToken */ || token() === 22 /* OpenBracketToken */) {
31827                 return expression;
31828             }
31829             // If we have seen "super" it must be followed by '(' or '.'.
31830             // If it wasn't then just try to parse out a '.' and report an error.
31831             parseExpectedToken(24 /* DotToken */, ts.Diagnostics.super_must_be_followed_by_an_argument_list_or_member_access);
31832             // private names will never work with `super` (`super.#foo`), but that's a semantic error, not syntactic
31833             return finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true)), pos);
31834         }
31835         function parseJsxElementOrSelfClosingElementOrFragment(inExpressionContext, topInvalidNodePosition) {
31836             var pos = getNodePos();
31837             var opening = parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext);
31838             var result;
31839             if (opening.kind === 275 /* JsxOpeningElement */) {
31840                 var children = parseJsxChildren(opening);
31841                 var closingElement = parseJsxClosingElement(inExpressionContext);
31842                 if (!tagNamesAreEquivalent(opening.tagName, closingElement.tagName)) {
31843                     parseErrorAtRange(closingElement, ts.Diagnostics.Expected_corresponding_JSX_closing_tag_for_0, ts.getTextOfNodeFromSourceText(sourceText, opening.tagName));
31844                 }
31845                 result = finishNode(factory.createJsxElement(opening, children, closingElement), pos);
31846             }
31847             else if (opening.kind === 278 /* JsxOpeningFragment */) {
31848                 result = finishNode(factory.createJsxFragment(opening, parseJsxChildren(opening), parseJsxClosingFragment(inExpressionContext)), pos);
31849             }
31850             else {
31851                 ts.Debug.assert(opening.kind === 274 /* JsxSelfClosingElement */);
31852                 // Nothing else to do for self-closing elements
31853                 result = opening;
31854             }
31855             // If the user writes the invalid code '<div></div><div></div>' in an expression context (i.e. not wrapped in
31856             // an enclosing tag), we'll naively try to parse   ^ this as a 'less than' operator and the remainder of the tag
31857             // as garbage, which will cause the formatter to badly mangle the JSX. Perform a speculative parse of a JSX
31858             // element if we see a < token so that we can wrap it in a synthetic binary expression so the formatter
31859             // does less damage and we can report a better error.
31860             // Since JSX elements are invalid < operands anyway, this lookahead parse will only occur in error scenarios
31861             // of one sort or another.
31862             if (inExpressionContext && token() === 29 /* LessThanToken */) {
31863                 var topBadPos_1 = typeof topInvalidNodePosition === "undefined" ? result.pos : topInvalidNodePosition;
31864                 var invalidElement = tryParse(function () { return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ true, topBadPos_1); });
31865                 if (invalidElement) {
31866                     var operatorToken = createMissingNode(27 /* CommaToken */, /*reportAtCurrentPosition*/ false);
31867                     ts.setTextRangePosWidth(operatorToken, invalidElement.pos, 0);
31868                     parseErrorAt(ts.skipTrivia(sourceText, topBadPos_1), invalidElement.end, ts.Diagnostics.JSX_expressions_must_have_one_parent_element);
31869                     return finishNode(factory.createBinaryExpression(result, operatorToken, invalidElement), pos);
31870                 }
31871             }
31872             return result;
31873         }
31874         function parseJsxText() {
31875             var pos = getNodePos();
31876             var node = factory.createJsxText(scanner.getTokenValue(), currentToken === 12 /* JsxTextAllWhiteSpaces */);
31877             currentToken = scanner.scanJsxToken();
31878             return finishNode(node, pos);
31879         }
31880         function parseJsxChild(openingTag, token) {
31881             switch (token) {
31882                 case 1 /* EndOfFileToken */:
31883                     // If we hit EOF, issue the error at the tag that lacks the closing element
31884                     // rather than at the end of the file (which is useless)
31885                     if (ts.isJsxOpeningFragment(openingTag)) {
31886                         parseErrorAtRange(openingTag, ts.Diagnostics.JSX_fragment_has_no_corresponding_closing_tag);
31887                     }
31888                     else {
31889                         // We want the error span to cover only 'Foo.Bar' in < Foo.Bar >
31890                         // or to cover only 'Foo' in < Foo >
31891                         var tag = openingTag.tagName;
31892                         var start = ts.skipTrivia(sourceText, tag.pos);
31893                         parseErrorAt(start, tag.end, ts.Diagnostics.JSX_element_0_has_no_corresponding_closing_tag, ts.getTextOfNodeFromSourceText(sourceText, openingTag.tagName));
31894                     }
31895                     return undefined;
31896                 case 30 /* LessThanSlashToken */:
31897                 case 7 /* ConflictMarkerTrivia */:
31898                     return undefined;
31899                 case 11 /* JsxText */:
31900                 case 12 /* JsxTextAllWhiteSpaces */:
31901                     return parseJsxText();
31902                 case 18 /* OpenBraceToken */:
31903                     return parseJsxExpression(/*inExpressionContext*/ false);
31904                 case 29 /* LessThanToken */:
31905                     return parseJsxElementOrSelfClosingElementOrFragment(/*inExpressionContext*/ false);
31906                 default:
31907                     return ts.Debug.assertNever(token);
31908             }
31909         }
31910         function parseJsxChildren(openingTag) {
31911             var list = [];
31912             var listPos = getNodePos();
31913             var saveParsingContext = parsingContext;
31914             parsingContext |= 1 << 14 /* JsxChildren */;
31915             while (true) {
31916                 var child = parseJsxChild(openingTag, currentToken = scanner.reScanJsxToken());
31917                 if (!child)
31918                     break;
31919                 list.push(child);
31920             }
31921             parsingContext = saveParsingContext;
31922             return createNodeArray(list, listPos);
31923         }
31924         function parseJsxAttributes() {
31925             var pos = getNodePos();
31926             return finishNode(factory.createJsxAttributes(parseList(13 /* JsxAttributes */, parseJsxAttribute)), pos);
31927         }
31928         function parseJsxOpeningOrSelfClosingElementOrOpeningFragment(inExpressionContext) {
31929             var pos = getNodePos();
31930             parseExpected(29 /* LessThanToken */);
31931             if (token() === 31 /* GreaterThanToken */) {
31932                 // See below for explanation of scanJsxText
31933                 scanJsxText();
31934                 return finishNode(factory.createJsxOpeningFragment(), pos);
31935             }
31936             var tagName = parseJsxElementName();
31937             var typeArguments = tryParseTypeArguments();
31938             var attributes = parseJsxAttributes();
31939             var node;
31940             if (token() === 31 /* GreaterThanToken */) {
31941                 // Closing tag, so scan the immediately-following text with the JSX scanning instead
31942                 // of regular scanning to avoid treating illegal characters (e.g. '#') as immediate
31943                 // scanning errors
31944                 scanJsxText();
31945                 node = factory.createJsxOpeningElement(tagName, typeArguments, attributes);
31946             }
31947             else {
31948                 parseExpected(43 /* SlashToken */);
31949                 if (inExpressionContext) {
31950                     parseExpected(31 /* GreaterThanToken */);
31951                 }
31952                 else {
31953                     parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
31954                     scanJsxText();
31955                 }
31956                 node = factory.createJsxSelfClosingElement(tagName, typeArguments, attributes);
31957             }
31958             return finishNode(node, pos);
31959         }
31960         function parseJsxElementName() {
31961             var pos = getNodePos();
31962             scanJsxIdentifier();
31963             // JsxElement can have name in the form of
31964             //      propertyAccessExpression
31965             //      primaryExpression in the form of an identifier and "this" keyword
31966             // We can't just simply use parseLeftHandSideExpressionOrHigher because then we will start consider class,function etc as a keyword
31967             // We only want to consider "this" as a primaryExpression
31968             var expression = token() === 107 /* ThisKeyword */ ?
31969                 parseTokenNode() : parseIdentifierName();
31970             while (parseOptional(24 /* DotToken */)) {
31971                 expression = finishNode(factory.createPropertyAccessExpression(expression, parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ false)), pos);
31972             }
31973             return expression;
31974         }
31975         function parseJsxExpression(inExpressionContext) {
31976             var pos = getNodePos();
31977             if (!parseExpected(18 /* OpenBraceToken */)) {
31978                 return undefined;
31979             }
31980             var dotDotDotToken;
31981             var expression;
31982             if (token() !== 19 /* CloseBraceToken */) {
31983                 dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
31984                 // Only an AssignmentExpression is valid here per the JSX spec,
31985                 // but we can unambiguously parse a comma sequence and provide
31986                 // a better error message in grammar checking.
31987                 expression = parseExpression();
31988             }
31989             if (inExpressionContext) {
31990                 parseExpected(19 /* CloseBraceToken */);
31991             }
31992             else {
31993                 if (parseExpected(19 /* CloseBraceToken */, /*message*/ undefined, /*shouldAdvance*/ false)) {
31994                     scanJsxText();
31995                 }
31996             }
31997             return finishNode(factory.createJsxExpression(dotDotDotToken, expression), pos);
31998         }
31999         function parseJsxAttribute() {
32000             if (token() === 18 /* OpenBraceToken */) {
32001                 return parseJsxSpreadAttribute();
32002             }
32003             scanJsxIdentifier();
32004             var pos = getNodePos();
32005             return finishNode(factory.createJsxAttribute(parseIdentifierName(), token() !== 62 /* EqualsToken */ ? undefined :
32006                 scanJsxAttributeValue() === 10 /* StringLiteral */ ? parseLiteralNode() :
32007                     parseJsxExpression(/*inExpressionContext*/ true)), pos);
32008         }
32009         function parseJsxSpreadAttribute() {
32010             var pos = getNodePos();
32011             parseExpected(18 /* OpenBraceToken */);
32012             parseExpected(25 /* DotDotDotToken */);
32013             var expression = parseExpression();
32014             parseExpected(19 /* CloseBraceToken */);
32015             return finishNode(factory.createJsxSpreadAttribute(expression), pos);
32016         }
32017         function parseJsxClosingElement(inExpressionContext) {
32018             var pos = getNodePos();
32019             parseExpected(30 /* LessThanSlashToken */);
32020             var tagName = parseJsxElementName();
32021             if (inExpressionContext) {
32022                 parseExpected(31 /* GreaterThanToken */);
32023             }
32024             else {
32025                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
32026                 scanJsxText();
32027             }
32028             return finishNode(factory.createJsxClosingElement(tagName), pos);
32029         }
32030         function parseJsxClosingFragment(inExpressionContext) {
32031             var pos = getNodePos();
32032             parseExpected(30 /* LessThanSlashToken */);
32033             if (ts.tokenIsIdentifierOrKeyword(token())) {
32034                 parseErrorAtRange(parseJsxElementName(), ts.Diagnostics.Expected_corresponding_closing_tag_for_JSX_fragment);
32035             }
32036             if (inExpressionContext) {
32037                 parseExpected(31 /* GreaterThanToken */);
32038             }
32039             else {
32040                 parseExpected(31 /* GreaterThanToken */, /*diagnostic*/ undefined, /*shouldAdvance*/ false);
32041                 scanJsxText();
32042             }
32043             return finishNode(factory.createJsxJsxClosingFragment(), pos);
32044         }
32045         function parseTypeAssertion() {
32046             var pos = getNodePos();
32047             parseExpected(29 /* LessThanToken */);
32048             var type = parseType();
32049             parseExpected(31 /* GreaterThanToken */);
32050             var expression = parseSimpleUnaryExpression();
32051             return finishNode(factory.createTypeAssertion(type, expression), pos);
32052         }
32053         function nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate() {
32054             nextToken();
32055             return ts.tokenIsIdentifierOrKeyword(token())
32056                 || token() === 22 /* OpenBracketToken */
32057                 || isTemplateStartOfTaggedTemplate();
32058         }
32059         function isStartOfOptionalPropertyOrElementAccessChain() {
32060             return token() === 28 /* QuestionDotToken */
32061                 && lookAhead(nextTokenIsIdentifierOrKeywordOrOpenBracketOrTemplate);
32062         }
32063         function tryReparseOptionalChain(node) {
32064             if (node.flags & 32 /* OptionalChain */) {
32065                 return true;
32066             }
32067             // check for an optional chain in a non-null expression
32068             if (ts.isNonNullExpression(node)) {
32069                 var expr = node.expression;
32070                 while (ts.isNonNullExpression(expr) && !(expr.flags & 32 /* OptionalChain */)) {
32071                     expr = expr.expression;
32072                 }
32073                 if (expr.flags & 32 /* OptionalChain */) {
32074                     // this is part of an optional chain. Walk down from `node` to `expression` and set the flag.
32075                     while (ts.isNonNullExpression(node)) {
32076                         node.flags |= 32 /* OptionalChain */;
32077                         node = node.expression;
32078                     }
32079                     return true;
32080                 }
32081             }
32082             return false;
32083         }
32084         function parsePropertyAccessExpressionRest(pos, expression, questionDotToken) {
32085             var name = parseRightSideOfDot(/*allowIdentifierNames*/ true, /*allowPrivateIdentifiers*/ true);
32086             var isOptionalChain = questionDotToken || tryReparseOptionalChain(expression);
32087             var propertyAccess = isOptionalChain ?
32088                 factory.createPropertyAccessChain(expression, questionDotToken, name) :
32089                 factory.createPropertyAccessExpression(expression, name);
32090             if (isOptionalChain && ts.isPrivateIdentifier(propertyAccess.name)) {
32091                 parseErrorAtRange(propertyAccess.name, ts.Diagnostics.An_optional_chain_cannot_contain_private_identifiers);
32092             }
32093             return finishNode(propertyAccess, pos);
32094         }
32095         function parseElementAccessExpressionRest(pos, expression, questionDotToken) {
32096             var argumentExpression;
32097             if (token() === 23 /* CloseBracketToken */) {
32098                 argumentExpression = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.An_element_access_expression_should_take_an_argument);
32099             }
32100             else {
32101                 var argument = allowInAnd(parseExpression);
32102                 if (ts.isStringOrNumericLiteralLike(argument)) {
32103                     argument.text = internIdentifier(argument.text);
32104                 }
32105                 argumentExpression = argument;
32106             }
32107             parseExpected(23 /* CloseBracketToken */);
32108             var indexedAccess = questionDotToken || tryReparseOptionalChain(expression) ?
32109                 factory.createElementAccessChain(expression, questionDotToken, argumentExpression) :
32110                 factory.createElementAccessExpression(expression, argumentExpression);
32111             return finishNode(indexedAccess, pos);
32112         }
32113         function parseMemberExpressionRest(pos, expression, allowOptionalChain) {
32114             while (true) {
32115                 var questionDotToken = void 0;
32116                 var isPropertyAccess = false;
32117                 if (allowOptionalChain && isStartOfOptionalPropertyOrElementAccessChain()) {
32118                     questionDotToken = parseExpectedToken(28 /* QuestionDotToken */);
32119                     isPropertyAccess = ts.tokenIsIdentifierOrKeyword(token());
32120                 }
32121                 else {
32122                     isPropertyAccess = parseOptional(24 /* DotToken */);
32123                 }
32124                 if (isPropertyAccess) {
32125                     expression = parsePropertyAccessExpressionRest(pos, expression, questionDotToken);
32126                     continue;
32127                 }
32128                 if (!questionDotToken && token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
32129                     nextToken();
32130                     expression = finishNode(factory.createNonNullExpression(expression), pos);
32131                     continue;
32132                 }
32133                 // when in the [Decorator] context, we do not parse ElementAccess as it could be part of a ComputedPropertyName
32134                 if ((questionDotToken || !inDecoratorContext()) && parseOptional(22 /* OpenBracketToken */)) {
32135                     expression = parseElementAccessExpressionRest(pos, expression, questionDotToken);
32136                     continue;
32137                 }
32138                 if (isTemplateStartOfTaggedTemplate()) {
32139                     expression = parseTaggedTemplateRest(pos, expression, questionDotToken, /*typeArguments*/ undefined);
32140                     continue;
32141                 }
32142                 return expression;
32143             }
32144         }
32145         function isTemplateStartOfTaggedTemplate() {
32146             return token() === 14 /* NoSubstitutionTemplateLiteral */ || token() === 15 /* TemplateHead */;
32147         }
32148         function parseTaggedTemplateRest(pos, tag, questionDotToken, typeArguments) {
32149             var tagExpression = factory.createTaggedTemplateExpression(tag, typeArguments, token() === 14 /* NoSubstitutionTemplateLiteral */ ?
32150                 (reScanTemplateHeadOrNoSubstitutionTemplate(), parseLiteralNode()) :
32151                 parseTemplateExpression(/*isTaggedTemplate*/ true));
32152             if (questionDotToken || tag.flags & 32 /* OptionalChain */) {
32153                 tagExpression.flags |= 32 /* OptionalChain */;
32154             }
32155             tagExpression.questionDotToken = questionDotToken;
32156             return finishNode(tagExpression, pos);
32157         }
32158         function parseCallExpressionRest(pos, expression) {
32159             while (true) {
32160                 expression = parseMemberExpressionRest(pos, expression, /*allowOptionalChain*/ true);
32161                 var questionDotToken = parseOptionalToken(28 /* QuestionDotToken */);
32162                 // handle 'foo<<T>()'
32163                 if (token() === 29 /* LessThanToken */ || token() === 47 /* LessThanLessThanToken */) {
32164                     // See if this is the start of a generic invocation.  If so, consume it and
32165                     // keep checking for postfix expressions.  Otherwise, it's just a '<' that's
32166                     // part of an arithmetic expression.  Break out so we consume it higher in the
32167                     // stack.
32168                     var typeArguments = tryParse(parseTypeArgumentsInExpression);
32169                     if (typeArguments) {
32170                         if (isTemplateStartOfTaggedTemplate()) {
32171                             expression = parseTaggedTemplateRest(pos, expression, questionDotToken, typeArguments);
32172                             continue;
32173                         }
32174                         var argumentList = parseArgumentList();
32175                         var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
32176                             factory.createCallChain(expression, questionDotToken, typeArguments, argumentList) :
32177                             factory.createCallExpression(expression, typeArguments, argumentList);
32178                         expression = finishNode(callExpr, pos);
32179                         continue;
32180                     }
32181                 }
32182                 else if (token() === 20 /* OpenParenToken */) {
32183                     var argumentList = parseArgumentList();
32184                     var callExpr = questionDotToken || tryReparseOptionalChain(expression) ?
32185                         factory.createCallChain(expression, questionDotToken, /*typeArguments*/ undefined, argumentList) :
32186                         factory.createCallExpression(expression, /*typeArguments*/ undefined, argumentList);
32187                     expression = finishNode(callExpr, pos);
32188                     continue;
32189                 }
32190                 if (questionDotToken) {
32191                     // We failed to parse anything, so report a missing identifier here.
32192                     var name = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ false, ts.Diagnostics.Identifier_expected);
32193                     expression = finishNode(factory.createPropertyAccessChain(expression, questionDotToken, name), pos);
32194                 }
32195                 break;
32196             }
32197             return expression;
32198         }
32199         function parseArgumentList() {
32200             parseExpected(20 /* OpenParenToken */);
32201             var result = parseDelimitedList(11 /* ArgumentExpressions */, parseArgumentExpression);
32202             parseExpected(21 /* CloseParenToken */);
32203             return result;
32204         }
32205         function parseTypeArgumentsInExpression() {
32206             if (reScanLessThanToken() !== 29 /* LessThanToken */) {
32207                 return undefined;
32208             }
32209             nextToken();
32210             var typeArguments = parseDelimitedList(20 /* TypeArguments */, parseType);
32211             if (!parseExpected(31 /* GreaterThanToken */)) {
32212                 // If it doesn't have the closing `>` then it's definitely not an type argument list.
32213                 return undefined;
32214             }
32215             // If we have a '<', then only parse this as a argument list if the type arguments
32216             // are complete and we have an open paren.  if we don't, rewind and return nothing.
32217             return typeArguments && canFollowTypeArgumentsInExpression()
32218                 ? typeArguments
32219                 : undefined;
32220         }
32221         function canFollowTypeArgumentsInExpression() {
32222             switch (token()) {
32223                 case 20 /* OpenParenToken */: // foo<x>(
32224                 case 14 /* NoSubstitutionTemplateLiteral */: // foo<T> `...`
32225                 case 15 /* TemplateHead */: // foo<T> `...${100}...`
32226                 // these are the only tokens can legally follow a type argument
32227                 // list. So we definitely want to treat them as type arg lists.
32228                 // falls through
32229                 case 24 /* DotToken */: // foo<x>.
32230                 case 21 /* CloseParenToken */: // foo<x>)
32231                 case 23 /* CloseBracketToken */: // foo<x>]
32232                 case 58 /* ColonToken */: // foo<x>:
32233                 case 26 /* SemicolonToken */: // foo<x>;
32234                 case 57 /* QuestionToken */: // foo<x>?
32235                 case 34 /* EqualsEqualsToken */: // foo<x> ==
32236                 case 36 /* EqualsEqualsEqualsToken */: // foo<x> ===
32237                 case 35 /* ExclamationEqualsToken */: // foo<x> !=
32238                 case 37 /* ExclamationEqualsEqualsToken */: // foo<x> !==
32239                 case 55 /* AmpersandAmpersandToken */: // foo<x> &&
32240                 case 56 /* BarBarToken */: // foo<x> ||
32241                 case 60 /* QuestionQuestionToken */: // foo<x> ??
32242                 case 52 /* CaretToken */: // foo<x> ^
32243                 case 50 /* AmpersandToken */: // foo<x> &
32244                 case 51 /* BarToken */: // foo<x> |
32245                 case 19 /* CloseBraceToken */: // foo<x> }
32246                 case 1 /* EndOfFileToken */: // foo<x>
32247                     // these cases can't legally follow a type arg list.  However, they're not legal
32248                     // expressions either.  The user is probably in the middle of a generic type. So
32249                     // treat it as such.
32250                     return true;
32251                 case 27 /* CommaToken */: // foo<x>,
32252                 case 18 /* OpenBraceToken */: // foo<x> {
32253                 // We don't want to treat these as type arguments.  Otherwise we'll parse this
32254                 // as an invocation expression.  Instead, we want to parse out the expression
32255                 // in isolation from the type arguments.
32256                 // falls through
32257                 default:
32258                     // Anything else treat as an expression.
32259                     return false;
32260             }
32261         }
32262         function parsePrimaryExpression() {
32263             switch (token()) {
32264                 case 8 /* NumericLiteral */:
32265                 case 9 /* BigIntLiteral */:
32266                 case 10 /* StringLiteral */:
32267                 case 14 /* NoSubstitutionTemplateLiteral */:
32268                     return parseLiteralNode();
32269                 case 107 /* ThisKeyword */:
32270                 case 105 /* SuperKeyword */:
32271                 case 103 /* NullKeyword */:
32272                 case 109 /* TrueKeyword */:
32273                 case 94 /* FalseKeyword */:
32274                     return parseTokenNode();
32275                 case 20 /* OpenParenToken */:
32276                     return parseParenthesizedExpression();
32277                 case 22 /* OpenBracketToken */:
32278                     return parseArrayLiteralExpression();
32279                 case 18 /* OpenBraceToken */:
32280                     return parseObjectLiteralExpression();
32281                 case 129 /* AsyncKeyword */:
32282                     // Async arrow functions are parsed earlier in parseAssignmentExpressionOrHigher.
32283                     // If we encounter `async [no LineTerminator here] function` then this is an async
32284                     // function; otherwise, its an identifier.
32285                     if (!lookAhead(nextTokenIsFunctionKeywordOnSameLine)) {
32286                         break;
32287                     }
32288                     return parseFunctionExpression();
32289                 case 83 /* ClassKeyword */:
32290                     return parseClassExpression();
32291                 case 97 /* FunctionKeyword */:
32292                     return parseFunctionExpression();
32293                 case 102 /* NewKeyword */:
32294                     return parseNewExpressionOrNewDotTarget();
32295                 case 43 /* SlashToken */:
32296                 case 67 /* SlashEqualsToken */:
32297                     if (reScanSlashToken() === 13 /* RegularExpressionLiteral */) {
32298                         return parseLiteralNode();
32299                     }
32300                     break;
32301                 case 15 /* TemplateHead */:
32302                     return parseTemplateExpression(/* isTaggedTemplate */ false);
32303             }
32304             return parseIdentifier(ts.Diagnostics.Expression_expected);
32305         }
32306         function parseParenthesizedExpression() {
32307             var pos = getNodePos();
32308             var hasJSDoc = hasPrecedingJSDocComment();
32309             parseExpected(20 /* OpenParenToken */);
32310             var expression = allowInAnd(parseExpression);
32311             parseExpected(21 /* CloseParenToken */);
32312             return withJSDoc(finishNode(factory.createParenthesizedExpression(expression), pos), hasJSDoc);
32313         }
32314         function parseSpreadElement() {
32315             var pos = getNodePos();
32316             parseExpected(25 /* DotDotDotToken */);
32317             var expression = parseAssignmentExpressionOrHigher();
32318             return finishNode(factory.createSpreadElement(expression), pos);
32319         }
32320         function parseArgumentOrArrayLiteralElement() {
32321             return token() === 25 /* DotDotDotToken */ ? parseSpreadElement() :
32322                 token() === 27 /* CommaToken */ ? finishNode(factory.createOmittedExpression(), getNodePos()) :
32323                     parseAssignmentExpressionOrHigher();
32324         }
32325         function parseArgumentExpression() {
32326             return doOutsideOfContext(disallowInAndDecoratorContext, parseArgumentOrArrayLiteralElement);
32327         }
32328         function parseArrayLiteralExpression() {
32329             var pos = getNodePos();
32330             parseExpected(22 /* OpenBracketToken */);
32331             var multiLine = scanner.hasPrecedingLineBreak();
32332             var elements = parseDelimitedList(15 /* ArrayLiteralMembers */, parseArgumentOrArrayLiteralElement);
32333             parseExpected(23 /* CloseBracketToken */);
32334             return finishNode(factory.createArrayLiteralExpression(elements, multiLine), pos);
32335         }
32336         function parseObjectLiteralElement() {
32337             var pos = getNodePos();
32338             var hasJSDoc = hasPrecedingJSDocComment();
32339             if (parseOptionalToken(25 /* DotDotDotToken */)) {
32340                 var expression = parseAssignmentExpressionOrHigher();
32341                 return withJSDoc(finishNode(factory.createSpreadAssignment(expression), pos), hasJSDoc);
32342             }
32343             var decorators = parseDecorators();
32344             var modifiers = parseModifiers();
32345             if (parseContextualModifier(134 /* GetKeyword */)) {
32346                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */);
32347             }
32348             if (parseContextualModifier(146 /* SetKeyword */)) {
32349                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */);
32350             }
32351             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
32352             var tokenIsIdentifier = isIdentifier();
32353             var name = parsePropertyName();
32354             // Disallowing of optional property assignments and definite assignment assertion happens in the grammar checker.
32355             var questionToken = parseOptionalToken(57 /* QuestionToken */);
32356             var exclamationToken = parseOptionalToken(53 /* ExclamationToken */);
32357             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
32358                 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken);
32359             }
32360             // check if it is short-hand property assignment or normal property assignment
32361             // NOTE: if token is EqualsToken it is interpreted as CoverInitializedName production
32362             // CoverInitializedName[Yield] :
32363             //     IdentifierReference[?Yield] Initializer[In, ?Yield]
32364             // this is necessary because ObjectLiteral productions are also used to cover grammar for ObjectAssignmentPattern
32365             var node;
32366             var isShorthandPropertyAssignment = tokenIsIdentifier && (token() !== 58 /* ColonToken */);
32367             if (isShorthandPropertyAssignment) {
32368                 var equalsToken = parseOptionalToken(62 /* EqualsToken */);
32369                 var objectAssignmentInitializer = equalsToken ? allowInAnd(parseAssignmentExpressionOrHigher) : undefined;
32370                 node = factory.createShorthandPropertyAssignment(name, objectAssignmentInitializer);
32371                 // Save equals token for error reporting.
32372                 // TODO(rbuckton): Consider manufacturing this when we need to report an error as it is otherwise not useful.
32373                 node.equalsToken = equalsToken;
32374             }
32375             else {
32376                 parseExpected(58 /* ColonToken */);
32377                 var initializer = allowInAnd(parseAssignmentExpressionOrHigher);
32378                 node = factory.createPropertyAssignment(name, initializer);
32379             }
32380             // Decorators, Modifiers, questionToken, and exclamationToken are not supported by property assignments and are reported in the grammar checker
32381             node.decorators = decorators;
32382             node.modifiers = modifiers;
32383             node.questionToken = questionToken;
32384             node.exclamationToken = exclamationToken;
32385             return withJSDoc(finishNode(node, pos), hasJSDoc);
32386         }
32387         function parseObjectLiteralExpression() {
32388             var pos = getNodePos();
32389             var openBracePosition = scanner.getTokenPos();
32390             parseExpected(18 /* OpenBraceToken */);
32391             var multiLine = scanner.hasPrecedingLineBreak();
32392             var properties = parseDelimitedList(12 /* ObjectLiteralMembers */, parseObjectLiteralElement, /*considerSemicolonAsDelimiter*/ true);
32393             if (!parseExpected(19 /* CloseBraceToken */)) {
32394                 var lastError = ts.lastOrUndefined(parseDiagnostics);
32395                 if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
32396                     ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
32397                 }
32398             }
32399             return finishNode(factory.createObjectLiteralExpression(properties, multiLine), pos);
32400         }
32401         function parseFunctionExpression() {
32402             // GeneratorExpression:
32403             //      function* BindingIdentifier [Yield][opt](FormalParameters[Yield]){ GeneratorBody }
32404             //
32405             // FunctionExpression:
32406             //      function BindingIdentifier[opt](FormalParameters){ FunctionBody }
32407             var saveDecoratorContext = inDecoratorContext();
32408             if (saveDecoratorContext) {
32409                 setDecoratorContext(/*val*/ false);
32410             }
32411             var pos = getNodePos();
32412             var hasJSDoc = hasPrecedingJSDocComment();
32413             var modifiers = parseModifiers();
32414             parseExpected(97 /* FunctionKeyword */);
32415             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
32416             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
32417             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
32418             var name = isGenerator && isAsync ? doInYieldAndAwaitContext(parseOptionalBindingIdentifier) :
32419                 isGenerator ? doInYieldContext(parseOptionalBindingIdentifier) :
32420                     isAsync ? doInAwaitContext(parseOptionalBindingIdentifier) :
32421                         parseOptionalBindingIdentifier();
32422             var typeParameters = parseTypeParameters();
32423             var parameters = parseParameters(isGenerator | isAsync);
32424             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
32425             var body = parseFunctionBlock(isGenerator | isAsync);
32426             if (saveDecoratorContext) {
32427                 setDecoratorContext(/*val*/ true);
32428             }
32429             var node = factory.createFunctionExpression(modifiers, asteriskToken, name, typeParameters, parameters, type, body);
32430             return withJSDoc(finishNode(node, pos), hasJSDoc);
32431         }
32432         function parseOptionalBindingIdentifier() {
32433             return isBindingIdentifier() ? parseBindingIdentifier() : undefined;
32434         }
32435         function parseNewExpressionOrNewDotTarget() {
32436             var pos = getNodePos();
32437             parseExpected(102 /* NewKeyword */);
32438             if (parseOptional(24 /* DotToken */)) {
32439                 var name = parseIdentifierName();
32440                 return finishNode(factory.createMetaProperty(102 /* NewKeyword */, name), pos);
32441             }
32442             var expressionPos = getNodePos();
32443             var expression = parsePrimaryExpression();
32444             var typeArguments;
32445             while (true) {
32446                 expression = parseMemberExpressionRest(expressionPos, expression, /*allowOptionalChain*/ false);
32447                 typeArguments = tryParse(parseTypeArgumentsInExpression);
32448                 if (isTemplateStartOfTaggedTemplate()) {
32449                     ts.Debug.assert(!!typeArguments, "Expected a type argument list; all plain tagged template starts should be consumed in 'parseMemberExpressionRest'");
32450                     expression = parseTaggedTemplateRest(expressionPos, expression, /*optionalChain*/ undefined, typeArguments);
32451                     typeArguments = undefined;
32452                 }
32453                 break;
32454             }
32455             var argumentsArray;
32456             if (token() === 20 /* OpenParenToken */) {
32457                 argumentsArray = parseArgumentList();
32458             }
32459             else if (typeArguments) {
32460                 parseErrorAt(pos, scanner.getStartPos(), ts.Diagnostics.A_new_expression_with_type_arguments_must_always_be_followed_by_a_parenthesized_argument_list);
32461             }
32462             return finishNode(factory.createNewExpression(expression, typeArguments, argumentsArray), pos);
32463         }
32464         // STATEMENTS
32465         function parseBlock(ignoreMissingOpenBrace, diagnosticMessage) {
32466             var pos = getNodePos();
32467             var openBracePosition = scanner.getTokenPos();
32468             if (parseExpected(18 /* OpenBraceToken */, diagnosticMessage) || ignoreMissingOpenBrace) {
32469                 var multiLine = scanner.hasPrecedingLineBreak();
32470                 var statements = parseList(1 /* BlockStatements */, parseStatement);
32471                 if (!parseExpected(19 /* CloseBraceToken */)) {
32472                     var lastError = ts.lastOrUndefined(parseDiagnostics);
32473                     if (lastError && lastError.code === ts.Diagnostics._0_expected.code) {
32474                         ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, openBracePosition, 1, ts.Diagnostics.The_parser_expected_to_find_a_to_match_the_token_here));
32475                     }
32476                 }
32477                 return finishNode(factory.createBlock(statements, multiLine), pos);
32478             }
32479             else {
32480                 var statements = createMissingList();
32481                 return finishNode(factory.createBlock(statements, /*multiLine*/ undefined), pos);
32482             }
32483         }
32484         function parseFunctionBlock(flags, diagnosticMessage) {
32485             var savedYieldContext = inYieldContext();
32486             setYieldContext(!!(flags & 1 /* Yield */));
32487             var savedAwaitContext = inAwaitContext();
32488             setAwaitContext(!!(flags & 2 /* Await */));
32489             var savedTopLevel = topLevel;
32490             topLevel = false;
32491             // We may be in a [Decorator] context when parsing a function expression or
32492             // arrow function. The body of the function is not in [Decorator] context.
32493             var saveDecoratorContext = inDecoratorContext();
32494             if (saveDecoratorContext) {
32495                 setDecoratorContext(/*val*/ false);
32496             }
32497             var block = parseBlock(!!(flags & 16 /* IgnoreMissingOpenBrace */), diagnosticMessage);
32498             if (saveDecoratorContext) {
32499                 setDecoratorContext(/*val*/ true);
32500             }
32501             topLevel = savedTopLevel;
32502             setYieldContext(savedYieldContext);
32503             setAwaitContext(savedAwaitContext);
32504             return block;
32505         }
32506         function parseEmptyStatement() {
32507             var pos = getNodePos();
32508             parseExpected(26 /* SemicolonToken */);
32509             return finishNode(factory.createEmptyStatement(), pos);
32510         }
32511         function parseIfStatement() {
32512             var pos = getNodePos();
32513             parseExpected(98 /* IfKeyword */);
32514             parseExpected(20 /* OpenParenToken */);
32515             var expression = allowInAnd(parseExpression);
32516             parseExpected(21 /* CloseParenToken */);
32517             var thenStatement = parseStatement();
32518             var elseStatement = parseOptional(90 /* ElseKeyword */) ? parseStatement() : undefined;
32519             return finishNode(factory.createIfStatement(expression, thenStatement, elseStatement), pos);
32520         }
32521         function parseDoStatement() {
32522             var pos = getNodePos();
32523             parseExpected(89 /* DoKeyword */);
32524             var statement = parseStatement();
32525             parseExpected(114 /* WhileKeyword */);
32526             parseExpected(20 /* OpenParenToken */);
32527             var expression = allowInAnd(parseExpression);
32528             parseExpected(21 /* CloseParenToken */);
32529             // From: https://mail.mozilla.org/pipermail/es-discuss/2011-August/016188.html
32530             // 157 min --- All allen at wirfs-brock.com CONF --- "do{;}while(false)false" prohibited in
32531             // spec but allowed in consensus reality. Approved -- this is the de-facto standard whereby
32532             //  do;while(0)x will have a semicolon inserted before x.
32533             parseOptional(26 /* SemicolonToken */);
32534             return finishNode(factory.createDoStatement(statement, expression), pos);
32535         }
32536         function parseWhileStatement() {
32537             var pos = getNodePos();
32538             parseExpected(114 /* WhileKeyword */);
32539             parseExpected(20 /* OpenParenToken */);
32540             var expression = allowInAnd(parseExpression);
32541             parseExpected(21 /* CloseParenToken */);
32542             var statement = parseStatement();
32543             return finishNode(factory.createWhileStatement(expression, statement), pos);
32544         }
32545         function parseForOrForInOrForOfStatement() {
32546             var pos = getNodePos();
32547             parseExpected(96 /* ForKeyword */);
32548             var awaitToken = parseOptionalToken(130 /* AwaitKeyword */);
32549             parseExpected(20 /* OpenParenToken */);
32550             var initializer;
32551             if (token() !== 26 /* SemicolonToken */) {
32552                 if (token() === 112 /* VarKeyword */ || token() === 118 /* LetKeyword */ || token() === 84 /* ConstKeyword */) {
32553                     initializer = parseVariableDeclarationList(/*inForStatementInitializer*/ true);
32554                 }
32555                 else {
32556                     initializer = disallowInAnd(parseExpression);
32557                 }
32558             }
32559             var node;
32560             if (awaitToken ? parseExpected(156 /* OfKeyword */) : parseOptional(156 /* OfKeyword */)) {
32561                 var expression = allowInAnd(parseAssignmentExpressionOrHigher);
32562                 parseExpected(21 /* CloseParenToken */);
32563                 node = factory.createForOfStatement(awaitToken, initializer, expression, parseStatement());
32564             }
32565             else if (parseOptional(100 /* InKeyword */)) {
32566                 var expression = allowInAnd(parseExpression);
32567                 parseExpected(21 /* CloseParenToken */);
32568                 node = factory.createForInStatement(initializer, expression, parseStatement());
32569             }
32570             else {
32571                 parseExpected(26 /* SemicolonToken */);
32572                 var condition = token() !== 26 /* SemicolonToken */ && token() !== 21 /* CloseParenToken */
32573                     ? allowInAnd(parseExpression)
32574                     : undefined;
32575                 parseExpected(26 /* SemicolonToken */);
32576                 var incrementor = token() !== 21 /* CloseParenToken */
32577                     ? allowInAnd(parseExpression)
32578                     : undefined;
32579                 parseExpected(21 /* CloseParenToken */);
32580                 node = factory.createForStatement(initializer, condition, incrementor, parseStatement());
32581             }
32582             return finishNode(node, pos);
32583         }
32584         function parseBreakOrContinueStatement(kind) {
32585             var pos = getNodePos();
32586             parseExpected(kind === 241 /* BreakStatement */ ? 80 /* BreakKeyword */ : 85 /* ContinueKeyword */);
32587             var label = canParseSemicolon() ? undefined : parseIdentifier();
32588             parseSemicolon();
32589             var node = kind === 241 /* BreakStatement */
32590                 ? factory.createBreakStatement(label)
32591                 : factory.createContinueStatement(label);
32592             return finishNode(node, pos);
32593         }
32594         function parseReturnStatement() {
32595             var pos = getNodePos();
32596             parseExpected(104 /* ReturnKeyword */);
32597             var expression = canParseSemicolon() ? undefined : allowInAnd(parseExpression);
32598             parseSemicolon();
32599             return finishNode(factory.createReturnStatement(expression), pos);
32600         }
32601         function parseWithStatement() {
32602             var pos = getNodePos();
32603             parseExpected(115 /* WithKeyword */);
32604             parseExpected(20 /* OpenParenToken */);
32605             var expression = allowInAnd(parseExpression);
32606             parseExpected(21 /* CloseParenToken */);
32607             var statement = doInsideOfContext(16777216 /* InWithStatement */, parseStatement);
32608             return finishNode(factory.createWithStatement(expression, statement), pos);
32609         }
32610         function parseCaseClause() {
32611             var pos = getNodePos();
32612             parseExpected(81 /* CaseKeyword */);
32613             var expression = allowInAnd(parseExpression);
32614             parseExpected(58 /* ColonToken */);
32615             var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
32616             return finishNode(factory.createCaseClause(expression, statements), pos);
32617         }
32618         function parseDefaultClause() {
32619             var pos = getNodePos();
32620             parseExpected(87 /* DefaultKeyword */);
32621             parseExpected(58 /* ColonToken */);
32622             var statements = parseList(3 /* SwitchClauseStatements */, parseStatement);
32623             return finishNode(factory.createDefaultClause(statements), pos);
32624         }
32625         function parseCaseOrDefaultClause() {
32626             return token() === 81 /* CaseKeyword */ ? parseCaseClause() : parseDefaultClause();
32627         }
32628         function parseCaseBlock() {
32629             var pos = getNodePos();
32630             parseExpected(18 /* OpenBraceToken */);
32631             var clauses = parseList(2 /* SwitchClauses */, parseCaseOrDefaultClause);
32632             parseExpected(19 /* CloseBraceToken */);
32633             return finishNode(factory.createCaseBlock(clauses), pos);
32634         }
32635         function parseSwitchStatement() {
32636             var pos = getNodePos();
32637             parseExpected(106 /* SwitchKeyword */);
32638             parseExpected(20 /* OpenParenToken */);
32639             var expression = allowInAnd(parseExpression);
32640             parseExpected(21 /* CloseParenToken */);
32641             var caseBlock = parseCaseBlock();
32642             return finishNode(factory.createSwitchStatement(expression, caseBlock), pos);
32643         }
32644         function parseThrowStatement() {
32645             // ThrowStatement[Yield] :
32646             //      throw [no LineTerminator here]Expression[In, ?Yield];
32647             var pos = getNodePos();
32648             parseExpected(108 /* ThrowKeyword */);
32649             // Because of automatic semicolon insertion, we need to report error if this
32650             // throw could be terminated with a semicolon.  Note: we can't call 'parseExpression'
32651             // directly as that might consume an expression on the following line.
32652             // Instead, we create a "missing" identifier, but don't report an error. The actual error
32653             // will be reported in the grammar walker.
32654             var expression = scanner.hasPrecedingLineBreak() ? undefined : allowInAnd(parseExpression);
32655             if (expression === undefined) {
32656                 identifierCount++;
32657                 expression = finishNode(factory.createIdentifier(""), getNodePos());
32658             }
32659             parseSemicolon();
32660             return finishNode(factory.createThrowStatement(expression), pos);
32661         }
32662         // TODO: Review for error recovery
32663         function parseTryStatement() {
32664             var pos = getNodePos();
32665             parseExpected(110 /* TryKeyword */);
32666             var tryBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
32667             var catchClause = token() === 82 /* CatchKeyword */ ? parseCatchClause() : undefined;
32668             // If we don't have a catch clause, then we must have a finally clause.  Try to parse
32669             // one out no matter what.
32670             var finallyBlock;
32671             if (!catchClause || token() === 95 /* FinallyKeyword */) {
32672                 parseExpected(95 /* FinallyKeyword */);
32673                 finallyBlock = parseBlock(/*ignoreMissingOpenBrace*/ false);
32674             }
32675             return finishNode(factory.createTryStatement(tryBlock, catchClause, finallyBlock), pos);
32676         }
32677         function parseCatchClause() {
32678             var pos = getNodePos();
32679             parseExpected(82 /* CatchKeyword */);
32680             var variableDeclaration;
32681             if (parseOptional(20 /* OpenParenToken */)) {
32682                 variableDeclaration = parseVariableDeclaration();
32683                 parseExpected(21 /* CloseParenToken */);
32684             }
32685             else {
32686                 // Keep shape of node to avoid degrading performance.
32687                 variableDeclaration = undefined;
32688             }
32689             var block = parseBlock(/*ignoreMissingOpenBrace*/ false);
32690             return finishNode(factory.createCatchClause(variableDeclaration, block), pos);
32691         }
32692         function parseDebuggerStatement() {
32693             var pos = getNodePos();
32694             parseExpected(86 /* DebuggerKeyword */);
32695             parseSemicolon();
32696             return finishNode(factory.createDebuggerStatement(), pos);
32697         }
32698         function parseExpressionOrLabeledStatement() {
32699             // Avoiding having to do the lookahead for a labeled statement by just trying to parse
32700             // out an expression, seeing if it is identifier and then seeing if it is followed by
32701             // a colon.
32702             var pos = getNodePos();
32703             var hasJSDoc = hasPrecedingJSDocComment();
32704             var node;
32705             var hasParen = token() === 20 /* OpenParenToken */;
32706             var expression = allowInAnd(parseExpression);
32707             if (ts.isIdentifier(expression) && parseOptional(58 /* ColonToken */)) {
32708                 node = factory.createLabeledStatement(expression, parseStatement());
32709             }
32710             else {
32711                 parseSemicolon();
32712                 node = factory.createExpressionStatement(expression);
32713                 if (hasParen) {
32714                     // do not parse the same jsdoc twice
32715                     hasJSDoc = false;
32716                 }
32717             }
32718             return withJSDoc(finishNode(node, pos), hasJSDoc);
32719         }
32720         function nextTokenIsIdentifierOrKeywordOnSameLine() {
32721             nextToken();
32722             return ts.tokenIsIdentifierOrKeyword(token()) && !scanner.hasPrecedingLineBreak();
32723         }
32724         function nextTokenIsClassKeywordOnSameLine() {
32725             nextToken();
32726             return token() === 83 /* ClassKeyword */ && !scanner.hasPrecedingLineBreak();
32727         }
32728         function nextTokenIsFunctionKeywordOnSameLine() {
32729             nextToken();
32730             return token() === 97 /* FunctionKeyword */ && !scanner.hasPrecedingLineBreak();
32731         }
32732         function nextTokenIsIdentifierOrKeywordOrLiteralOnSameLine() {
32733             nextToken();
32734             return (ts.tokenIsIdentifierOrKeyword(token()) || token() === 8 /* NumericLiteral */ || token() === 9 /* BigIntLiteral */ || token() === 10 /* StringLiteral */) && !scanner.hasPrecedingLineBreak();
32735         }
32736         function isDeclaration() {
32737             while (true) {
32738                 switch (token()) {
32739                     case 112 /* VarKeyword */:
32740                     case 118 /* LetKeyword */:
32741                     case 84 /* ConstKeyword */:
32742                     case 97 /* FunctionKeyword */:
32743                     case 83 /* ClassKeyword */:
32744                     case 91 /* EnumKeyword */:
32745                         return true;
32746                     // 'declare', 'module', 'namespace', 'interface'* and 'type' are all legal JavaScript identifiers;
32747                     // however, an identifier cannot be followed by another identifier on the same line. This is what we
32748                     // count on to parse out the respective declarations. For instance, we exploit this to say that
32749                     //
32750                     //    namespace n
32751                     //
32752                     // can be none other than the beginning of a namespace declaration, but need to respect that JavaScript sees
32753                     //
32754                     //    namespace
32755                     //    n
32756                     //
32757                     // as the identifier 'namespace' on one line followed by the identifier 'n' on another.
32758                     // We need to look one token ahead to see if it permissible to try parsing a declaration.
32759                     //
32760                     // *Note*: 'interface' is actually a strict mode reserved word. So while
32761                     //
32762                     //   "use strict"
32763                     //   interface
32764                     //   I {}
32765                     //
32766                     // could be legal, it would add complexity for very little gain.
32767                     case 117 /* InterfaceKeyword */:
32768                     case 149 /* TypeKeyword */:
32769                         return nextTokenIsIdentifierOnSameLine();
32770                     case 139 /* ModuleKeyword */:
32771                     case 140 /* NamespaceKeyword */:
32772                         return nextTokenIsIdentifierOrStringLiteralOnSameLine();
32773                     case 125 /* AbstractKeyword */:
32774                     case 129 /* AsyncKeyword */:
32775                     case 133 /* DeclareKeyword */:
32776                     case 120 /* PrivateKeyword */:
32777                     case 121 /* ProtectedKeyword */:
32778                     case 122 /* PublicKeyword */:
32779                     case 142 /* ReadonlyKeyword */:
32780                         nextToken();
32781                         // ASI takes effect for this modifier.
32782                         if (scanner.hasPrecedingLineBreak()) {
32783                             return false;
32784                         }
32785                         continue;
32786                     case 154 /* GlobalKeyword */:
32787                         nextToken();
32788                         return token() === 18 /* OpenBraceToken */ || token() === 78 /* Identifier */ || token() === 92 /* ExportKeyword */;
32789                     case 99 /* ImportKeyword */:
32790                         nextToken();
32791                         return token() === 10 /* StringLiteral */ || token() === 41 /* AsteriskToken */ ||
32792                             token() === 18 /* OpenBraceToken */ || ts.tokenIsIdentifierOrKeyword(token());
32793                     case 92 /* ExportKeyword */:
32794                         var currentToken_1 = nextToken();
32795                         if (currentToken_1 === 149 /* TypeKeyword */) {
32796                             currentToken_1 = lookAhead(nextToken);
32797                         }
32798                         if (currentToken_1 === 62 /* EqualsToken */ || currentToken_1 === 41 /* AsteriskToken */ ||
32799                             currentToken_1 === 18 /* OpenBraceToken */ || currentToken_1 === 87 /* DefaultKeyword */ ||
32800                             currentToken_1 === 126 /* AsKeyword */) {
32801                             return true;
32802                         }
32803                         continue;
32804                     case 123 /* StaticKeyword */:
32805                         nextToken();
32806                         continue;
32807                     default:
32808                         return false;
32809                 }
32810             }
32811         }
32812         function isStartOfDeclaration() {
32813             return lookAhead(isDeclaration);
32814         }
32815         function isStartOfStatement() {
32816             switch (token()) {
32817                 case 59 /* AtToken */:
32818                 case 26 /* SemicolonToken */:
32819                 case 18 /* OpenBraceToken */:
32820                 case 112 /* VarKeyword */:
32821                 case 118 /* LetKeyword */:
32822                 case 97 /* FunctionKeyword */:
32823                 case 83 /* ClassKeyword */:
32824                 case 91 /* EnumKeyword */:
32825                 case 98 /* IfKeyword */:
32826                 case 89 /* DoKeyword */:
32827                 case 114 /* WhileKeyword */:
32828                 case 96 /* ForKeyword */:
32829                 case 85 /* ContinueKeyword */:
32830                 case 80 /* BreakKeyword */:
32831                 case 104 /* ReturnKeyword */:
32832                 case 115 /* WithKeyword */:
32833                 case 106 /* SwitchKeyword */:
32834                 case 108 /* ThrowKeyword */:
32835                 case 110 /* TryKeyword */:
32836                 case 86 /* DebuggerKeyword */:
32837                 // 'catch' and 'finally' do not actually indicate that the code is part of a statement,
32838                 // however, we say they are here so that we may gracefully parse them and error later.
32839                 // falls through
32840                 case 82 /* CatchKeyword */:
32841                 case 95 /* FinallyKeyword */:
32842                     return true;
32843                 case 99 /* ImportKeyword */:
32844                     return isStartOfDeclaration() || lookAhead(nextTokenIsOpenParenOrLessThanOrDot);
32845                 case 84 /* ConstKeyword */:
32846                 case 92 /* ExportKeyword */:
32847                     return isStartOfDeclaration();
32848                 case 129 /* AsyncKeyword */:
32849                 case 133 /* DeclareKeyword */:
32850                 case 117 /* InterfaceKeyword */:
32851                 case 139 /* ModuleKeyword */:
32852                 case 140 /* NamespaceKeyword */:
32853                 case 149 /* TypeKeyword */:
32854                 case 154 /* GlobalKeyword */:
32855                     // When these don't start a declaration, they're an identifier in an expression statement
32856                     return true;
32857                 case 122 /* PublicKeyword */:
32858                 case 120 /* PrivateKeyword */:
32859                 case 121 /* ProtectedKeyword */:
32860                 case 123 /* StaticKeyword */:
32861                 case 142 /* ReadonlyKeyword */:
32862                     // When these don't start a declaration, they may be the start of a class member if an identifier
32863                     // immediately follows. Otherwise they're an identifier in an expression statement.
32864                     return isStartOfDeclaration() || !lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine);
32865                 default:
32866                     return isStartOfExpression();
32867             }
32868         }
32869         function nextTokenIsIdentifierOrStartOfDestructuring() {
32870             nextToken();
32871             return isIdentifier() || token() === 18 /* OpenBraceToken */ || token() === 22 /* OpenBracketToken */;
32872         }
32873         function isLetDeclaration() {
32874             // In ES6 'let' always starts a lexical declaration if followed by an identifier or {
32875             // or [.
32876             return lookAhead(nextTokenIsIdentifierOrStartOfDestructuring);
32877         }
32878         function parseStatement() {
32879             switch (token()) {
32880                 case 26 /* SemicolonToken */:
32881                     return parseEmptyStatement();
32882                 case 18 /* OpenBraceToken */:
32883                     return parseBlock(/*ignoreMissingOpenBrace*/ false);
32884                 case 112 /* VarKeyword */:
32885                     return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32886                 case 118 /* LetKeyword */:
32887                     if (isLetDeclaration()) {
32888                         return parseVariableStatement(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32889                     }
32890                     break;
32891                 case 97 /* FunctionKeyword */:
32892                     return parseFunctionDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32893                 case 83 /* ClassKeyword */:
32894                     return parseClassDeclaration(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined);
32895                 case 98 /* IfKeyword */:
32896                     return parseIfStatement();
32897                 case 89 /* DoKeyword */:
32898                     return parseDoStatement();
32899                 case 114 /* WhileKeyword */:
32900                     return parseWhileStatement();
32901                 case 96 /* ForKeyword */:
32902                     return parseForOrForInOrForOfStatement();
32903                 case 85 /* ContinueKeyword */:
32904                     return parseBreakOrContinueStatement(240 /* ContinueStatement */);
32905                 case 80 /* BreakKeyword */:
32906                     return parseBreakOrContinueStatement(241 /* BreakStatement */);
32907                 case 104 /* ReturnKeyword */:
32908                     return parseReturnStatement();
32909                 case 115 /* WithKeyword */:
32910                     return parseWithStatement();
32911                 case 106 /* SwitchKeyword */:
32912                     return parseSwitchStatement();
32913                 case 108 /* ThrowKeyword */:
32914                     return parseThrowStatement();
32915                 case 110 /* TryKeyword */:
32916                 // Include 'catch' and 'finally' for error recovery.
32917                 // falls through
32918                 case 82 /* CatchKeyword */:
32919                 case 95 /* FinallyKeyword */:
32920                     return parseTryStatement();
32921                 case 86 /* DebuggerKeyword */:
32922                     return parseDebuggerStatement();
32923                 case 59 /* AtToken */:
32924                     return parseDeclaration();
32925                 case 129 /* AsyncKeyword */:
32926                 case 117 /* InterfaceKeyword */:
32927                 case 149 /* TypeKeyword */:
32928                 case 139 /* ModuleKeyword */:
32929                 case 140 /* NamespaceKeyword */:
32930                 case 133 /* DeclareKeyword */:
32931                 case 84 /* ConstKeyword */:
32932                 case 91 /* EnumKeyword */:
32933                 case 92 /* ExportKeyword */:
32934                 case 99 /* ImportKeyword */:
32935                 case 120 /* PrivateKeyword */:
32936                 case 121 /* ProtectedKeyword */:
32937                 case 122 /* PublicKeyword */:
32938                 case 125 /* AbstractKeyword */:
32939                 case 123 /* StaticKeyword */:
32940                 case 142 /* ReadonlyKeyword */:
32941                 case 154 /* GlobalKeyword */:
32942                     if (isStartOfDeclaration()) {
32943                         return parseDeclaration();
32944                     }
32945                     break;
32946             }
32947             return parseExpressionOrLabeledStatement();
32948         }
32949         function isDeclareModifier(modifier) {
32950             return modifier.kind === 133 /* DeclareKeyword */;
32951         }
32952         function parseDeclaration() {
32953             // TODO: Can we hold onto the parsed decorators/modifiers and advance the scanner
32954             //       if we can't reuse the declaration, so that we don't do this work twice?
32955             //
32956             // `parseListElement` attempted to get the reused node at this position,
32957             // but the ambient context flag was not yet set, so the node appeared
32958             // not reusable in that context.
32959             var isAmbient = ts.some(lookAhead(function () { return (parseDecorators(), parseModifiers()); }), isDeclareModifier);
32960             if (isAmbient) {
32961                 var node = tryReuseAmbientDeclaration();
32962                 if (node) {
32963                     return node;
32964                 }
32965             }
32966             var pos = getNodePos();
32967             var hasJSDoc = hasPrecedingJSDocComment();
32968             var decorators = parseDecorators();
32969             var modifiers = parseModifiers();
32970             if (isAmbient) {
32971                 for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
32972                     var m = _a[_i];
32973                     m.flags |= 8388608 /* Ambient */;
32974                 }
32975                 return doInsideOfContext(8388608 /* Ambient */, function () { return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers); });
32976             }
32977             else {
32978                 return parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers);
32979             }
32980         }
32981         function tryReuseAmbientDeclaration() {
32982             return doInsideOfContext(8388608 /* Ambient */, function () {
32983                 var node = currentNode(parsingContext);
32984                 if (node) {
32985                     return consumeNode(node);
32986                 }
32987             });
32988         }
32989         function parseDeclarationWorker(pos, hasJSDoc, decorators, modifiers) {
32990             switch (token()) {
32991                 case 112 /* VarKeyword */:
32992                 case 118 /* LetKeyword */:
32993                 case 84 /* ConstKeyword */:
32994                     return parseVariableStatement(pos, hasJSDoc, decorators, modifiers);
32995                 case 97 /* FunctionKeyword */:
32996                     return parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers);
32997                 case 83 /* ClassKeyword */:
32998                     return parseClassDeclaration(pos, hasJSDoc, decorators, modifiers);
32999                 case 117 /* InterfaceKeyword */:
33000                     return parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers);
33001                 case 149 /* TypeKeyword */:
33002                     return parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers);
33003                 case 91 /* EnumKeyword */:
33004                     return parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers);
33005                 case 154 /* GlobalKeyword */:
33006                 case 139 /* ModuleKeyword */:
33007                 case 140 /* NamespaceKeyword */:
33008                     return parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
33009                 case 99 /* ImportKeyword */:
33010                     return parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers);
33011                 case 92 /* ExportKeyword */:
33012                     nextToken();
33013                     switch (token()) {
33014                         case 87 /* DefaultKeyword */:
33015                         case 62 /* EqualsToken */:
33016                             return parseExportAssignment(pos, hasJSDoc, decorators, modifiers);
33017                         case 126 /* AsKeyword */:
33018                             return parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers);
33019                         default:
33020                             return parseExportDeclaration(pos, hasJSDoc, decorators, modifiers);
33021                     }
33022                 default:
33023                     if (decorators || modifiers) {
33024                         // We reached this point because we encountered decorators and/or modifiers and assumed a declaration
33025                         // would follow. For recovery and error reporting purposes, return an incomplete declaration.
33026                         var missing = createMissingNode(271 /* MissingDeclaration */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
33027                         ts.setTextRangePos(missing, pos);
33028                         missing.decorators = decorators;
33029                         missing.modifiers = modifiers;
33030                         return missing;
33031                     }
33032                     return undefined; // TODO: GH#18217
33033             }
33034         }
33035         function nextTokenIsIdentifierOrStringLiteralOnSameLine() {
33036             nextToken();
33037             return !scanner.hasPrecedingLineBreak() && (isIdentifier() || token() === 10 /* StringLiteral */);
33038         }
33039         function parseFunctionBlockOrSemicolon(flags, diagnosticMessage) {
33040             if (token() !== 18 /* OpenBraceToken */ && canParseSemicolon()) {
33041                 parseSemicolon();
33042                 return;
33043             }
33044             return parseFunctionBlock(flags, diagnosticMessage);
33045         }
33046         // DECLARATIONS
33047         function parseArrayBindingElement() {
33048             var pos = getNodePos();
33049             if (token() === 27 /* CommaToken */) {
33050                 return finishNode(factory.createOmittedExpression(), pos);
33051             }
33052             var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
33053             var name = parseIdentifierOrPattern();
33054             var initializer = parseInitializer();
33055             return finishNode(factory.createBindingElement(dotDotDotToken, /*propertyName*/ undefined, name, initializer), pos);
33056         }
33057         function parseObjectBindingElement() {
33058             var pos = getNodePos();
33059             var dotDotDotToken = parseOptionalToken(25 /* DotDotDotToken */);
33060             var tokenIsIdentifier = isBindingIdentifier();
33061             var propertyName = parsePropertyName();
33062             var name;
33063             if (tokenIsIdentifier && token() !== 58 /* ColonToken */) {
33064                 name = propertyName;
33065                 propertyName = undefined;
33066             }
33067             else {
33068                 parseExpected(58 /* ColonToken */);
33069                 name = parseIdentifierOrPattern();
33070             }
33071             var initializer = parseInitializer();
33072             return finishNode(factory.createBindingElement(dotDotDotToken, propertyName, name, initializer), pos);
33073         }
33074         function parseObjectBindingPattern() {
33075             var pos = getNodePos();
33076             parseExpected(18 /* OpenBraceToken */);
33077             var elements = parseDelimitedList(9 /* ObjectBindingElements */, parseObjectBindingElement);
33078             parseExpected(19 /* CloseBraceToken */);
33079             return finishNode(factory.createObjectBindingPattern(elements), pos);
33080         }
33081         function parseArrayBindingPattern() {
33082             var pos = getNodePos();
33083             parseExpected(22 /* OpenBracketToken */);
33084             var elements = parseDelimitedList(10 /* ArrayBindingElements */, parseArrayBindingElement);
33085             parseExpected(23 /* CloseBracketToken */);
33086             return finishNode(factory.createArrayBindingPattern(elements), pos);
33087         }
33088         function isBindingIdentifierOrPrivateIdentifierOrPattern() {
33089             return token() === 18 /* OpenBraceToken */
33090                 || token() === 22 /* OpenBracketToken */
33091                 || token() === 79 /* PrivateIdentifier */
33092                 || isBindingIdentifier();
33093         }
33094         function parseIdentifierOrPattern(privateIdentifierDiagnosticMessage) {
33095             if (token() === 22 /* OpenBracketToken */) {
33096                 return parseArrayBindingPattern();
33097             }
33098             if (token() === 18 /* OpenBraceToken */) {
33099                 return parseObjectBindingPattern();
33100             }
33101             return parseBindingIdentifier(privateIdentifierDiagnosticMessage);
33102         }
33103         function parseVariableDeclarationAllowExclamation() {
33104             return parseVariableDeclaration(/*allowExclamation*/ true);
33105         }
33106         function parseVariableDeclaration(allowExclamation) {
33107             var pos = getNodePos();
33108             var name = parseIdentifierOrPattern(ts.Diagnostics.Private_identifiers_are_not_allowed_in_variable_declarations);
33109             var exclamationToken;
33110             if (allowExclamation && name.kind === 78 /* Identifier */ &&
33111                 token() === 53 /* ExclamationToken */ && !scanner.hasPrecedingLineBreak()) {
33112                 exclamationToken = parseTokenNode();
33113             }
33114             var type = parseTypeAnnotation();
33115             var initializer = isInOrOfKeyword(token()) ? undefined : parseInitializer();
33116             var node = factory.createVariableDeclaration(name, exclamationToken, type, initializer);
33117             return finishNode(node, pos);
33118         }
33119         function parseVariableDeclarationList(inForStatementInitializer) {
33120             var pos = getNodePos();
33121             var flags = 0;
33122             switch (token()) {
33123                 case 112 /* VarKeyword */:
33124                     break;
33125                 case 118 /* LetKeyword */:
33126                     flags |= 1 /* Let */;
33127                     break;
33128                 case 84 /* ConstKeyword */:
33129                     flags |= 2 /* Const */;
33130                     break;
33131                 default:
33132                     ts.Debug.fail();
33133             }
33134             nextToken();
33135             // The user may have written the following:
33136             //
33137             //    for (let of X) { }
33138             //
33139             // In this case, we want to parse an empty declaration list, and then parse 'of'
33140             // as a keyword. The reason this is not automatic is that 'of' is a valid identifier.
33141             // So we need to look ahead to determine if 'of' should be treated as a keyword in
33142             // this context.
33143             // The checker will then give an error that there is an empty declaration list.
33144             var declarations;
33145             if (token() === 156 /* OfKeyword */ && lookAhead(canFollowContextualOfKeyword)) {
33146                 declarations = createMissingList();
33147             }
33148             else {
33149                 var savedDisallowIn = inDisallowInContext();
33150                 setDisallowInContext(inForStatementInitializer);
33151                 declarations = parseDelimitedList(8 /* VariableDeclarations */, inForStatementInitializer ? parseVariableDeclaration : parseVariableDeclarationAllowExclamation);
33152                 setDisallowInContext(savedDisallowIn);
33153             }
33154             return finishNode(factory.createVariableDeclarationList(declarations, flags), pos);
33155         }
33156         function canFollowContextualOfKeyword() {
33157             return nextTokenIsIdentifier() && nextToken() === 21 /* CloseParenToken */;
33158         }
33159         function parseVariableStatement(pos, hasJSDoc, decorators, modifiers) {
33160             var declarationList = parseVariableDeclarationList(/*inForStatementInitializer*/ false);
33161             parseSemicolon();
33162             var node = factory.createVariableStatement(modifiers, declarationList);
33163             // Decorators are not allowed on a variable statement, so we keep track of them to report them in the grammar checker.
33164             node.decorators = decorators;
33165             return withJSDoc(finishNode(node, pos), hasJSDoc);
33166         }
33167         function parseFunctionDeclaration(pos, hasJSDoc, decorators, modifiers) {
33168             var savedAwaitContext = inAwaitContext();
33169             var modifierFlags = ts.modifiersToFlags(modifiers);
33170             parseExpected(97 /* FunctionKeyword */);
33171             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
33172             // We don't parse the name here in await context, instead we will report a grammar error in the checker.
33173             var name = modifierFlags & 512 /* Default */ ? parseOptionalBindingIdentifier() : parseBindingIdentifier();
33174             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
33175             var isAsync = modifierFlags & 256 /* Async */ ? 2 /* Await */ : 0 /* None */;
33176             var typeParameters = parseTypeParameters();
33177             if (modifierFlags & 1 /* Export */)
33178                 setAwaitContext(/*value*/ true);
33179             var parameters = parseParameters(isGenerator | isAsync);
33180             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33181             var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, ts.Diagnostics.or_expected);
33182             setAwaitContext(savedAwaitContext);
33183             var node = factory.createFunctionDeclaration(decorators, modifiers, asteriskToken, name, typeParameters, parameters, type, body);
33184             return withJSDoc(finishNode(node, pos), hasJSDoc);
33185         }
33186         function parseConstructorName() {
33187             if (token() === 132 /* ConstructorKeyword */) {
33188                 return parseExpected(132 /* ConstructorKeyword */);
33189             }
33190             if (token() === 10 /* StringLiteral */ && lookAhead(nextToken) === 20 /* OpenParenToken */) {
33191                 return tryParse(function () {
33192                     var literalNode = parseLiteralNode();
33193                     return literalNode.text === "constructor" ? literalNode : undefined;
33194                 });
33195             }
33196         }
33197         function tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers) {
33198             return tryParse(function () {
33199                 if (parseConstructorName()) {
33200                     var typeParameters = parseTypeParameters();
33201                     var parameters = parseParameters(0 /* None */);
33202                     var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33203                     var body = parseFunctionBlockOrSemicolon(0 /* None */, ts.Diagnostics.or_expected);
33204                     var node = factory.createConstructorDeclaration(decorators, modifiers, parameters, body);
33205                     // Attach `typeParameters` and `type` if they exist so that we can report them in the grammar checker.
33206                     node.typeParameters = typeParameters;
33207                     node.type = type;
33208                     return withJSDoc(finishNode(node, pos), hasJSDoc);
33209                 }
33210             });
33211         }
33212         function parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, exclamationToken, diagnosticMessage) {
33213             var isGenerator = asteriskToken ? 1 /* Yield */ : 0 /* None */;
33214             var isAsync = ts.some(modifiers, ts.isAsyncModifier) ? 2 /* Await */ : 0 /* None */;
33215             var typeParameters = parseTypeParameters();
33216             var parameters = parseParameters(isGenerator | isAsync);
33217             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33218             var body = parseFunctionBlockOrSemicolon(isGenerator | isAsync, diagnosticMessage);
33219             var node = factory.createMethodDeclaration(decorators, modifiers, asteriskToken, name, questionToken, typeParameters, parameters, type, body);
33220             // An exclamation token on a method is invalid syntax and will be handled by the grammar checker
33221             node.exclamationToken = exclamationToken;
33222             return withJSDoc(finishNode(node, pos), hasJSDoc);
33223         }
33224         function parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken) {
33225             var exclamationToken = !questionToken && !scanner.hasPrecedingLineBreak() ? parseOptionalToken(53 /* ExclamationToken */) : undefined;
33226             var type = parseTypeAnnotation();
33227             var initializer = doOutsideOfContext(8192 /* YieldContext */ | 32768 /* AwaitContext */ | 4096 /* DisallowInContext */, parseInitializer);
33228             parseSemicolon();
33229             var node = factory.createPropertyDeclaration(decorators, modifiers, name, questionToken || exclamationToken, type, initializer);
33230             return withJSDoc(finishNode(node, pos), hasJSDoc);
33231         }
33232         function parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers) {
33233             var asteriskToken = parseOptionalToken(41 /* AsteriskToken */);
33234             var name = parsePropertyName();
33235             // Note: this is not legal as per the grammar.  But we allow it in the parser and
33236             // report an error in the grammar checker.
33237             var questionToken = parseOptionalToken(57 /* QuestionToken */);
33238             if (asteriskToken || token() === 20 /* OpenParenToken */ || token() === 29 /* LessThanToken */) {
33239                 return parseMethodDeclaration(pos, hasJSDoc, decorators, modifiers, asteriskToken, name, questionToken, /*exclamationToken*/ undefined, ts.Diagnostics.or_expected);
33240             }
33241             return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, questionToken);
33242         }
33243         function parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, kind) {
33244             var name = parsePropertyName();
33245             var typeParameters = parseTypeParameters();
33246             var parameters = parseParameters(0 /* None */);
33247             var type = parseReturnType(58 /* ColonToken */, /*isType*/ false);
33248             var body = parseFunctionBlockOrSemicolon(0 /* None */);
33249             var node = kind === 167 /* GetAccessor */
33250                 ? factory.createGetAccessorDeclaration(decorators, modifiers, name, parameters, type, body)
33251                 : factory.createSetAccessorDeclaration(decorators, modifiers, name, parameters, body);
33252             // Keep track of `typeParameters` (for both) and `type` (for setters) if they were parsed those indicate grammar errors
33253             node.typeParameters = typeParameters;
33254             if (type && node.kind === 168 /* SetAccessor */)
33255                 node.type = type;
33256             return withJSDoc(finishNode(node, pos), hasJSDoc);
33257         }
33258         function isClassMemberStart() {
33259             var idToken;
33260             if (token() === 59 /* AtToken */) {
33261                 return true;
33262             }
33263             // Eat up all modifiers, but hold on to the last one in case it is actually an identifier.
33264             while (ts.isModifierKind(token())) {
33265                 idToken = token();
33266                 // If the idToken is a class modifier (protected, private, public, and static), it is
33267                 // certain that we are starting to parse class member. This allows better error recovery
33268                 // Example:
33269                 //      public foo() ...     // true
33270                 //      public @dec blah ... // true; we will then report an error later
33271                 //      export public ...    // true; we will then report an error later
33272                 if (ts.isClassMemberModifier(idToken)) {
33273                     return true;
33274                 }
33275                 nextToken();
33276             }
33277             if (token() === 41 /* AsteriskToken */) {
33278                 return true;
33279             }
33280             // Try to get the first property-like token following all modifiers.
33281             // This can either be an identifier or the 'get' or 'set' keywords.
33282             if (isLiteralPropertyName()) {
33283                 idToken = token();
33284                 nextToken();
33285             }
33286             // Index signatures and computed properties are class members; we can parse.
33287             if (token() === 22 /* OpenBracketToken */) {
33288                 return true;
33289             }
33290             // If we were able to get any potential identifier...
33291             if (idToken !== undefined) {
33292                 // If we have a non-keyword identifier, or if we have an accessor, then it's safe to parse.
33293                 if (!ts.isKeyword(idToken) || idToken === 146 /* SetKeyword */ || idToken === 134 /* GetKeyword */) {
33294                     return true;
33295                 }
33296                 // If it *is* a keyword, but not an accessor, check a little farther along
33297                 // to see if it should actually be parsed as a class member.
33298                 switch (token()) {
33299                     case 20 /* OpenParenToken */: // Method declaration
33300                     case 29 /* LessThanToken */: // Generic Method declaration
33301                     case 53 /* ExclamationToken */: // Non-null assertion on property name
33302                     case 58 /* ColonToken */: // Type Annotation for declaration
33303                     case 62 /* EqualsToken */: // Initializer for declaration
33304                     case 57 /* QuestionToken */: // Not valid, but permitted so that it gets caught later on.
33305                         return true;
33306                     default:
33307                         // Covers
33308                         //  - Semicolons     (declaration termination)
33309                         //  - Closing braces (end-of-class, must be declaration)
33310                         //  - End-of-files   (not valid, but permitted so that it gets caught later on)
33311                         //  - Line-breaks    (enabling *automatic semicolon insertion*)
33312                         return canParseSemicolon();
33313                 }
33314             }
33315             return false;
33316         }
33317         function parseDecoratorExpression() {
33318             if (inAwaitContext() && token() === 130 /* AwaitKeyword */) {
33319                 // `@await` is is disallowed in an [Await] context, but can cause parsing to go off the rails
33320                 // This simply parses the missing identifier and moves on.
33321                 var pos = getNodePos();
33322                 var awaitExpression = parseIdentifier(ts.Diagnostics.Expression_expected);
33323                 nextToken();
33324                 var memberExpression = parseMemberExpressionRest(pos, awaitExpression, /*allowOptionalChain*/ true);
33325                 return parseCallExpressionRest(pos, memberExpression);
33326             }
33327             return parseLeftHandSideExpressionOrHigher();
33328         }
33329         function tryParseDecorator() {
33330             var pos = getNodePos();
33331             if (!parseOptional(59 /* AtToken */)) {
33332                 return undefined;
33333             }
33334             var expression = doInDecoratorContext(parseDecoratorExpression);
33335             return finishNode(factory.createDecorator(expression), pos);
33336         }
33337         function parseDecorators() {
33338             var pos = getNodePos();
33339             var list, decorator;
33340             while (decorator = tryParseDecorator()) {
33341                 list = ts.append(list, decorator);
33342             }
33343             return list && createNodeArray(list, pos);
33344         }
33345         function tryParseModifier(permitInvalidConstAsModifier) {
33346             var pos = getNodePos();
33347             var kind = token();
33348             if (token() === 84 /* ConstKeyword */ && permitInvalidConstAsModifier) {
33349                 // We need to ensure that any subsequent modifiers appear on the same line
33350                 // so that when 'const' is a standalone declaration, we don't issue an error.
33351                 if (!tryParse(nextTokenIsOnSameLineAndCanFollowModifier)) {
33352                     return undefined;
33353                 }
33354             }
33355             else {
33356                 if (!parseAnyContextualModifier()) {
33357                     return undefined;
33358                 }
33359             }
33360             return finishNode(factory.createToken(kind), pos);
33361         }
33362         /*
33363          * There are situations in which a modifier like 'const' will appear unexpectedly, such as on a class member.
33364          * In those situations, if we are entirely sure that 'const' is not valid on its own (such as when ASI takes effect
33365          * and turns it into a standalone declaration), then it is better to parse it and report an error later.
33366          *
33367          * In such situations, 'permitInvalidConstAsModifier' should be set to true.
33368          */
33369         function parseModifiers(permitInvalidConstAsModifier) {
33370             var pos = getNodePos();
33371             var list, modifier;
33372             while (modifier = tryParseModifier(permitInvalidConstAsModifier)) {
33373                 list = ts.append(list, modifier);
33374             }
33375             return list && createNodeArray(list, pos);
33376         }
33377         function parseModifiersForArrowFunction() {
33378             var modifiers;
33379             if (token() === 129 /* AsyncKeyword */) {
33380                 var pos = getNodePos();
33381                 nextToken();
33382                 var modifier = finishNode(factory.createToken(129 /* AsyncKeyword */), pos);
33383                 modifiers = createNodeArray([modifier], pos);
33384             }
33385             return modifiers;
33386         }
33387         function parseClassElement() {
33388             var pos = getNodePos();
33389             if (token() === 26 /* SemicolonToken */) {
33390                 nextToken();
33391                 return finishNode(factory.createSemicolonClassElement(), pos);
33392             }
33393             var hasJSDoc = hasPrecedingJSDocComment();
33394             var decorators = parseDecorators();
33395             var modifiers = parseModifiers(/*permitInvalidConstAsModifier*/ true);
33396             if (parseContextualModifier(134 /* GetKeyword */)) {
33397                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 167 /* GetAccessor */);
33398             }
33399             if (parseContextualModifier(146 /* SetKeyword */)) {
33400                 return parseAccessorDeclaration(pos, hasJSDoc, decorators, modifiers, 168 /* SetAccessor */);
33401             }
33402             if (token() === 132 /* ConstructorKeyword */ || token() === 10 /* StringLiteral */) {
33403                 var constructorDeclaration = tryParseConstructorDeclaration(pos, hasJSDoc, decorators, modifiers);
33404                 if (constructorDeclaration) {
33405                     return constructorDeclaration;
33406                 }
33407             }
33408             if (isIndexSignature()) {
33409                 return parseIndexSignatureDeclaration(pos, hasJSDoc, decorators, modifiers);
33410             }
33411             // It is very important that we check this *after* checking indexers because
33412             // the [ token can start an index signature or a computed property name
33413             if (ts.tokenIsIdentifierOrKeyword(token()) ||
33414                 token() === 10 /* StringLiteral */ ||
33415                 token() === 8 /* NumericLiteral */ ||
33416                 token() === 41 /* AsteriskToken */ ||
33417                 token() === 22 /* OpenBracketToken */) {
33418                 var isAmbient = ts.some(modifiers, isDeclareModifier);
33419                 if (isAmbient) {
33420                     for (var _i = 0, _a = modifiers; _i < _a.length; _i++) {
33421                         var m = _a[_i];
33422                         m.flags |= 8388608 /* Ambient */;
33423                     }
33424                     return doInsideOfContext(8388608 /* Ambient */, function () { return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers); });
33425                 }
33426                 else {
33427                     return parsePropertyOrMethodDeclaration(pos, hasJSDoc, decorators, modifiers);
33428                 }
33429             }
33430             if (decorators || modifiers) {
33431                 // treat this as a property declaration with a missing name.
33432                 var name = createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ true, ts.Diagnostics.Declaration_expected);
33433                 return parsePropertyDeclaration(pos, hasJSDoc, decorators, modifiers, name, /*questionToken*/ undefined);
33434             }
33435             // 'isClassMemberStart' should have hinted not to attempt parsing.
33436             return ts.Debug.fail("Should not have attempted to parse class member declaration.");
33437         }
33438         function parseClassExpression() {
33439             return parseClassDeclarationOrExpression(getNodePos(), hasPrecedingJSDocComment(), /*decorators*/ undefined, /*modifiers*/ undefined, 221 /* ClassExpression */);
33440         }
33441         function parseClassDeclaration(pos, hasJSDoc, decorators, modifiers) {
33442             return parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, 252 /* ClassDeclaration */);
33443         }
33444         function parseClassDeclarationOrExpression(pos, hasJSDoc, decorators, modifiers, kind) {
33445             var savedAwaitContext = inAwaitContext();
33446             parseExpected(83 /* ClassKeyword */);
33447             // We don't parse the name here in await context, instead we will report a grammar error in the checker.
33448             var name = parseNameOfClassDeclarationOrExpression();
33449             var typeParameters = parseTypeParameters();
33450             if (ts.some(modifiers, ts.isExportModifier))
33451                 setAwaitContext(/*value*/ true);
33452             var heritageClauses = parseHeritageClauses();
33453             var members;
33454             if (parseExpected(18 /* OpenBraceToken */)) {
33455                 // ClassTail[Yield,Await] : (Modified) See 14.5
33456                 //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
33457                 members = parseClassMembers();
33458                 parseExpected(19 /* CloseBraceToken */);
33459             }
33460             else {
33461                 members = createMissingList();
33462             }
33463             setAwaitContext(savedAwaitContext);
33464             var node = kind === 252 /* ClassDeclaration */
33465                 ? factory.createClassDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members)
33466                 : factory.createClassExpression(decorators, modifiers, name, typeParameters, heritageClauses, members);
33467             return withJSDoc(finishNode(node, pos), hasJSDoc);
33468         }
33469         function parseNameOfClassDeclarationOrExpression() {
33470             // implements is a future reserved word so
33471             // 'class implements' might mean either
33472             // - class expression with omitted name, 'implements' starts heritage clause
33473             // - class with name 'implements'
33474             // 'isImplementsClause' helps to disambiguate between these two cases
33475             return isBindingIdentifier() && !isImplementsClause()
33476                 ? createIdentifier(isBindingIdentifier())
33477                 : undefined;
33478         }
33479         function isImplementsClause() {
33480             return token() === 116 /* ImplementsKeyword */ && lookAhead(nextTokenIsIdentifierOrKeyword);
33481         }
33482         function parseHeritageClauses() {
33483             // ClassTail[Yield,Await] : (Modified) See 14.5
33484             //      ClassHeritage[?Yield,?Await]opt { ClassBody[?Yield,?Await]opt }
33485             if (isHeritageClause()) {
33486                 return parseList(22 /* HeritageClauses */, parseHeritageClause);
33487             }
33488             return undefined;
33489         }
33490         function parseHeritageClause() {
33491             var pos = getNodePos();
33492             var tok = token();
33493             ts.Debug.assert(tok === 93 /* ExtendsKeyword */ || tok === 116 /* ImplementsKeyword */); // isListElement() should ensure this.
33494             nextToken();
33495             var types = parseDelimitedList(7 /* HeritageClauseElement */, parseExpressionWithTypeArguments);
33496             return finishNode(factory.createHeritageClause(tok, types), pos);
33497         }
33498         function parseExpressionWithTypeArguments() {
33499             var pos = getNodePos();
33500             var expression = parseLeftHandSideExpressionOrHigher();
33501             var typeArguments = tryParseTypeArguments();
33502             return finishNode(factory.createExpressionWithTypeArguments(expression, typeArguments), pos);
33503         }
33504         function tryParseTypeArguments() {
33505             return token() === 29 /* LessThanToken */ ?
33506                 parseBracketedList(20 /* TypeArguments */, parseType, 29 /* LessThanToken */, 31 /* GreaterThanToken */) : undefined;
33507         }
33508         function isHeritageClause() {
33509             return token() === 93 /* ExtendsKeyword */ || token() === 116 /* ImplementsKeyword */;
33510         }
33511         function parseClassMembers() {
33512             return parseList(5 /* ClassMembers */, parseClassElement);
33513         }
33514         function parseInterfaceDeclaration(pos, hasJSDoc, decorators, modifiers) {
33515             parseExpected(117 /* InterfaceKeyword */);
33516             var name = parseIdentifier();
33517             var typeParameters = parseTypeParameters();
33518             var heritageClauses = parseHeritageClauses();
33519             var members = parseObjectTypeMembers();
33520             var node = factory.createInterfaceDeclaration(decorators, modifiers, name, typeParameters, heritageClauses, members);
33521             return withJSDoc(finishNode(node, pos), hasJSDoc);
33522         }
33523         function parseTypeAliasDeclaration(pos, hasJSDoc, decorators, modifiers) {
33524             parseExpected(149 /* TypeKeyword */);
33525             var name = parseIdentifier();
33526             var typeParameters = parseTypeParameters();
33527             parseExpected(62 /* EqualsToken */);
33528             var type = token() === 136 /* IntrinsicKeyword */ && tryParse(parseKeywordAndNoDot) || parseType();
33529             parseSemicolon();
33530             var node = factory.createTypeAliasDeclaration(decorators, modifiers, name, typeParameters, type);
33531             return withJSDoc(finishNode(node, pos), hasJSDoc);
33532         }
33533         // In an ambient declaration, the grammar only allows integer literals as initializers.
33534         // In a non-ambient declaration, the grammar allows uninitialized members only in a
33535         // ConstantEnumMemberSection, which starts at the beginning of an enum declaration
33536         // or any time an integer literal initializer is encountered.
33537         function parseEnumMember() {
33538             var pos = getNodePos();
33539             var hasJSDoc = hasPrecedingJSDocComment();
33540             var name = parsePropertyName();
33541             var initializer = allowInAnd(parseInitializer);
33542             return withJSDoc(finishNode(factory.createEnumMember(name, initializer), pos), hasJSDoc);
33543         }
33544         function parseEnumDeclaration(pos, hasJSDoc, decorators, modifiers) {
33545             parseExpected(91 /* EnumKeyword */);
33546             var name = parseIdentifier();
33547             var members;
33548             if (parseExpected(18 /* OpenBraceToken */)) {
33549                 members = doOutsideOfYieldAndAwaitContext(function () { return parseDelimitedList(6 /* EnumMembers */, parseEnumMember); });
33550                 parseExpected(19 /* CloseBraceToken */);
33551             }
33552             else {
33553                 members = createMissingList();
33554             }
33555             var node = factory.createEnumDeclaration(decorators, modifiers, name, members);
33556             return withJSDoc(finishNode(node, pos), hasJSDoc);
33557         }
33558         function parseModuleBlock() {
33559             var pos = getNodePos();
33560             var statements;
33561             if (parseExpected(18 /* OpenBraceToken */)) {
33562                 statements = parseList(1 /* BlockStatements */, parseStatement);
33563                 parseExpected(19 /* CloseBraceToken */);
33564             }
33565             else {
33566                 statements = createMissingList();
33567             }
33568             return finishNode(factory.createModuleBlock(statements), pos);
33569         }
33570         function parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags) {
33571             // If we are parsing a dotted namespace name, we want to
33572             // propagate the 'Namespace' flag across the names if set.
33573             var namespaceFlag = flags & 16 /* Namespace */;
33574             var name = parseIdentifier();
33575             var body = parseOptional(24 /* DotToken */)
33576                 ? parseModuleOrNamespaceDeclaration(getNodePos(), /*hasJSDoc*/ false, /*decorators*/ undefined, /*modifiers*/ undefined, 4 /* NestedNamespace */ | namespaceFlag)
33577                 : parseModuleBlock();
33578             var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
33579             return withJSDoc(finishNode(node, pos), hasJSDoc);
33580         }
33581         function parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
33582             var flags = 0;
33583             var name;
33584             if (token() === 154 /* GlobalKeyword */) {
33585                 // parse 'global' as name of global scope augmentation
33586                 name = parseIdentifier();
33587                 flags |= 1024 /* GlobalAugmentation */;
33588             }
33589             else {
33590                 name = parseLiteralNode();
33591                 name.text = internIdentifier(name.text);
33592             }
33593             var body;
33594             if (token() === 18 /* OpenBraceToken */) {
33595                 body = parseModuleBlock();
33596             }
33597             else {
33598                 parseSemicolon();
33599             }
33600             var node = factory.createModuleDeclaration(decorators, modifiers, name, body, flags);
33601             return withJSDoc(finishNode(node, pos), hasJSDoc);
33602         }
33603         function parseModuleDeclaration(pos, hasJSDoc, decorators, modifiers) {
33604             var flags = 0;
33605             if (token() === 154 /* GlobalKeyword */) {
33606                 // global augmentation
33607                 return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
33608             }
33609             else if (parseOptional(140 /* NamespaceKeyword */)) {
33610                 flags |= 16 /* Namespace */;
33611             }
33612             else {
33613                 parseExpected(139 /* ModuleKeyword */);
33614                 if (token() === 10 /* StringLiteral */) {
33615                     return parseAmbientExternalModuleDeclaration(pos, hasJSDoc, decorators, modifiers);
33616                 }
33617             }
33618             return parseModuleOrNamespaceDeclaration(pos, hasJSDoc, decorators, modifiers, flags);
33619         }
33620         function isExternalModuleReference() {
33621             return token() === 143 /* RequireKeyword */ &&
33622                 lookAhead(nextTokenIsOpenParen);
33623         }
33624         function nextTokenIsOpenParen() {
33625             return nextToken() === 20 /* OpenParenToken */;
33626         }
33627         function nextTokenIsSlash() {
33628             return nextToken() === 43 /* SlashToken */;
33629         }
33630         function parseNamespaceExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
33631             parseExpected(126 /* AsKeyword */);
33632             parseExpected(140 /* NamespaceKeyword */);
33633             var name = parseIdentifier();
33634             parseSemicolon();
33635             var node = factory.createNamespaceExportDeclaration(name);
33636             // NamespaceExportDeclaration nodes cannot have decorators or modifiers, so we attach them here so we can report them in the grammar checker
33637             node.decorators = decorators;
33638             node.modifiers = modifiers;
33639             return withJSDoc(finishNode(node, pos), hasJSDoc);
33640         }
33641         function parseImportDeclarationOrImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers) {
33642             parseExpected(99 /* ImportKeyword */);
33643             var afterImportPos = scanner.getStartPos();
33644             // We don't parse the identifier here in await context, instead we will report a grammar error in the checker.
33645             var identifier;
33646             if (isIdentifier()) {
33647                 identifier = parseIdentifier();
33648             }
33649             var isTypeOnly = false;
33650             if (token() !== 153 /* FromKeyword */ &&
33651                 (identifier === null || identifier === void 0 ? void 0 : identifier.escapedText) === "type" &&
33652                 (isIdentifier() || tokenAfterImportDefinitelyProducesImportDeclaration())) {
33653                 isTypeOnly = true;
33654                 identifier = isIdentifier() ? parseIdentifier() : undefined;
33655             }
33656             if (identifier && !tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration()) {
33657                 return parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly);
33658             }
33659             // ImportDeclaration:
33660             //  import ImportClause from ModuleSpecifier ;
33661             //  import ModuleSpecifier;
33662             var importClause;
33663             if (identifier || // import id
33664                 token() === 41 /* AsteriskToken */ || // import *
33665                 token() === 18 /* OpenBraceToken */ // import {
33666             ) {
33667                 importClause = parseImportClause(identifier, afterImportPos, isTypeOnly);
33668                 parseExpected(153 /* FromKeyword */);
33669             }
33670             var moduleSpecifier = parseModuleSpecifier();
33671             parseSemicolon();
33672             var node = factory.createImportDeclaration(decorators, modifiers, importClause, moduleSpecifier);
33673             return withJSDoc(finishNode(node, pos), hasJSDoc);
33674         }
33675         function tokenAfterImportDefinitelyProducesImportDeclaration() {
33676             return token() === 41 /* AsteriskToken */ || token() === 18 /* OpenBraceToken */;
33677         }
33678         function tokenAfterImportedIdentifierDefinitelyProducesImportDeclaration() {
33679             // In `import id ___`, the current token decides whether to produce
33680             // an ImportDeclaration or ImportEqualsDeclaration.
33681             return token() === 27 /* CommaToken */ || token() === 153 /* FromKeyword */;
33682         }
33683         function parseImportEqualsDeclaration(pos, hasJSDoc, decorators, modifiers, identifier, isTypeOnly) {
33684             parseExpected(62 /* EqualsToken */);
33685             var moduleReference = parseModuleReference();
33686             parseSemicolon();
33687             var node = factory.createImportEqualsDeclaration(decorators, modifiers, identifier, moduleReference);
33688             var finished = withJSDoc(finishNode(node, pos), hasJSDoc);
33689             if (isTypeOnly) {
33690                 parseErrorAtRange(finished, ts.Diagnostics.Only_ECMAScript_imports_may_use_import_type);
33691             }
33692             return finished;
33693         }
33694         function parseImportClause(identifier, pos, isTypeOnly) {
33695             // ImportClause:
33696             //  ImportedDefaultBinding
33697             //  NameSpaceImport
33698             //  NamedImports
33699             //  ImportedDefaultBinding, NameSpaceImport
33700             //  ImportedDefaultBinding, NamedImports
33701             // If there was no default import or if there is comma token after default import
33702             // parse namespace or named imports
33703             var namedBindings;
33704             if (!identifier ||
33705                 parseOptional(27 /* CommaToken */)) {
33706                 namedBindings = token() === 41 /* AsteriskToken */ ? parseNamespaceImport() : parseNamedImportsOrExports(264 /* NamedImports */);
33707             }
33708             return finishNode(factory.createImportClause(isTypeOnly, identifier, namedBindings), pos);
33709         }
33710         function parseModuleReference() {
33711             return isExternalModuleReference()
33712                 ? parseExternalModuleReference()
33713                 : parseEntityName(/*allowReservedWords*/ false);
33714         }
33715         function parseExternalModuleReference() {
33716             var pos = getNodePos();
33717             parseExpected(143 /* RequireKeyword */);
33718             parseExpected(20 /* OpenParenToken */);
33719             var expression = parseModuleSpecifier();
33720             parseExpected(21 /* CloseParenToken */);
33721             return finishNode(factory.createExternalModuleReference(expression), pos);
33722         }
33723         function parseModuleSpecifier() {
33724             if (token() === 10 /* StringLiteral */) {
33725                 var result = parseLiteralNode();
33726                 result.text = internIdentifier(result.text);
33727                 return result;
33728             }
33729             else {
33730                 // We allow arbitrary expressions here, even though the grammar only allows string
33731                 // literals.  We check to ensure that it is only a string literal later in the grammar
33732                 // check pass.
33733                 return parseExpression();
33734             }
33735         }
33736         function parseNamespaceImport() {
33737             // NameSpaceImport:
33738             //  * as ImportedBinding
33739             var pos = getNodePos();
33740             parseExpected(41 /* AsteriskToken */);
33741             parseExpected(126 /* AsKeyword */);
33742             var name = parseIdentifier();
33743             return finishNode(factory.createNamespaceImport(name), pos);
33744         }
33745         function parseNamedImportsOrExports(kind) {
33746             var pos = getNodePos();
33747             // NamedImports:
33748             //  { }
33749             //  { ImportsList }
33750             //  { ImportsList, }
33751             // ImportsList:
33752             //  ImportSpecifier
33753             //  ImportsList, ImportSpecifier
33754             var node = kind === 264 /* NamedImports */
33755                 ? factory.createNamedImports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseImportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */))
33756                 : factory.createNamedExports(parseBracketedList(23 /* ImportOrExportSpecifiers */, parseExportSpecifier, 18 /* OpenBraceToken */, 19 /* CloseBraceToken */));
33757             return finishNode(node, pos);
33758         }
33759         function parseExportSpecifier() {
33760             return parseImportOrExportSpecifier(270 /* ExportSpecifier */);
33761         }
33762         function parseImportSpecifier() {
33763             return parseImportOrExportSpecifier(265 /* ImportSpecifier */);
33764         }
33765         function parseImportOrExportSpecifier(kind) {
33766             var pos = getNodePos();
33767             // ImportSpecifier:
33768             //   BindingIdentifier
33769             //   IdentifierName as BindingIdentifier
33770             // ExportSpecifier:
33771             //   IdentifierName
33772             //   IdentifierName as IdentifierName
33773             var checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
33774             var checkIdentifierStart = scanner.getTokenPos();
33775             var checkIdentifierEnd = scanner.getTextPos();
33776             var identifierName = parseIdentifierName();
33777             var propertyName;
33778             var name;
33779             if (token() === 126 /* AsKeyword */) {
33780                 propertyName = identifierName;
33781                 parseExpected(126 /* AsKeyword */);
33782                 checkIdentifierIsKeyword = ts.isKeyword(token()) && !isIdentifier();
33783                 checkIdentifierStart = scanner.getTokenPos();
33784                 checkIdentifierEnd = scanner.getTextPos();
33785                 name = parseIdentifierName();
33786             }
33787             else {
33788                 name = identifierName;
33789             }
33790             if (kind === 265 /* ImportSpecifier */ && checkIdentifierIsKeyword) {
33791                 parseErrorAt(checkIdentifierStart, checkIdentifierEnd, ts.Diagnostics.Identifier_expected);
33792             }
33793             var node = kind === 265 /* ImportSpecifier */
33794                 ? factory.createImportSpecifier(propertyName, name)
33795                 : factory.createExportSpecifier(propertyName, name);
33796             return finishNode(node, pos);
33797         }
33798         function parseNamespaceExport(pos) {
33799             return finishNode(factory.createNamespaceExport(parseIdentifierName()), pos);
33800         }
33801         function parseExportDeclaration(pos, hasJSDoc, decorators, modifiers) {
33802             var savedAwaitContext = inAwaitContext();
33803             setAwaitContext(/*value*/ true);
33804             var exportClause;
33805             var moduleSpecifier;
33806             var isTypeOnly = parseOptional(149 /* TypeKeyword */);
33807             var namespaceExportPos = getNodePos();
33808             if (parseOptional(41 /* AsteriskToken */)) {
33809                 if (parseOptional(126 /* AsKeyword */)) {
33810                     exportClause = parseNamespaceExport(namespaceExportPos);
33811                 }
33812                 parseExpected(153 /* FromKeyword */);
33813                 moduleSpecifier = parseModuleSpecifier();
33814             }
33815             else {
33816                 exportClause = parseNamedImportsOrExports(268 /* NamedExports */);
33817                 // It is not uncommon to accidentally omit the 'from' keyword. Additionally, in editing scenarios,
33818                 // the 'from' keyword can be parsed as a named export when the export clause is unterminated (i.e. `export { from "moduleName";`)
33819                 // If we don't have a 'from' keyword, see if we have a string literal such that ASI won't take effect.
33820                 if (token() === 153 /* FromKeyword */ || (token() === 10 /* StringLiteral */ && !scanner.hasPrecedingLineBreak())) {
33821                     parseExpected(153 /* FromKeyword */);
33822                     moduleSpecifier = parseModuleSpecifier();
33823                 }
33824             }
33825             parseSemicolon();
33826             setAwaitContext(savedAwaitContext);
33827             var node = factory.createExportDeclaration(decorators, modifiers, isTypeOnly, exportClause, moduleSpecifier);
33828             return withJSDoc(finishNode(node, pos), hasJSDoc);
33829         }
33830         function parseExportAssignment(pos, hasJSDoc, decorators, modifiers) {
33831             var savedAwaitContext = inAwaitContext();
33832             setAwaitContext(/*value*/ true);
33833             var isExportEquals;
33834             if (parseOptional(62 /* EqualsToken */)) {
33835                 isExportEquals = true;
33836             }
33837             else {
33838                 parseExpected(87 /* DefaultKeyword */);
33839             }
33840             var expression = parseAssignmentExpressionOrHigher();
33841             parseSemicolon();
33842             setAwaitContext(savedAwaitContext);
33843             var node = factory.createExportAssignment(decorators, modifiers, isExportEquals, expression);
33844             return withJSDoc(finishNode(node, pos), hasJSDoc);
33845         }
33846         function setExternalModuleIndicator(sourceFile) {
33847             // Try to use the first top-level import/export when available, then
33848             // fall back to looking for an 'import.meta' somewhere in the tree if necessary.
33849             sourceFile.externalModuleIndicator =
33850                 ts.forEach(sourceFile.statements, isAnExternalModuleIndicatorNode) ||
33851                     getImportMetaIfNecessary(sourceFile);
33852         }
33853         function isAnExternalModuleIndicatorNode(node) {
33854             return hasModifierOfKind(node, 92 /* ExportKeyword */)
33855                 || ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)
33856                 || ts.isImportDeclaration(node)
33857                 || ts.isExportAssignment(node)
33858                 || ts.isExportDeclaration(node) ? node : undefined;
33859         }
33860         function getImportMetaIfNecessary(sourceFile) {
33861             return sourceFile.flags & 2097152 /* PossiblyContainsImportMeta */ ?
33862                 walkTreeForExternalModuleIndicators(sourceFile) :
33863                 undefined;
33864         }
33865         function walkTreeForExternalModuleIndicators(node) {
33866             return isImportMeta(node) ? node : forEachChild(node, walkTreeForExternalModuleIndicators);
33867         }
33868         /** Do not use hasModifier inside the parser; it relies on parent pointers. Use this instead. */
33869         function hasModifierOfKind(node, kind) {
33870             return ts.some(node.modifiers, function (m) { return m.kind === kind; });
33871         }
33872         function isImportMeta(node) {
33873             return ts.isMetaProperty(node) && node.keywordToken === 99 /* ImportKeyword */ && node.name.escapedText === "meta";
33874         }
33875         var ParsingContext;
33876         (function (ParsingContext) {
33877             ParsingContext[ParsingContext["SourceElements"] = 0] = "SourceElements";
33878             ParsingContext[ParsingContext["BlockStatements"] = 1] = "BlockStatements";
33879             ParsingContext[ParsingContext["SwitchClauses"] = 2] = "SwitchClauses";
33880             ParsingContext[ParsingContext["SwitchClauseStatements"] = 3] = "SwitchClauseStatements";
33881             ParsingContext[ParsingContext["TypeMembers"] = 4] = "TypeMembers";
33882             ParsingContext[ParsingContext["ClassMembers"] = 5] = "ClassMembers";
33883             ParsingContext[ParsingContext["EnumMembers"] = 6] = "EnumMembers";
33884             ParsingContext[ParsingContext["HeritageClauseElement"] = 7] = "HeritageClauseElement";
33885             ParsingContext[ParsingContext["VariableDeclarations"] = 8] = "VariableDeclarations";
33886             ParsingContext[ParsingContext["ObjectBindingElements"] = 9] = "ObjectBindingElements";
33887             ParsingContext[ParsingContext["ArrayBindingElements"] = 10] = "ArrayBindingElements";
33888             ParsingContext[ParsingContext["ArgumentExpressions"] = 11] = "ArgumentExpressions";
33889             ParsingContext[ParsingContext["ObjectLiteralMembers"] = 12] = "ObjectLiteralMembers";
33890             ParsingContext[ParsingContext["JsxAttributes"] = 13] = "JsxAttributes";
33891             ParsingContext[ParsingContext["JsxChildren"] = 14] = "JsxChildren";
33892             ParsingContext[ParsingContext["ArrayLiteralMembers"] = 15] = "ArrayLiteralMembers";
33893             ParsingContext[ParsingContext["Parameters"] = 16] = "Parameters";
33894             ParsingContext[ParsingContext["JSDocParameters"] = 17] = "JSDocParameters";
33895             ParsingContext[ParsingContext["RestProperties"] = 18] = "RestProperties";
33896             ParsingContext[ParsingContext["TypeParameters"] = 19] = "TypeParameters";
33897             ParsingContext[ParsingContext["TypeArguments"] = 20] = "TypeArguments";
33898             ParsingContext[ParsingContext["TupleElementTypes"] = 21] = "TupleElementTypes";
33899             ParsingContext[ParsingContext["HeritageClauses"] = 22] = "HeritageClauses";
33900             ParsingContext[ParsingContext["ImportOrExportSpecifiers"] = 23] = "ImportOrExportSpecifiers";
33901             ParsingContext[ParsingContext["Count"] = 24] = "Count"; // Number of parsing contexts
33902         })(ParsingContext || (ParsingContext = {}));
33903         var Tristate;
33904         (function (Tristate) {
33905             Tristate[Tristate["False"] = 0] = "False";
33906             Tristate[Tristate["True"] = 1] = "True";
33907             Tristate[Tristate["Unknown"] = 2] = "Unknown";
33908         })(Tristate || (Tristate = {}));
33909         var JSDocParser;
33910         (function (JSDocParser) {
33911             function parseJSDocTypeExpressionForTests(content, start, length) {
33912                 initializeState("file.js", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
33913                 scanner.setText(content, start, length);
33914                 currentToken = scanner.scan();
33915                 var jsDocTypeExpression = parseJSDocTypeExpression();
33916                 var sourceFile = createSourceFile("file.js", 99 /* Latest */, 1 /* JS */, /*isDeclarationFile*/ false, [], factory.createToken(1 /* EndOfFileToken */), 0 /* None */);
33917                 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
33918                 if (jsDocDiagnostics) {
33919                     sourceFile.jsDocDiagnostics = ts.attachFileToDiagnostics(jsDocDiagnostics, sourceFile);
33920                 }
33921                 clearState();
33922                 return jsDocTypeExpression ? { jsDocTypeExpression: jsDocTypeExpression, diagnostics: diagnostics } : undefined;
33923             }
33924             JSDocParser.parseJSDocTypeExpressionForTests = parseJSDocTypeExpressionForTests;
33925             // Parses out a JSDoc type expression.
33926             function parseJSDocTypeExpression(mayOmitBraces) {
33927                 var pos = getNodePos();
33928                 var hasBrace = (mayOmitBraces ? parseOptional : parseExpected)(18 /* OpenBraceToken */);
33929                 var type = doInsideOfContext(4194304 /* JSDoc */, parseJSDocType);
33930                 if (!mayOmitBraces || hasBrace) {
33931                     parseExpectedJSDoc(19 /* CloseBraceToken */);
33932                 }
33933                 var result = factory.createJSDocTypeExpression(type);
33934                 fixupParentReferences(result);
33935                 return finishNode(result, pos);
33936             }
33937             JSDocParser.parseJSDocTypeExpression = parseJSDocTypeExpression;
33938             function parseJSDocNameReference() {
33939                 var pos = getNodePos();
33940                 var hasBrace = parseOptional(18 /* OpenBraceToken */);
33941                 var entityName = parseEntityName(/* allowReservedWords*/ false);
33942                 if (hasBrace) {
33943                     parseExpectedJSDoc(19 /* CloseBraceToken */);
33944                 }
33945                 var result = factory.createJSDocNameReference(entityName);
33946                 fixupParentReferences(result);
33947                 return finishNode(result, pos);
33948             }
33949             JSDocParser.parseJSDocNameReference = parseJSDocNameReference;
33950             function parseIsolatedJSDocComment(content, start, length) {
33951                 initializeState("", content, 99 /* Latest */, /*_syntaxCursor:*/ undefined, 1 /* JS */);
33952                 var jsDoc = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
33953                 var sourceFile = { languageVariant: 0 /* Standard */, text: content };
33954                 var diagnostics = ts.attachFileToDiagnostics(parseDiagnostics, sourceFile);
33955                 clearState();
33956                 return jsDoc ? { jsDoc: jsDoc, diagnostics: diagnostics } : undefined;
33957             }
33958             JSDocParser.parseIsolatedJSDocComment = parseIsolatedJSDocComment;
33959             function parseJSDocComment(parent, start, length) {
33960                 var saveToken = currentToken;
33961                 var saveParseDiagnosticsLength = parseDiagnostics.length;
33962                 var saveParseErrorBeforeNextFinishedNode = parseErrorBeforeNextFinishedNode;
33963                 var comment = doInsideOfContext(4194304 /* JSDoc */, function () { return parseJSDocCommentWorker(start, length); });
33964                 ts.setParent(comment, parent);
33965                 if (contextFlags & 131072 /* JavaScriptFile */) {
33966                     if (!jsDocDiagnostics) {
33967                         jsDocDiagnostics = [];
33968                     }
33969                     jsDocDiagnostics.push.apply(jsDocDiagnostics, parseDiagnostics);
33970                 }
33971                 currentToken = saveToken;
33972                 parseDiagnostics.length = saveParseDiagnosticsLength;
33973                 parseErrorBeforeNextFinishedNode = saveParseErrorBeforeNextFinishedNode;
33974                 return comment;
33975             }
33976             JSDocParser.parseJSDocComment = parseJSDocComment;
33977             var JSDocState;
33978             (function (JSDocState) {
33979                 JSDocState[JSDocState["BeginningOfLine"] = 0] = "BeginningOfLine";
33980                 JSDocState[JSDocState["SawAsterisk"] = 1] = "SawAsterisk";
33981                 JSDocState[JSDocState["SavingComments"] = 2] = "SavingComments";
33982                 JSDocState[JSDocState["SavingBackticks"] = 3] = "SavingBackticks";
33983             })(JSDocState || (JSDocState = {}));
33984             var PropertyLikeParse;
33985             (function (PropertyLikeParse) {
33986                 PropertyLikeParse[PropertyLikeParse["Property"] = 1] = "Property";
33987                 PropertyLikeParse[PropertyLikeParse["Parameter"] = 2] = "Parameter";
33988                 PropertyLikeParse[PropertyLikeParse["CallbackParameter"] = 4] = "CallbackParameter";
33989             })(PropertyLikeParse || (PropertyLikeParse = {}));
33990             function parseJSDocCommentWorker(start, length) {
33991                 if (start === void 0) { start = 0; }
33992                 var content = sourceText;
33993                 var end = length === undefined ? content.length : start + length;
33994                 length = end - start;
33995                 ts.Debug.assert(start >= 0);
33996                 ts.Debug.assert(start <= end);
33997                 ts.Debug.assert(end <= content.length);
33998                 // Check for /** (JSDoc opening part)
33999                 if (!isJSDocLikeText(content, start)) {
34000                     return undefined;
34001                 }
34002                 var tags;
34003                 var tagsPos;
34004                 var tagsEnd;
34005                 var comments = [];
34006                 // + 3 for leading /**, - 5 in total for /** */
34007                 return scanner.scanRange(start + 3, length - 5, function () {
34008                     // Initially we can parse out a tag.  We also have seen a starting asterisk.
34009                     // This is so that /** * @type */ doesn't parse.
34010                     var state = 1 /* SawAsterisk */;
34011                     var margin;
34012                     // + 4 for leading '/** '
34013                     // + 1 because the last index of \n is always one index before the first character in the line and coincidentally, if there is no \n before start, it is -1, which is also one index before the first character
34014                     var indent = start - (content.lastIndexOf("\n", start) + 1) + 4;
34015                     function pushComment(text) {
34016                         if (!margin) {
34017                             margin = indent;
34018                         }
34019                         comments.push(text);
34020                         indent += text.length;
34021                     }
34022                     nextTokenJSDoc();
34023                     while (parseOptionalJsdoc(5 /* WhitespaceTrivia */))
34024                         ;
34025                     if (parseOptionalJsdoc(4 /* NewLineTrivia */)) {
34026                         state = 0 /* BeginningOfLine */;
34027                         indent = 0;
34028                     }
34029                     loop: while (true) {
34030                         switch (token()) {
34031                             case 59 /* AtToken */:
34032                                 if (state === 0 /* BeginningOfLine */ || state === 1 /* SawAsterisk */) {
34033                                     removeTrailingWhitespace(comments);
34034                                     addTag(parseTag(indent));
34035                                     // NOTE: According to usejsdoc.org, a tag goes to end of line, except the last tag.
34036                                     // Real-world comments may break this rule, so "BeginningOfLine" will not be a real line beginning
34037                                     // for malformed examples like `/** @param {string} x @returns {number} the length */`
34038                                     state = 0 /* BeginningOfLine */;
34039                                     margin = undefined;
34040                                 }
34041                                 else {
34042                                     pushComment(scanner.getTokenText());
34043                                 }
34044                                 break;
34045                             case 4 /* NewLineTrivia */:
34046                                 comments.push(scanner.getTokenText());
34047                                 state = 0 /* BeginningOfLine */;
34048                                 indent = 0;
34049                                 break;
34050                             case 41 /* AsteriskToken */:
34051                                 var asterisk = scanner.getTokenText();
34052                                 if (state === 1 /* SawAsterisk */ || state === 2 /* SavingComments */) {
34053                                     // If we've already seen an asterisk, then we can no longer parse a tag on this line
34054                                     state = 2 /* SavingComments */;
34055                                     pushComment(asterisk);
34056                                 }
34057                                 else {
34058                                     // Ignore the first asterisk on a line
34059                                     state = 1 /* SawAsterisk */;
34060                                     indent += asterisk.length;
34061                                 }
34062                                 break;
34063                             case 5 /* WhitespaceTrivia */:
34064                                 // only collect whitespace if we're already saving comments or have just crossed the comment indent margin
34065                                 var whitespace = scanner.getTokenText();
34066                                 if (state === 2 /* SavingComments */) {
34067                                     comments.push(whitespace);
34068                                 }
34069                                 else if (margin !== undefined && indent + whitespace.length > margin) {
34070                                     comments.push(whitespace.slice(margin - indent));
34071                                 }
34072                                 indent += whitespace.length;
34073                                 break;
34074                             case 1 /* EndOfFileToken */:
34075                                 break loop;
34076                             default:
34077                                 // Anything else is doc comment text. We just save it. Because it
34078                                 // wasn't a tag, we can no longer parse a tag on this line until we hit the next
34079                                 // line break.
34080                                 state = 2 /* SavingComments */;
34081                                 pushComment(scanner.getTokenText());
34082                                 break;
34083                         }
34084                         nextTokenJSDoc();
34085                     }
34086                     removeLeadingNewlines(comments);
34087                     removeTrailingWhitespace(comments);
34088                     return createJSDocComment();
34089                 });
34090                 function removeLeadingNewlines(comments) {
34091                     while (comments.length && (comments[0] === "\n" || comments[0] === "\r")) {
34092                         comments.shift();
34093                     }
34094                 }
34095                 function removeTrailingWhitespace(comments) {
34096                     while (comments.length && comments[comments.length - 1].trim() === "") {
34097                         comments.pop();
34098                     }
34099                 }
34100                 function createJSDocComment() {
34101                     var comment = comments.length ? comments.join("") : undefined;
34102                     var tagsArray = tags && createNodeArray(tags, tagsPos, tagsEnd);
34103                     return finishNode(factory.createJSDocComment(comment, tagsArray), start, end);
34104                 }
34105                 function isNextNonwhitespaceTokenEndOfFile() {
34106                     // We must use infinite lookahead, as there could be any number of newlines :(
34107                     while (true) {
34108                         nextTokenJSDoc();
34109                         if (token() === 1 /* EndOfFileToken */) {
34110                             return true;
34111                         }
34112                         if (!(token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */)) {
34113                             return false;
34114                         }
34115                     }
34116                 }
34117                 function skipWhitespace() {
34118                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34119                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
34120                             return; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
34121                         }
34122                     }
34123                     while (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34124                         nextTokenJSDoc();
34125                     }
34126                 }
34127                 function skipWhitespaceOrAsterisk() {
34128                     if (token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34129                         if (lookAhead(isNextNonwhitespaceTokenEndOfFile)) {
34130                             return ""; // Don't skip whitespace prior to EoF (or end of comment) - that shouldn't be included in any node's range
34131                         }
34132                     }
34133                     var precedingLineBreak = scanner.hasPrecedingLineBreak();
34134                     var seenLineBreak = false;
34135                     var indentText = "";
34136                     while ((precedingLineBreak && token() === 41 /* AsteriskToken */) || token() === 5 /* WhitespaceTrivia */ || token() === 4 /* NewLineTrivia */) {
34137                         indentText += scanner.getTokenText();
34138                         if (token() === 4 /* NewLineTrivia */) {
34139                             precedingLineBreak = true;
34140                             seenLineBreak = true;
34141                             indentText = "";
34142                         }
34143                         else if (token() === 41 /* AsteriskToken */) {
34144                             precedingLineBreak = false;
34145                         }
34146                         nextTokenJSDoc();
34147                     }
34148                     return seenLineBreak ? indentText : "";
34149                 }
34150                 function parseTag(margin) {
34151                     ts.Debug.assert(token() === 59 /* AtToken */);
34152                     var start = scanner.getTokenPos();
34153                     nextTokenJSDoc();
34154                     var tagName = parseJSDocIdentifierName(/*message*/ undefined);
34155                     var indentText = skipWhitespaceOrAsterisk();
34156                     var tag;
34157                     switch (tagName.escapedText) {
34158                         case "author":
34159                             tag = parseAuthorTag(start, tagName, margin, indentText);
34160                             break;
34161                         case "implements":
34162                             tag = parseImplementsTag(start, tagName, margin, indentText);
34163                             break;
34164                         case "augments":
34165                         case "extends":
34166                             tag = parseAugmentsTag(start, tagName, margin, indentText);
34167                             break;
34168                         case "class":
34169                         case "constructor":
34170                             tag = parseSimpleTag(start, factory.createJSDocClassTag, tagName, margin, indentText);
34171                             break;
34172                         case "public":
34173                             tag = parseSimpleTag(start, factory.createJSDocPublicTag, tagName, margin, indentText);
34174                             break;
34175                         case "private":
34176                             tag = parseSimpleTag(start, factory.createJSDocPrivateTag, tagName, margin, indentText);
34177                             break;
34178                         case "protected":
34179                             tag = parseSimpleTag(start, factory.createJSDocProtectedTag, tagName, margin, indentText);
34180                             break;
34181                         case "readonly":
34182                             tag = parseSimpleTag(start, factory.createJSDocReadonlyTag, tagName, margin, indentText);
34183                             break;
34184                         case "deprecated":
34185                             hasDeprecatedTag = true;
34186                             tag = parseSimpleTag(start, factory.createJSDocDeprecatedTag, tagName, margin, indentText);
34187                             break;
34188                         case "this":
34189                             tag = parseThisTag(start, tagName, margin, indentText);
34190                             break;
34191                         case "enum":
34192                             tag = parseEnumTag(start, tagName, margin, indentText);
34193                             break;
34194                         case "arg":
34195                         case "argument":
34196                         case "param":
34197                             return parseParameterOrPropertyTag(start, tagName, 2 /* Parameter */, margin);
34198                         case "return":
34199                         case "returns":
34200                             tag = parseReturnTag(start, tagName, margin, indentText);
34201                             break;
34202                         case "template":
34203                             tag = parseTemplateTag(start, tagName, margin, indentText);
34204                             break;
34205                         case "type":
34206                             tag = parseTypeTag(start, tagName, margin, indentText);
34207                             break;
34208                         case "typedef":
34209                             tag = parseTypedefTag(start, tagName, margin, indentText);
34210                             break;
34211                         case "callback":
34212                             tag = parseCallbackTag(start, tagName, margin, indentText);
34213                             break;
34214                         case "see":
34215                             tag = parseSeeTag(start, tagName, margin, indentText);
34216                             break;
34217                         default:
34218                             tag = parseUnknownTag(start, tagName, margin, indentText);
34219                             break;
34220                     }
34221                     return tag;
34222                 }
34223                 function parseTrailingTagComments(pos, end, margin, indentText) {
34224                     // some tags, like typedef and callback, have already parsed their comments earlier
34225                     if (!indentText) {
34226                         margin += end - pos;
34227                     }
34228                     return parseTagComments(margin, indentText.slice(margin));
34229                 }
34230                 function parseTagComments(indent, initialMargin) {
34231                     var comments = [];
34232                     var state = 0 /* BeginningOfLine */;
34233                     var margin;
34234                     function pushComment(text) {
34235                         if (!margin) {
34236                             margin = indent;
34237                         }
34238                         comments.push(text);
34239                         indent += text.length;
34240                     }
34241                     if (initialMargin !== undefined) {
34242                         // jump straight to saving comments if there is some initial indentation
34243                         if (initialMargin !== "") {
34244                             pushComment(initialMargin);
34245                         }
34246                         state = 1 /* SawAsterisk */;
34247                     }
34248                     var tok = token();
34249                     loop: while (true) {
34250                         switch (tok) {
34251                             case 4 /* NewLineTrivia */:
34252                                 state = 0 /* BeginningOfLine */;
34253                                 // don't use pushComment here because we want to keep the margin unchanged
34254                                 comments.push(scanner.getTokenText());
34255                                 indent = 0;
34256                                 break;
34257                             case 59 /* AtToken */:
34258                                 if (state === 3 /* SavingBackticks */) {
34259                                     comments.push(scanner.getTokenText());
34260                                     break;
34261                                 }
34262                                 scanner.setTextPos(scanner.getTextPos() - 1);
34263                             // falls through
34264                             case 1 /* EndOfFileToken */:
34265                                 // Done
34266                                 break loop;
34267                             case 5 /* WhitespaceTrivia */:
34268                                 if (state === 2 /* SavingComments */ || state === 3 /* SavingBackticks */) {
34269                                     pushComment(scanner.getTokenText());
34270                                 }
34271                                 else {
34272                                     var whitespace = scanner.getTokenText();
34273                                     // if the whitespace crosses the margin, take only the whitespace that passes the margin
34274                                     if (margin !== undefined && indent + whitespace.length > margin) {
34275                                         comments.push(whitespace.slice(margin - indent));
34276                                     }
34277                                     indent += whitespace.length;
34278                                 }
34279                                 break;
34280                             case 18 /* OpenBraceToken */:
34281                                 state = 2 /* SavingComments */;
34282                                 if (lookAhead(function () { return nextTokenJSDoc() === 59 /* AtToken */ && ts.tokenIsIdentifierOrKeyword(nextTokenJSDoc()) && scanner.getTokenText() === "link"; })) {
34283                                     pushComment(scanner.getTokenText());
34284                                     nextTokenJSDoc();
34285                                     pushComment(scanner.getTokenText());
34286                                     nextTokenJSDoc();
34287                                 }
34288                                 pushComment(scanner.getTokenText());
34289                                 break;
34290                             case 61 /* BacktickToken */:
34291                                 if (state === 3 /* SavingBackticks */) {
34292                                     state = 2 /* SavingComments */;
34293                                 }
34294                                 else {
34295                                     state = 3 /* SavingBackticks */;
34296                                 }
34297                                 pushComment(scanner.getTokenText());
34298                                 break;
34299                             case 41 /* AsteriskToken */:
34300                                 if (state === 0 /* BeginningOfLine */) {
34301                                     // leading asterisks start recording on the *next* (non-whitespace) token
34302                                     state = 1 /* SawAsterisk */;
34303                                     indent += 1;
34304                                     break;
34305                                 }
34306                             // record the * as a comment
34307                             // falls through
34308                             default:
34309                                 if (state !== 3 /* SavingBackticks */) {
34310                                     state = 2 /* SavingComments */; // leading identifiers start recording as well
34311                                 }
34312                                 pushComment(scanner.getTokenText());
34313                                 break;
34314                         }
34315                         tok = nextTokenJSDoc();
34316                     }
34317                     removeLeadingNewlines(comments);
34318                     removeTrailingWhitespace(comments);
34319                     return comments.length === 0 ? undefined : comments.join("");
34320                 }
34321                 function parseUnknownTag(start, tagName, indent, indentText) {
34322                     var end = getNodePos();
34323                     return finishNode(factory.createJSDocUnknownTag(tagName, parseTrailingTagComments(start, end, indent, indentText)), start, end);
34324                 }
34325                 function addTag(tag) {
34326                     if (!tag) {
34327                         return;
34328                     }
34329                     if (!tags) {
34330                         tags = [tag];
34331                         tagsPos = tag.pos;
34332                     }
34333                     else {
34334                         tags.push(tag);
34335                     }
34336                     tagsEnd = tag.end;
34337                 }
34338                 function tryParseTypeExpression() {
34339                     skipWhitespaceOrAsterisk();
34340                     return token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
34341                 }
34342                 function parseBracketNameInPropertyAndParamTag() {
34343                     // Looking for something like '[foo]', 'foo', '[foo.bar]' or 'foo.bar'
34344                     var isBracketed = parseOptionalJsdoc(22 /* OpenBracketToken */);
34345                     if (isBracketed) {
34346                         skipWhitespace();
34347                     }
34348                     // a markdown-quoted name: `arg` is not legal jsdoc, but occurs in the wild
34349                     var isBackquoted = parseOptionalJsdoc(61 /* BacktickToken */);
34350                     var name = parseJSDocEntityName();
34351                     if (isBackquoted) {
34352                         parseExpectedTokenJSDoc(61 /* BacktickToken */);
34353                     }
34354                     if (isBracketed) {
34355                         skipWhitespace();
34356                         // May have an optional default, e.g. '[foo = 42]'
34357                         if (parseOptionalToken(62 /* EqualsToken */)) {
34358                             parseExpression();
34359                         }
34360                         parseExpected(23 /* CloseBracketToken */);
34361                     }
34362                     return { name: name, isBracketed: isBracketed };
34363                 }
34364                 function isObjectOrObjectArrayTypeReference(node) {
34365                     switch (node.kind) {
34366                         case 145 /* ObjectKeyword */:
34367                             return true;
34368                         case 178 /* ArrayType */:
34369                             return isObjectOrObjectArrayTypeReference(node.elementType);
34370                         default:
34371                             return ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "Object" && !node.typeArguments;
34372                     }
34373                 }
34374                 function parseParameterOrPropertyTag(start, tagName, target, indent) {
34375                     var typeExpression = tryParseTypeExpression();
34376                     var isNameFirst = !typeExpression;
34377                     skipWhitespaceOrAsterisk();
34378                     var _a = parseBracketNameInPropertyAndParamTag(), name = _a.name, isBracketed = _a.isBracketed;
34379                     skipWhitespace();
34380                     if (isNameFirst) {
34381                         typeExpression = tryParseTypeExpression();
34382                     }
34383                     var comment = parseTagComments(indent + scanner.getStartPos() - start);
34384                     var nestedTypeLiteral = target !== 4 /* CallbackParameter */ && parseNestedTypeLiteral(typeExpression, name, target, indent);
34385                     if (nestedTypeLiteral) {
34386                         typeExpression = nestedTypeLiteral;
34387                         isNameFirst = true;
34388                     }
34389                     var result = target === 1 /* Property */
34390                         ? factory.createJSDocPropertyTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment)
34391                         : factory.createJSDocParameterTag(tagName, name, isBracketed, typeExpression, isNameFirst, comment);
34392                     return finishNode(result, start);
34393                 }
34394                 function parseNestedTypeLiteral(typeExpression, name, target, indent) {
34395                     if (typeExpression && isObjectOrObjectArrayTypeReference(typeExpression.type)) {
34396                         var pos = getNodePos();
34397                         var child = void 0;
34398                         var children = void 0;
34399                         while (child = tryParse(function () { return parseChildParameterOrPropertyTag(target, indent, name); })) {
34400                             if (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) {
34401                                 children = ts.append(children, child);
34402                             }
34403                         }
34404                         if (children) {
34405                             var literal = finishNode(factory.createJSDocTypeLiteral(children, typeExpression.type.kind === 178 /* ArrayType */), pos);
34406                             return finishNode(factory.createJSDocTypeExpression(literal), pos);
34407                         }
34408                     }
34409                 }
34410                 function parseReturnTag(start, tagName, indent, indentText) {
34411                     if (ts.some(tags, ts.isJSDocReturnTag)) {
34412                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
34413                     }
34414                     var typeExpression = tryParseTypeExpression();
34415                     var end = getNodePos();
34416                     return finishNode(factory.createJSDocReturnTag(tagName, typeExpression, parseTrailingTagComments(start, end, indent, indentText)), start, end);
34417                 }
34418                 function parseTypeTag(start, tagName, indent, indentText) {
34419                     if (ts.some(tags, ts.isJSDocTypeTag)) {
34420                         parseErrorAt(tagName.pos, scanner.getTokenPos(), ts.Diagnostics._0_tag_already_specified, tagName.escapedText);
34421                     }
34422                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
34423                     var end = getNodePos();
34424                     var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined;
34425                     return finishNode(factory.createJSDocTypeTag(tagName, typeExpression, comments), start, end);
34426                 }
34427                 function parseSeeTag(start, tagName, indent, indentText) {
34428                     var nameExpression = parseJSDocNameReference();
34429                     var end = getNodePos();
34430                     var comments = indent !== undefined && indentText !== undefined ? parseTrailingTagComments(start, end, indent, indentText) : undefined;
34431                     return finishNode(factory.createJSDocSeeTag(tagName, nameExpression, comments), start, end);
34432                 }
34433                 function parseAuthorTag(start, tagName, indent, indentText) {
34434                     var authorInfoWithEmail = tryParse(function () { return tryParseAuthorNameAndEmail(); });
34435                     if (!authorInfoWithEmail) {
34436                         var end_1 = getNodePos();
34437                         return finishNode(factory.createJSDocAuthorTag(tagName, parseTrailingTagComments(start, end_1, indent, indentText)), start, end_1);
34438                     }
34439                     var comments = authorInfoWithEmail;
34440                     if (lookAhead(function () { return nextToken() !== 4 /* NewLineTrivia */; })) {
34441                         var comment = parseTagComments(indent);
34442                         if (comment) {
34443                             comments += comment;
34444                         }
34445                     }
34446                     return finishNode(factory.createJSDocAuthorTag(tagName, comments), start);
34447                 }
34448                 function tryParseAuthorNameAndEmail() {
34449                     var comments = [];
34450                     var seenLessThan = false;
34451                     var seenGreaterThan = false;
34452                     var token = scanner.getToken();
34453                     loop: while (true) {
34454                         switch (token) {
34455                             case 78 /* Identifier */:
34456                             case 5 /* WhitespaceTrivia */:
34457                             case 24 /* DotToken */:
34458                             case 59 /* AtToken */:
34459                                 comments.push(scanner.getTokenText());
34460                                 break;
34461                             case 29 /* LessThanToken */:
34462                                 if (seenLessThan || seenGreaterThan) {
34463                                     return;
34464                                 }
34465                                 seenLessThan = true;
34466                                 comments.push(scanner.getTokenText());
34467                                 break;
34468                             case 31 /* GreaterThanToken */:
34469                                 if (!seenLessThan || seenGreaterThan) {
34470                                     return;
34471                                 }
34472                                 seenGreaterThan = true;
34473                                 comments.push(scanner.getTokenText());
34474                                 scanner.setTextPos(scanner.getTokenPos() + 1);
34475                                 break loop;
34476                             case 4 /* NewLineTrivia */:
34477                             case 1 /* EndOfFileToken */:
34478                                 break loop;
34479                         }
34480                         token = nextTokenJSDoc();
34481                     }
34482                     if (seenLessThan && seenGreaterThan) {
34483                         return comments.length === 0 ? undefined : comments.join("");
34484                     }
34485                 }
34486                 function parseImplementsTag(start, tagName, margin, indentText) {
34487                     var className = parseExpressionWithTypeArgumentsForAugments();
34488                     var end = getNodePos();
34489                     return finishNode(factory.createJSDocImplementsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34490                 }
34491                 function parseAugmentsTag(start, tagName, margin, indentText) {
34492                     var className = parseExpressionWithTypeArgumentsForAugments();
34493                     var end = getNodePos();
34494                     return finishNode(factory.createJSDocAugmentsTag(tagName, className, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34495                 }
34496                 function parseExpressionWithTypeArgumentsForAugments() {
34497                     var usedBrace = parseOptional(18 /* OpenBraceToken */);
34498                     var pos = getNodePos();
34499                     var expression = parsePropertyAccessEntityNameExpression();
34500                     var typeArguments = tryParseTypeArguments();
34501                     var node = factory.createExpressionWithTypeArguments(expression, typeArguments);
34502                     var res = finishNode(node, pos);
34503                     if (usedBrace) {
34504                         parseExpected(19 /* CloseBraceToken */);
34505                     }
34506                     return res;
34507                 }
34508                 function parsePropertyAccessEntityNameExpression() {
34509                     var pos = getNodePos();
34510                     var node = parseJSDocIdentifierName();
34511                     while (parseOptional(24 /* DotToken */)) {
34512                         var name = parseJSDocIdentifierName();
34513                         node = finishNode(factory.createPropertyAccessExpression(node, name), pos);
34514                     }
34515                     return node;
34516                 }
34517                 function parseSimpleTag(start, createTag, tagName, margin, indentText) {
34518                     var end = getNodePos();
34519                     return finishNode(createTag(tagName, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34520                 }
34521                 function parseThisTag(start, tagName, margin, indentText) {
34522                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
34523                     skipWhitespace();
34524                     var end = getNodePos();
34525                     return finishNode(factory.createJSDocThisTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34526                 }
34527                 function parseEnumTag(start, tagName, margin, indentText) {
34528                     var typeExpression = parseJSDocTypeExpression(/*mayOmitBraces*/ true);
34529                     skipWhitespace();
34530                     var end = getNodePos();
34531                     return finishNode(factory.createJSDocEnumTag(tagName, typeExpression, parseTrailingTagComments(start, end, margin, indentText)), start, end);
34532                 }
34533                 function parseTypedefTag(start, tagName, indent, indentText) {
34534                     var _a;
34535                     var typeExpression = tryParseTypeExpression();
34536                     skipWhitespaceOrAsterisk();
34537                     var fullName = parseJSDocTypeNameWithNamespace();
34538                     skipWhitespace();
34539                     var comment = parseTagComments(indent);
34540                     var end;
34541                     if (!typeExpression || isObjectOrObjectArrayTypeReference(typeExpression.type)) {
34542                         var child = void 0;
34543                         var childTypeTag = void 0;
34544                         var jsDocPropertyTags = void 0;
34545                         var hasChildren = false;
34546                         while (child = tryParse(function () { return parseChildPropertyTag(indent); })) {
34547                             hasChildren = true;
34548                             if (child.kind === 329 /* JSDocTypeTag */) {
34549                                 if (childTypeTag) {
34550                                     parseErrorAtCurrentToken(ts.Diagnostics.A_JSDoc_typedef_comment_may_not_contain_multiple_type_tags);
34551                                     var lastError = ts.lastOrUndefined(parseDiagnostics);
34552                                     if (lastError) {
34553                                         ts.addRelatedInfo(lastError, ts.createDetachedDiagnostic(fileName, 0, 0, ts.Diagnostics.The_tag_was_first_specified_here));
34554                                     }
34555                                     break;
34556                                 }
34557                                 else {
34558                                     childTypeTag = child;
34559                                 }
34560                             }
34561                             else {
34562                                 jsDocPropertyTags = ts.append(jsDocPropertyTags, child);
34563                             }
34564                         }
34565                         if (hasChildren) {
34566                             var isArrayType = typeExpression && typeExpression.type.kind === 178 /* ArrayType */;
34567                             var jsdocTypeLiteral = factory.createJSDocTypeLiteral(jsDocPropertyTags, isArrayType);
34568                             typeExpression = childTypeTag && childTypeTag.typeExpression && !isObjectOrObjectArrayTypeReference(childTypeTag.typeExpression.type) ?
34569                                 childTypeTag.typeExpression :
34570                                 finishNode(jsdocTypeLiteral, start);
34571                             end = typeExpression.end;
34572                         }
34573                     }
34574                     // Only include the characters between the name end and the next token if a comment was actually parsed out - otherwise it's just whitespace
34575                     end = end || comment !== undefined ?
34576                         getNodePos() :
34577                         ((_a = fullName !== null && fullName !== void 0 ? fullName : typeExpression) !== null && _a !== void 0 ? _a : tagName).end;
34578                     if (!comment) {
34579                         comment = parseTrailingTagComments(start, end, indent, indentText);
34580                     }
34581                     var typedefTag = factory.createJSDocTypedefTag(tagName, typeExpression, fullName, comment);
34582                     return finishNode(typedefTag, start, end);
34583                 }
34584                 function parseJSDocTypeNameWithNamespace(nested) {
34585                     var pos = scanner.getTokenPos();
34586                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
34587                         return undefined;
34588                     }
34589                     var typeNameOrNamespaceName = parseJSDocIdentifierName();
34590                     if (parseOptional(24 /* DotToken */)) {
34591                         var body = parseJSDocTypeNameWithNamespace(/*nested*/ true);
34592                         var jsDocNamespaceNode = factory.createModuleDeclaration(
34593                         /*decorators*/ undefined, 
34594                         /*modifiers*/ undefined, typeNameOrNamespaceName, body, nested ? 4 /* NestedNamespace */ : undefined);
34595                         return finishNode(jsDocNamespaceNode, pos);
34596                     }
34597                     if (nested) {
34598                         typeNameOrNamespaceName.isInJSDocNamespace = true;
34599                     }
34600                     return typeNameOrNamespaceName;
34601                 }
34602                 function parseCallbackTagParameters(indent) {
34603                     var pos = getNodePos();
34604                     var child;
34605                     var parameters;
34606                     while (child = tryParse(function () { return parseChildParameterOrPropertyTag(4 /* CallbackParameter */, indent); })) {
34607                         parameters = ts.append(parameters, child);
34608                     }
34609                     return createNodeArray(parameters || [], pos);
34610                 }
34611                 function parseCallbackTag(start, tagName, indent, indentText) {
34612                     var fullName = parseJSDocTypeNameWithNamespace();
34613                     skipWhitespace();
34614                     var comment = parseTagComments(indent);
34615                     var parameters = parseCallbackTagParameters(indent);
34616                     var returnTag = tryParse(function () {
34617                         if (parseOptionalJsdoc(59 /* AtToken */)) {
34618                             var tag = parseTag(indent);
34619                             if (tag && tag.kind === 327 /* JSDocReturnTag */) {
34620                                 return tag;
34621                             }
34622                         }
34623                     });
34624                     var typeExpression = finishNode(factory.createJSDocSignature(/*typeParameters*/ undefined, parameters, returnTag), start);
34625                     var end = getNodePos();
34626                     if (!comment) {
34627                         comment = parseTrailingTagComments(start, end, indent, indentText);
34628                     }
34629                     return finishNode(factory.createJSDocCallbackTag(tagName, typeExpression, fullName, comment), start, end);
34630                 }
34631                 function escapedTextsEqual(a, b) {
34632                     while (!ts.isIdentifier(a) || !ts.isIdentifier(b)) {
34633                         if (!ts.isIdentifier(a) && !ts.isIdentifier(b) && a.right.escapedText === b.right.escapedText) {
34634                             a = a.left;
34635                             b = b.left;
34636                         }
34637                         else {
34638                             return false;
34639                         }
34640                     }
34641                     return a.escapedText === b.escapedText;
34642                 }
34643                 function parseChildPropertyTag(indent) {
34644                     return parseChildParameterOrPropertyTag(1 /* Property */, indent);
34645                 }
34646                 function parseChildParameterOrPropertyTag(target, indent, name) {
34647                     var canParseTag = true;
34648                     var seenAsterisk = false;
34649                     while (true) {
34650                         switch (nextTokenJSDoc()) {
34651                             case 59 /* AtToken */:
34652                                 if (canParseTag) {
34653                                     var child = tryParseChildTag(target, indent);
34654                                     if (child && (child.kind === 326 /* JSDocParameterTag */ || child.kind === 333 /* JSDocPropertyTag */) &&
34655                                         target !== 4 /* CallbackParameter */ &&
34656                                         name && (ts.isIdentifier(child.name) || !escapedTextsEqual(name, child.name.left))) {
34657                                         return false;
34658                                     }
34659                                     return child;
34660                                 }
34661                                 seenAsterisk = false;
34662                                 break;
34663                             case 4 /* NewLineTrivia */:
34664                                 canParseTag = true;
34665                                 seenAsterisk = false;
34666                                 break;
34667                             case 41 /* AsteriskToken */:
34668                                 if (seenAsterisk) {
34669                                     canParseTag = false;
34670                                 }
34671                                 seenAsterisk = true;
34672                                 break;
34673                             case 78 /* Identifier */:
34674                                 canParseTag = false;
34675                                 break;
34676                             case 1 /* EndOfFileToken */:
34677                                 return false;
34678                         }
34679                     }
34680                 }
34681                 function tryParseChildTag(target, indent) {
34682                     ts.Debug.assert(token() === 59 /* AtToken */);
34683                     var start = scanner.getStartPos();
34684                     nextTokenJSDoc();
34685                     var tagName = parseJSDocIdentifierName();
34686                     skipWhitespace();
34687                     var t;
34688                     switch (tagName.escapedText) {
34689                         case "type":
34690                             return target === 1 /* Property */ && parseTypeTag(start, tagName);
34691                         case "prop":
34692                         case "property":
34693                             t = 1 /* Property */;
34694                             break;
34695                         case "arg":
34696                         case "argument":
34697                         case "param":
34698                             t = 2 /* Parameter */ | 4 /* CallbackParameter */;
34699                             break;
34700                         default:
34701                             return false;
34702                     }
34703                     if (!(target & t)) {
34704                         return false;
34705                     }
34706                     return parseParameterOrPropertyTag(start, tagName, target, indent);
34707                 }
34708                 function parseTemplateTagTypeParameter() {
34709                     var typeParameterPos = getNodePos();
34710                     var name = parseJSDocIdentifierName(ts.Diagnostics.Unexpected_token_A_type_parameter_name_was_expected_without_curly_braces);
34711                     return finishNode(factory.createTypeParameterDeclaration(name, /*constraint*/ undefined, /*defaultType*/ undefined), typeParameterPos);
34712                 }
34713                 function parseTemplateTagTypeParameters() {
34714                     var pos = getNodePos();
34715                     var typeParameters = [];
34716                     do {
34717                         skipWhitespace();
34718                         typeParameters.push(parseTemplateTagTypeParameter());
34719                         skipWhitespaceOrAsterisk();
34720                     } while (parseOptionalJsdoc(27 /* CommaToken */));
34721                     return createNodeArray(typeParameters, pos);
34722                 }
34723                 function parseTemplateTag(start, tagName, indent, indentText) {
34724                     // The template tag looks like one of the following:
34725                     //   @template T,U,V
34726                     //   @template {Constraint} T
34727                     //
34728                     // According to the [closure docs](https://github.com/google/closure-compiler/wiki/Generic-Types#multiple-bounded-template-types):
34729                     //   > Multiple bounded generics cannot be declared on the same line. For the sake of clarity, if multiple templates share the same
34730                     //   > type bound they must be declared on separate lines.
34731                     //
34732                     // TODO: Determine whether we should enforce this in the checker.
34733                     // TODO: Consider moving the `constraint` to the first type parameter as we could then remove `getEffectiveConstraintOfTypeParameter`.
34734                     // TODO: Consider only parsing a single type parameter if there is a constraint.
34735                     var constraint = token() === 18 /* OpenBraceToken */ ? parseJSDocTypeExpression() : undefined;
34736                     var typeParameters = parseTemplateTagTypeParameters();
34737                     var end = getNodePos();
34738                     return finishNode(factory.createJSDocTemplateTag(tagName, constraint, typeParameters, parseTrailingTagComments(start, end, indent, indentText)), start, end);
34739                 }
34740                 function parseOptionalJsdoc(t) {
34741                     if (token() === t) {
34742                         nextTokenJSDoc();
34743                         return true;
34744                     }
34745                     return false;
34746                 }
34747                 function parseJSDocEntityName() {
34748                     var entity = parseJSDocIdentifierName();
34749                     if (parseOptional(22 /* OpenBracketToken */)) {
34750                         parseExpected(23 /* CloseBracketToken */);
34751                         // Note that y[] is accepted as an entity name, but the postfix brackets are not saved for checking.
34752                         // Technically usejsdoc.org requires them for specifying a property of a type equivalent to Array<{ x: ...}>
34753                         // but it's not worth it to enforce that restriction.
34754                     }
34755                     while (parseOptional(24 /* DotToken */)) {
34756                         var name = parseJSDocIdentifierName();
34757                         if (parseOptional(22 /* OpenBracketToken */)) {
34758                             parseExpected(23 /* CloseBracketToken */);
34759                         }
34760                         entity = createQualifiedName(entity, name);
34761                     }
34762                     return entity;
34763                 }
34764                 function parseJSDocIdentifierName(message) {
34765                     if (!ts.tokenIsIdentifierOrKeyword(token())) {
34766                         return createMissingNode(78 /* Identifier */, /*reportAtCurrentPosition*/ !message, message || ts.Diagnostics.Identifier_expected);
34767                     }
34768                     identifierCount++;
34769                     var pos = scanner.getTokenPos();
34770                     var end = scanner.getTextPos();
34771                     var originalKeywordKind = token();
34772                     var text = internIdentifier(scanner.getTokenValue());
34773                     var result = finishNode(factory.createIdentifier(text, /*typeArguments*/ undefined, originalKeywordKind), pos, end);
34774                     nextTokenJSDoc();
34775                     return result;
34776                 }
34777             }
34778         })(JSDocParser = Parser.JSDocParser || (Parser.JSDocParser = {}));
34779     })(Parser || (Parser = {}));
34780     var IncrementalParser;
34781     (function (IncrementalParser) {
34782         function updateSourceFile(sourceFile, newText, textChangeRange, aggressiveChecks) {
34783             aggressiveChecks = aggressiveChecks || ts.Debug.shouldAssert(2 /* Aggressive */);
34784             checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks);
34785             if (ts.textChangeRangeIsUnchanged(textChangeRange)) {
34786                 // if the text didn't change, then we can just return our current source file as-is.
34787                 return sourceFile;
34788             }
34789             if (sourceFile.statements.length === 0) {
34790                 // If we don't have any statements in the current source file, then there's no real
34791                 // way to incrementally parse.  So just do a full parse instead.
34792                 return Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, /*syntaxCursor*/ undefined, /*setParentNodes*/ true, sourceFile.scriptKind);
34793             }
34794             // Make sure we're not trying to incrementally update a source file more than once.  Once
34795             // we do an update the original source file is considered unusable from that point onwards.
34796             //
34797             // This is because we do incremental parsing in-place.  i.e. we take nodes from the old
34798             // tree and give them new positions and parents.  From that point on, trusting the old
34799             // tree at all is not possible as far too much of it may violate invariants.
34800             var incrementalSourceFile = sourceFile;
34801             ts.Debug.assert(!incrementalSourceFile.hasBeenIncrementallyParsed);
34802             incrementalSourceFile.hasBeenIncrementallyParsed = true;
34803             Parser.fixupParentReferences(incrementalSourceFile);
34804             var oldText = sourceFile.text;
34805             var syntaxCursor = createSyntaxCursor(sourceFile);
34806             // Make the actual change larger so that we know to reparse anything whose lookahead
34807             // might have intersected the change.
34808             var changeRange = extendToAffectedRange(sourceFile, textChangeRange);
34809             checkChangeRange(sourceFile, newText, changeRange, aggressiveChecks);
34810             // Ensure that extending the affected range only moved the start of the change range
34811             // earlier in the file.
34812             ts.Debug.assert(changeRange.span.start <= textChangeRange.span.start);
34813             ts.Debug.assert(ts.textSpanEnd(changeRange.span) === ts.textSpanEnd(textChangeRange.span));
34814             ts.Debug.assert(ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)) === ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)));
34815             // The is the amount the nodes after the edit range need to be adjusted.  It can be
34816             // positive (if the edit added characters), negative (if the edit deleted characters)
34817             // or zero (if this was a pure overwrite with nothing added/removed).
34818             var delta = ts.textChangeRangeNewSpan(changeRange).length - changeRange.span.length;
34819             // If we added or removed characters during the edit, then we need to go and adjust all
34820             // the nodes after the edit.  Those nodes may move forward (if we inserted chars) or they
34821             // may move backward (if we deleted chars).
34822             //
34823             // Doing this helps us out in two ways.  First, it means that any nodes/tokens we want
34824             // to reuse are already at the appropriate position in the new text.  That way when we
34825             // reuse them, we don't have to figure out if they need to be adjusted.  Second, it makes
34826             // it very easy to determine if we can reuse a node.  If the node's position is at where
34827             // we are in the text, then we can reuse it.  Otherwise we can't.  If the node's position
34828             // is ahead of us, then we'll need to rescan tokens.  If the node's position is behind
34829             // us, then we'll need to skip it or crumble it as appropriate
34830             //
34831             // We will also adjust the positions of nodes that intersect the change range as well.
34832             // By doing this, we ensure that all the positions in the old tree are consistent, not
34833             // just the positions of nodes entirely before/after the change range.  By being
34834             // consistent, we can then easily map from positions to nodes in the old tree easily.
34835             //
34836             // Also, mark any syntax elements that intersect the changed span.  We know, up front,
34837             // that we cannot reuse these elements.
34838             updateTokenPositionsAndMarkElements(incrementalSourceFile, changeRange.span.start, ts.textSpanEnd(changeRange.span), ts.textSpanEnd(ts.textChangeRangeNewSpan(changeRange)), delta, oldText, newText, aggressiveChecks);
34839             // Now that we've set up our internal incremental state just proceed and parse the
34840             // source file in the normal fashion.  When possible the parser will retrieve and
34841             // reuse nodes from the old tree.
34842             //
34843             // Note: passing in 'true' for setNodeParents is very important.  When incrementally
34844             // parsing, we will be reusing nodes from the old tree, and placing it into new
34845             // parents.  If we don't set the parents now, we'll end up with an observably
34846             // inconsistent tree.  Setting the parents on the new tree should be very fast.  We
34847             // will immediately bail out of walking any subtrees when we can see that their parents
34848             // are already correct.
34849             var result = Parser.parseSourceFile(sourceFile.fileName, newText, sourceFile.languageVersion, syntaxCursor, /*setParentNodes*/ true, sourceFile.scriptKind);
34850             result.commentDirectives = getNewCommentDirectives(sourceFile.commentDirectives, result.commentDirectives, changeRange.span.start, ts.textSpanEnd(changeRange.span), delta, oldText, newText, aggressiveChecks);
34851             return result;
34852         }
34853         IncrementalParser.updateSourceFile = updateSourceFile;
34854         function getNewCommentDirectives(oldDirectives, newDirectives, changeStart, changeRangeOldEnd, delta, oldText, newText, aggressiveChecks) {
34855             if (!oldDirectives)
34856                 return newDirectives;
34857             var commentDirectives;
34858             var addedNewlyScannedDirectives = false;
34859             for (var _i = 0, oldDirectives_1 = oldDirectives; _i < oldDirectives_1.length; _i++) {
34860                 var directive = oldDirectives_1[_i];
34861                 var range = directive.range, type = directive.type;
34862                 // Range before the change
34863                 if (range.end < changeStart) {
34864                     commentDirectives = ts.append(commentDirectives, directive);
34865                 }
34866                 else if (range.pos > changeRangeOldEnd) {
34867                     addNewlyScannedDirectives();
34868                     // Node is entirely past the change range.  We need to move both its pos and
34869                     // end, forward or backward appropriately.
34870                     var updatedDirective = {
34871                         range: { pos: range.pos + delta, end: range.end + delta },
34872                         type: type
34873                     };
34874                     commentDirectives = ts.append(commentDirectives, updatedDirective);
34875                     if (aggressiveChecks) {
34876                         ts.Debug.assert(oldText.substring(range.pos, range.end) === newText.substring(updatedDirective.range.pos, updatedDirective.range.end));
34877                     }
34878                 }
34879                 // Ignore ranges that fall in change range
34880             }
34881             addNewlyScannedDirectives();
34882             return commentDirectives;
34883             function addNewlyScannedDirectives() {
34884                 if (addedNewlyScannedDirectives)
34885                     return;
34886                 addedNewlyScannedDirectives = true;
34887                 if (!commentDirectives) {
34888                     commentDirectives = newDirectives;
34889                 }
34890                 else if (newDirectives) {
34891                     commentDirectives.push.apply(commentDirectives, newDirectives);
34892                 }
34893             }
34894         }
34895         function moveElementEntirelyPastChangeRange(element, isArray, delta, oldText, newText, aggressiveChecks) {
34896             if (isArray) {
34897                 visitArray(element);
34898             }
34899             else {
34900                 visitNode(element);
34901             }
34902             return;
34903             function visitNode(node) {
34904                 var text = "";
34905                 if (aggressiveChecks && shouldCheckNode(node)) {
34906                     text = oldText.substring(node.pos, node.end);
34907                 }
34908                 // Ditch any existing LS children we may have created.  This way we can avoid
34909                 // moving them forward.
34910                 if (node._children) {
34911                     node._children = undefined;
34912                 }
34913                 ts.setTextRangePosEnd(node, node.pos + delta, node.end + delta);
34914                 if (aggressiveChecks && shouldCheckNode(node)) {
34915                     ts.Debug.assert(text === newText.substring(node.pos, node.end));
34916                 }
34917                 forEachChild(node, visitNode, visitArray);
34918                 if (ts.hasJSDocNodes(node)) {
34919                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
34920                         var jsDocComment = _a[_i];
34921                         visitNode(jsDocComment);
34922                     }
34923                 }
34924                 checkNodePositions(node, aggressiveChecks);
34925             }
34926             function visitArray(array) {
34927                 array._children = undefined;
34928                 ts.setTextRangePosEnd(array, array.pos + delta, array.end + delta);
34929                 for (var _i = 0, array_8 = array; _i < array_8.length; _i++) {
34930                     var node = array_8[_i];
34931                     visitNode(node);
34932                 }
34933             }
34934         }
34935         function shouldCheckNode(node) {
34936             switch (node.kind) {
34937                 case 10 /* StringLiteral */:
34938                 case 8 /* NumericLiteral */:
34939                 case 78 /* Identifier */:
34940                     return true;
34941             }
34942             return false;
34943         }
34944         function adjustIntersectingElement(element, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta) {
34945             ts.Debug.assert(element.end >= changeStart, "Adjusting an element that was entirely before the change range");
34946             ts.Debug.assert(element.pos <= changeRangeOldEnd, "Adjusting an element that was entirely after the change range");
34947             ts.Debug.assert(element.pos <= element.end);
34948             // We have an element that intersects the change range in some way.  It may have its
34949             // start, or its end (or both) in the changed range.  We want to adjust any part
34950             // that intersects such that the final tree is in a consistent state.  i.e. all
34951             // children have spans within the span of their parent, and all siblings are ordered
34952             // properly.
34953             // We may need to update both the 'pos' and the 'end' of the element.
34954             // If the 'pos' is before the start of the change, then we don't need to touch it.
34955             // If it isn't, then the 'pos' must be inside the change.  How we update it will
34956             // depend if delta is positive or negative. If delta is positive then we have
34957             // something like:
34958             //
34959             //  -------------------AAA-----------------
34960             //  -------------------BBBCCCCCCC-----------------
34961             //
34962             // In this case, we consider any node that started in the change range to still be
34963             // starting at the same position.
34964             //
34965             // however, if the delta is negative, then we instead have something like this:
34966             //
34967             //  -------------------XXXYYYYYYY-----------------
34968             //  -------------------ZZZ-----------------
34969             //
34970             // In this case, any element that started in the 'X' range will keep its position.
34971             // However any element that started after that will have their pos adjusted to be
34972             // at the end of the new range.  i.e. any node that started in the 'Y' range will
34973             // be adjusted to have their start at the end of the 'Z' range.
34974             //
34975             // The element will keep its position if possible.  Or Move backward to the new-end
34976             // if it's in the 'Y' range.
34977             var pos = Math.min(element.pos, changeRangeNewEnd);
34978             // If the 'end' is after the change range, then we always adjust it by the delta
34979             // amount.  However, if the end is in the change range, then how we adjust it
34980             // will depend on if delta is positive or negative.  If delta is positive then we
34981             // have something like:
34982             //
34983             //  -------------------AAA-----------------
34984             //  -------------------BBBCCCCCCC-----------------
34985             //
34986             // In this case, we consider any node that ended inside the change range to keep its
34987             // end position.
34988             //
34989             // however, if the delta is negative, then we instead have something like this:
34990             //
34991             //  -------------------XXXYYYYYYY-----------------
34992             //  -------------------ZZZ-----------------
34993             //
34994             // In this case, any element that ended in the 'X' range will keep its position.
34995             // However any element that ended after that will have their pos adjusted to be
34996             // at the end of the new range.  i.e. any node that ended in the 'Y' range will
34997             // be adjusted to have their end at the end of the 'Z' range.
34998             var end = element.end >= changeRangeOldEnd ?
34999                 // Element ends after the change range.  Always adjust the end pos.
35000                 element.end + delta :
35001                 // Element ends in the change range.  The element will keep its position if
35002                 // possible. Or Move backward to the new-end if it's in the 'Y' range.
35003                 Math.min(element.end, changeRangeNewEnd);
35004             ts.Debug.assert(pos <= end);
35005             if (element.parent) {
35006                 ts.Debug.assertGreaterThanOrEqual(pos, element.parent.pos);
35007                 ts.Debug.assertLessThanOrEqual(end, element.parent.end);
35008             }
35009             ts.setTextRangePosEnd(element, pos, end);
35010         }
35011         function checkNodePositions(node, aggressiveChecks) {
35012             if (aggressiveChecks) {
35013                 var pos_2 = node.pos;
35014                 var visitNode_1 = function (child) {
35015                     ts.Debug.assert(child.pos >= pos_2);
35016                     pos_2 = child.end;
35017                 };
35018                 if (ts.hasJSDocNodes(node)) {
35019                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
35020                         var jsDocComment = _a[_i];
35021                         visitNode_1(jsDocComment);
35022                     }
35023                 }
35024                 forEachChild(node, visitNode_1);
35025                 ts.Debug.assert(pos_2 <= node.end);
35026             }
35027         }
35028         function updateTokenPositionsAndMarkElements(sourceFile, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta, oldText, newText, aggressiveChecks) {
35029             visitNode(sourceFile);
35030             return;
35031             function visitNode(child) {
35032                 ts.Debug.assert(child.pos <= child.end);
35033                 if (child.pos > changeRangeOldEnd) {
35034                     // Node is entirely past the change range.  We need to move both its pos and
35035                     // end, forward or backward appropriately.
35036                     moveElementEntirelyPastChangeRange(child, /*isArray*/ false, delta, oldText, newText, aggressiveChecks);
35037                     return;
35038                 }
35039                 // Check if the element intersects the change range.  If it does, then it is not
35040                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
35041                 // be able to use.
35042                 var fullEnd = child.end;
35043                 if (fullEnd >= changeStart) {
35044                     child.intersectsChange = true;
35045                     child._children = undefined;
35046                     // Adjust the pos or end (or both) of the intersecting element accordingly.
35047                     adjustIntersectingElement(child, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
35048                     forEachChild(child, visitNode, visitArray);
35049                     if (ts.hasJSDocNodes(child)) {
35050                         for (var _i = 0, _a = child.jsDoc; _i < _a.length; _i++) {
35051                             var jsDocComment = _a[_i];
35052                             visitNode(jsDocComment);
35053                         }
35054                     }
35055                     checkNodePositions(child, aggressiveChecks);
35056                     return;
35057                 }
35058                 // Otherwise, the node is entirely before the change range.  No need to do anything with it.
35059                 ts.Debug.assert(fullEnd < changeStart);
35060             }
35061             function visitArray(array) {
35062                 ts.Debug.assert(array.pos <= array.end);
35063                 if (array.pos > changeRangeOldEnd) {
35064                     // Array is entirely after the change range.  We need to move it, and move any of
35065                     // its children.
35066                     moveElementEntirelyPastChangeRange(array, /*isArray*/ true, delta, oldText, newText, aggressiveChecks);
35067                     return;
35068                 }
35069                 // Check if the element intersects the change range.  If it does, then it is not
35070                 // reusable.  Also, we'll need to recurse to see what constituent portions we may
35071                 // be able to use.
35072                 var fullEnd = array.end;
35073                 if (fullEnd >= changeStart) {
35074                     array.intersectsChange = true;
35075                     array._children = undefined;
35076                     // Adjust the pos or end (or both) of the intersecting array accordingly.
35077                     adjustIntersectingElement(array, changeStart, changeRangeOldEnd, changeRangeNewEnd, delta);
35078                     for (var _i = 0, array_9 = array; _i < array_9.length; _i++) {
35079                         var node = array_9[_i];
35080                         visitNode(node);
35081                     }
35082                     return;
35083                 }
35084                 // Otherwise, the array is entirely before the change range.  No need to do anything with it.
35085                 ts.Debug.assert(fullEnd < changeStart);
35086             }
35087         }
35088         function extendToAffectedRange(sourceFile, changeRange) {
35089             // Consider the following code:
35090             //      void foo() { /; }
35091             //
35092             // If the text changes with an insertion of / just before the semicolon then we end up with:
35093             //      void foo() { //; }
35094             //
35095             // If we were to just use the changeRange a is, then we would not rescan the { token
35096             // (as it does not intersect the actual original change range).  Because an edit may
35097             // change the token touching it, we actually need to look back *at least* one token so
35098             // that the prior token sees that change.
35099             var maxLookahead = 1;
35100             var start = changeRange.span.start;
35101             // the first iteration aligns us with the change start. subsequent iteration move us to
35102             // the left by maxLookahead tokens.  We only need to do this as long as we're not at the
35103             // start of the tree.
35104             for (var i = 0; start > 0 && i <= maxLookahead; i++) {
35105                 var nearestNode = findNearestNodeStartingBeforeOrAtPosition(sourceFile, start);
35106                 ts.Debug.assert(nearestNode.pos <= start);
35107                 var position = nearestNode.pos;
35108                 start = Math.max(0, position - 1);
35109             }
35110             var finalSpan = ts.createTextSpanFromBounds(start, ts.textSpanEnd(changeRange.span));
35111             var finalLength = changeRange.newLength + (changeRange.span.start - start);
35112             return ts.createTextChangeRange(finalSpan, finalLength);
35113         }
35114         function findNearestNodeStartingBeforeOrAtPosition(sourceFile, position) {
35115             var bestResult = sourceFile;
35116             var lastNodeEntirelyBeforePosition;
35117             forEachChild(sourceFile, visit);
35118             if (lastNodeEntirelyBeforePosition) {
35119                 var lastChildOfLastEntireNodeBeforePosition = getLastDescendant(lastNodeEntirelyBeforePosition);
35120                 if (lastChildOfLastEntireNodeBeforePosition.pos > bestResult.pos) {
35121                     bestResult = lastChildOfLastEntireNodeBeforePosition;
35122                 }
35123             }
35124             return bestResult;
35125             function getLastDescendant(node) {
35126                 while (true) {
35127                     var lastChild = ts.getLastChild(node);
35128                     if (lastChild) {
35129                         node = lastChild;
35130                     }
35131                     else {
35132                         return node;
35133                     }
35134                 }
35135             }
35136             function visit(child) {
35137                 if (ts.nodeIsMissing(child)) {
35138                     // Missing nodes are effectively invisible to us.  We never even consider them
35139                     // When trying to find the nearest node before us.
35140                     return;
35141                 }
35142                 // If the child intersects this position, then this node is currently the nearest
35143                 // node that starts before the position.
35144                 if (child.pos <= position) {
35145                     if (child.pos >= bestResult.pos) {
35146                         // This node starts before the position, and is closer to the position than
35147                         // the previous best node we found.  It is now the new best node.
35148                         bestResult = child;
35149                     }
35150                     // Now, the node may overlap the position, or it may end entirely before the
35151                     // position.  If it overlaps with the position, then either it, or one of its
35152                     // children must be the nearest node before the position.  So we can just
35153                     // recurse into this child to see if we can find something better.
35154                     if (position < child.end) {
35155                         // The nearest node is either this child, or one of the children inside
35156                         // of it.  We've already marked this child as the best so far.  Recurse
35157                         // in case one of the children is better.
35158                         forEachChild(child, visit);
35159                         // Once we look at the children of this node, then there's no need to
35160                         // continue any further.
35161                         return true;
35162                     }
35163                     else {
35164                         ts.Debug.assert(child.end <= position);
35165                         // The child ends entirely before this position.  Say you have the following
35166                         // (where $ is the position)
35167                         //
35168                         //      <complex expr 1> ? <complex expr 2> $ : <...> <...>
35169                         //
35170                         // We would want to find the nearest preceding node in "complex expr 2".
35171                         // To support that, we keep track of this node, and once we're done searching
35172                         // for a best node, we recurse down this node to see if we can find a good
35173                         // result in it.
35174                         //
35175                         // This approach allows us to quickly skip over nodes that are entirely
35176                         // before the position, while still allowing us to find any nodes in the
35177                         // last one that might be what we want.
35178                         lastNodeEntirelyBeforePosition = child;
35179                     }
35180                 }
35181                 else {
35182                     ts.Debug.assert(child.pos > position);
35183                     // We're now at a node that is entirely past the position we're searching for.
35184                     // This node (and all following nodes) could never contribute to the result,
35185                     // so just skip them by returning 'true' here.
35186                     return true;
35187                 }
35188             }
35189         }
35190         function checkChangeRange(sourceFile, newText, textChangeRange, aggressiveChecks) {
35191             var oldText = sourceFile.text;
35192             if (textChangeRange) {
35193                 ts.Debug.assert((oldText.length - textChangeRange.span.length + textChangeRange.newLength) === newText.length);
35194                 if (aggressiveChecks || ts.Debug.shouldAssert(3 /* VeryAggressive */)) {
35195                     var oldTextPrefix = oldText.substr(0, textChangeRange.span.start);
35196                     var newTextPrefix = newText.substr(0, textChangeRange.span.start);
35197                     ts.Debug.assert(oldTextPrefix === newTextPrefix);
35198                     var oldTextSuffix = oldText.substring(ts.textSpanEnd(textChangeRange.span), oldText.length);
35199                     var newTextSuffix = newText.substring(ts.textSpanEnd(ts.textChangeRangeNewSpan(textChangeRange)), newText.length);
35200                     ts.Debug.assert(oldTextSuffix === newTextSuffix);
35201                 }
35202             }
35203         }
35204         function createSyntaxCursor(sourceFile) {
35205             var currentArray = sourceFile.statements;
35206             var currentArrayIndex = 0;
35207             ts.Debug.assert(currentArrayIndex < currentArray.length);
35208             var current = currentArray[currentArrayIndex];
35209             var lastQueriedPosition = -1 /* Value */;
35210             return {
35211                 currentNode: function (position) {
35212                     // Only compute the current node if the position is different than the last time
35213                     // we were asked.  The parser commonly asks for the node at the same position
35214                     // twice.  Once to know if can read an appropriate list element at a certain point,
35215                     // and then to actually read and consume the node.
35216                     if (position !== lastQueriedPosition) {
35217                         // Much of the time the parser will need the very next node in the array that
35218                         // we just returned a node from.So just simply check for that case and move
35219                         // forward in the array instead of searching for the node again.
35220                         if (current && current.end === position && currentArrayIndex < (currentArray.length - 1)) {
35221                             currentArrayIndex++;
35222                             current = currentArray[currentArrayIndex];
35223                         }
35224                         // If we don't have a node, or the node we have isn't in the right position,
35225                         // then try to find a viable node at the position requested.
35226                         if (!current || current.pos !== position) {
35227                             findHighestListElementThatStartsAtPosition(position);
35228                         }
35229                     }
35230                     // Cache this query so that we don't do any extra work if the parser calls back
35231                     // into us.  Note: this is very common as the parser will make pairs of calls like
35232                     // 'isListElement -> parseListElement'.  If we were unable to find a node when
35233                     // called with 'isListElement', we don't want to redo the work when parseListElement
35234                     // is called immediately after.
35235                     lastQueriedPosition = position;
35236                     // Either we don'd have a node, or we have a node at the position being asked for.
35237                     ts.Debug.assert(!current || current.pos === position);
35238                     return current;
35239                 }
35240             };
35241             // Finds the highest element in the tree we can find that starts at the provided position.
35242             // The element must be a direct child of some node list in the tree.  This way after we
35243             // return it, we can easily return its next sibling in the list.
35244             function findHighestListElementThatStartsAtPosition(position) {
35245                 // Clear out any cached state about the last node we found.
35246                 currentArray = undefined;
35247                 currentArrayIndex = -1 /* Value */;
35248                 current = undefined;
35249                 // Recurse into the source file to find the highest node at this position.
35250                 forEachChild(sourceFile, visitNode, visitArray);
35251                 return;
35252                 function visitNode(node) {
35253                     if (position >= node.pos && position < node.end) {
35254                         // Position was within this node.  Keep searching deeper to find the node.
35255                         forEachChild(node, visitNode, visitArray);
35256                         // don't proceed any further in the search.
35257                         return true;
35258                     }
35259                     // position wasn't in this node, have to keep searching.
35260                     return false;
35261                 }
35262                 function visitArray(array) {
35263                     if (position >= array.pos && position < array.end) {
35264                         // position was in this array.  Search through this array to see if we find a
35265                         // viable element.
35266                         for (var i = 0; i < array.length; i++) {
35267                             var child = array[i];
35268                             if (child) {
35269                                 if (child.pos === position) {
35270                                     // Found the right node.  We're done.
35271                                     currentArray = array;
35272                                     currentArrayIndex = i;
35273                                     current = child;
35274                                     return true;
35275                                 }
35276                                 else {
35277                                     if (child.pos < position && position < child.end) {
35278                                         // Position in somewhere within this child.  Search in it and
35279                                         // stop searching in this array.
35280                                         forEachChild(child, visitNode, visitArray);
35281                                         return true;
35282                                     }
35283                                 }
35284                             }
35285                         }
35286                     }
35287                     // position wasn't in this array, have to keep searching.
35288                     return false;
35289                 }
35290             }
35291         }
35292         IncrementalParser.createSyntaxCursor = createSyntaxCursor;
35293         var InvalidPosition;
35294         (function (InvalidPosition) {
35295             InvalidPosition[InvalidPosition["Value"] = -1] = "Value";
35296         })(InvalidPosition || (InvalidPosition = {}));
35297     })(IncrementalParser || (IncrementalParser = {}));
35298     /** @internal */
35299     function isDeclarationFileName(fileName) {
35300         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
35301     }
35302     ts.isDeclarationFileName = isDeclarationFileName;
35303     /*@internal*/
35304     function processCommentPragmas(context, sourceText) {
35305         var pragmas = [];
35306         for (var _i = 0, _a = ts.getLeadingCommentRanges(sourceText, 0) || ts.emptyArray; _i < _a.length; _i++) {
35307             var range = _a[_i];
35308             var comment = sourceText.substring(range.pos, range.end);
35309             extractPragmas(pragmas, range, comment);
35310         }
35311         context.pragmas = new ts.Map();
35312         for (var _b = 0, pragmas_1 = pragmas; _b < pragmas_1.length; _b++) {
35313             var pragma = pragmas_1[_b];
35314             if (context.pragmas.has(pragma.name)) {
35315                 var currentValue = context.pragmas.get(pragma.name);
35316                 if (currentValue instanceof Array) {
35317                     currentValue.push(pragma.args);
35318                 }
35319                 else {
35320                     context.pragmas.set(pragma.name, [currentValue, pragma.args]);
35321                 }
35322                 continue;
35323             }
35324             context.pragmas.set(pragma.name, pragma.args);
35325         }
35326     }
35327     ts.processCommentPragmas = processCommentPragmas;
35328     /*@internal*/
35329     function processPragmasIntoFields(context, reportDiagnostic) {
35330         context.checkJsDirective = undefined;
35331         context.referencedFiles = [];
35332         context.typeReferenceDirectives = [];
35333         context.libReferenceDirectives = [];
35334         context.amdDependencies = [];
35335         context.hasNoDefaultLib = false;
35336         context.pragmas.forEach(function (entryOrList, key) {
35337             // TODO: The below should be strongly type-guarded and not need casts/explicit annotations, since entryOrList is related to
35338             // key and key is constrained to a union; but it's not (see GH#21483 for at least partial fix) :(
35339             switch (key) {
35340                 case "reference": {
35341                     var referencedFiles_1 = context.referencedFiles;
35342                     var typeReferenceDirectives_1 = context.typeReferenceDirectives;
35343                     var libReferenceDirectives_1 = context.libReferenceDirectives;
35344                     ts.forEach(ts.toArray(entryOrList), function (arg) {
35345                         var _a = arg.arguments, types = _a.types, lib = _a.lib, path = _a.path;
35346                         if (arg.arguments["no-default-lib"]) {
35347                             context.hasNoDefaultLib = true;
35348                         }
35349                         else if (types) {
35350                             typeReferenceDirectives_1.push({ pos: types.pos, end: types.end, fileName: types.value });
35351                         }
35352                         else if (lib) {
35353                             libReferenceDirectives_1.push({ pos: lib.pos, end: lib.end, fileName: lib.value });
35354                         }
35355                         else if (path) {
35356                             referencedFiles_1.push({ pos: path.pos, end: path.end, fileName: path.value });
35357                         }
35358                         else {
35359                             reportDiagnostic(arg.range.pos, arg.range.end - arg.range.pos, ts.Diagnostics.Invalid_reference_directive_syntax);
35360                         }
35361                     });
35362                     break;
35363                 }
35364                 case "amd-dependency": {
35365                     context.amdDependencies = ts.map(ts.toArray(entryOrList), function (x) { return ({ name: x.arguments.name, path: x.arguments.path }); });
35366                     break;
35367                 }
35368                 case "amd-module": {
35369                     if (entryOrList instanceof Array) {
35370                         for (var _i = 0, entryOrList_1 = entryOrList; _i < entryOrList_1.length; _i++) {
35371                             var entry = entryOrList_1[_i];
35372                             if (context.moduleName) {
35373                                 // TODO: It's probably fine to issue this diagnostic on all instances of the pragma
35374                                 reportDiagnostic(entry.range.pos, entry.range.end - entry.range.pos, ts.Diagnostics.An_AMD_module_cannot_have_multiple_name_assignments);
35375                             }
35376                             context.moduleName = entry.arguments.name;
35377                         }
35378                     }
35379                     else {
35380                         context.moduleName = entryOrList.arguments.name;
35381                     }
35382                     break;
35383                 }
35384                 case "ts-nocheck":
35385                 case "ts-check": {
35386                     // _last_ of either nocheck or check in a file is the "winner"
35387                     ts.forEach(ts.toArray(entryOrList), function (entry) {
35388                         if (!context.checkJsDirective || entry.range.pos > context.checkJsDirective.pos) {
35389                             context.checkJsDirective = {
35390                                 enabled: key === "ts-check",
35391                                 end: entry.range.end,
35392                                 pos: entry.range.pos
35393                             };
35394                         }
35395                     });
35396                     break;
35397                 }
35398                 case "jsx":
35399                 case "jsxfrag":
35400                 case "jsximportsource":
35401                 case "jsxruntime":
35402                     return; // Accessed directly
35403                 default: ts.Debug.fail("Unhandled pragma kind"); // Can this be made into an assertNever in the future?
35404             }
35405         });
35406     }
35407     ts.processPragmasIntoFields = processPragmasIntoFields;
35408     var namedArgRegExCache = new ts.Map();
35409     function getNamedArgRegEx(name) {
35410         if (namedArgRegExCache.has(name)) {
35411             return namedArgRegExCache.get(name);
35412         }
35413         var result = new RegExp("(\\s" + name + "\\s*=\\s*)('|\")(.+?)\\2", "im");
35414         namedArgRegExCache.set(name, result);
35415         return result;
35416     }
35417     var tripleSlashXMLCommentStartRegEx = /^\/\/\/\s*<(\S+)\s.*?\/>/im;
35418     var singleLinePragmaRegEx = /^\/\/\/?\s*@(\S+)\s*(.*)\s*$/im;
35419     function extractPragmas(pragmas, range, text) {
35420         var tripleSlash = range.kind === 2 /* SingleLineCommentTrivia */ && tripleSlashXMLCommentStartRegEx.exec(text);
35421         if (tripleSlash) {
35422             var name = tripleSlash[1].toLowerCase(); // Technically unsafe cast, but we do it so the below check to make it safe typechecks
35423             var pragma = ts.commentPragmas[name];
35424             if (!pragma || !(pragma.kind & 1 /* TripleSlashXML */)) {
35425                 return;
35426             }
35427             if (pragma.args) {
35428                 var argument = {};
35429                 for (var _i = 0, _a = pragma.args; _i < _a.length; _i++) {
35430                     var arg = _a[_i];
35431                     var matcher = getNamedArgRegEx(arg.name);
35432                     var matchResult = matcher.exec(text);
35433                     if (!matchResult && !arg.optional) {
35434                         return; // Missing required argument, don't parse
35435                     }
35436                     else if (matchResult) {
35437                         if (arg.captureSpan) {
35438                             var startPos = range.pos + matchResult.index + matchResult[1].length + matchResult[2].length;
35439                             argument[arg.name] = {
35440                                 value: matchResult[3],
35441                                 pos: startPos,
35442                                 end: startPos + matchResult[3].length
35443                             };
35444                         }
35445                         else {
35446                             argument[arg.name] = matchResult[3];
35447                         }
35448                     }
35449                 }
35450                 pragmas.push({ name: name, args: { arguments: argument, range: range } });
35451             }
35452             else {
35453                 pragmas.push({ name: name, args: { arguments: {}, range: range } });
35454             }
35455             return;
35456         }
35457         var singleLine = range.kind === 2 /* SingleLineCommentTrivia */ && singleLinePragmaRegEx.exec(text);
35458         if (singleLine) {
35459             return addPragmaForMatch(pragmas, range, 2 /* SingleLine */, singleLine);
35460         }
35461         if (range.kind === 3 /* MultiLineCommentTrivia */) {
35462             var multiLinePragmaRegEx = /\s*@(\S+)\s*(.*)\s*$/gim; // Defined inline since it uses the "g" flag, which keeps a persistent index (for iterating)
35463             var multiLineMatch = void 0;
35464             while (multiLineMatch = multiLinePragmaRegEx.exec(text)) {
35465                 addPragmaForMatch(pragmas, range, 4 /* MultiLine */, multiLineMatch);
35466             }
35467         }
35468     }
35469     function addPragmaForMatch(pragmas, range, kind, match) {
35470         if (!match)
35471             return;
35472         var name = match[1].toLowerCase(); // Technically unsafe cast, but we do it so they below check to make it safe typechecks
35473         var pragma = ts.commentPragmas[name];
35474         if (!pragma || !(pragma.kind & kind)) {
35475             return;
35476         }
35477         var args = match[2]; // Split on spaces and match up positionally with definition
35478         var argument = getNamedPragmaArguments(pragma, args);
35479         if (argument === "fail")
35480             return; // Missing required argument, fail to parse it
35481         pragmas.push({ name: name, args: { arguments: argument, range: range } });
35482         return;
35483     }
35484     function getNamedPragmaArguments(pragma, text) {
35485         if (!text)
35486             return {};
35487         if (!pragma.args)
35488             return {};
35489         var args = text.split(/\s+/);
35490         var argMap = {};
35491         for (var i = 0; i < pragma.args.length; i++) {
35492             var argument = pragma.args[i];
35493             if (!args[i] && !argument.optional) {
35494                 return "fail";
35495             }
35496             if (argument.captureSpan) {
35497                 return ts.Debug.fail("Capture spans not yet implemented for non-xml pragmas");
35498             }
35499             argMap[argument.name] = args[i];
35500         }
35501         return argMap;
35502     }
35503     /** @internal */
35504     function tagNamesAreEquivalent(lhs, rhs) {
35505         if (lhs.kind !== rhs.kind) {
35506             return false;
35507         }
35508         if (lhs.kind === 78 /* Identifier */) {
35509             return lhs.escapedText === rhs.escapedText;
35510         }
35511         if (lhs.kind === 107 /* ThisKeyword */) {
35512             return true;
35513         }
35514         // If we are at this statement then we must have PropertyAccessExpression and because tag name in Jsx element can only
35515         // take forms of JsxTagNameExpression which includes an identifier, "this" expression, or another propertyAccessExpression
35516         // it is safe to case the expression property as such. See parseJsxElementName for how we parse tag name in Jsx element
35517         return lhs.name.escapedText === rhs.name.escapedText &&
35518             tagNamesAreEquivalent(lhs.expression, rhs.expression);
35519     }
35520     ts.tagNamesAreEquivalent = tagNamesAreEquivalent;
35521 })(ts || (ts = {}));
35522 var ts;
35523 (function (ts) {
35524     /* @internal */
35525     ts.compileOnSaveCommandLineOption = { name: "compileOnSave", type: "boolean" };
35526     var jsxOptionMap = new ts.Map(ts.getEntries({
35527         "preserve": 1 /* Preserve */,
35528         "react-native": 3 /* ReactNative */,
35529         "react": 2 /* React */,
35530         "react-jsx": 4 /* ReactJSX */,
35531         "react-jsxdev": 5 /* ReactJSXDev */,
35532     }));
35533     /* @internal */
35534     ts.inverseJsxOptionMap = new ts.Map(ts.arrayFrom(ts.mapIterator(jsxOptionMap.entries(), function (_a) {
35535         var key = _a[0], value = _a[1];
35536         return ["" + value, key];
35537     })));
35538     // NOTE: The order here is important to default lib ordering as entries will have the same
35539     //       order in the generated program (see `getDefaultLibPriority` in program.ts). This
35540     //       order also affects overload resolution when a type declared in one lib is
35541     //       augmented in another lib.
35542     var libEntries = [
35543         // JavaScript only
35544         ["es5", "lib.es5.d.ts"],
35545         ["es6", "lib.es2015.d.ts"],
35546         ["es2015", "lib.es2015.d.ts"],
35547         ["es7", "lib.es2016.d.ts"],
35548         ["es2016", "lib.es2016.d.ts"],
35549         ["es2017", "lib.es2017.d.ts"],
35550         ["es2018", "lib.es2018.d.ts"],
35551         ["es2019", "lib.es2019.d.ts"],
35552         ["es2020", "lib.es2020.d.ts"],
35553         ["esnext", "lib.esnext.d.ts"],
35554         // Host only
35555         ["dom", "lib.dom.d.ts"],
35556         ["dom.iterable", "lib.dom.iterable.d.ts"],
35557         ["webworker", "lib.webworker.d.ts"],
35558         ["webworker.importscripts", "lib.webworker.importscripts.d.ts"],
35559         ["webworker.iterable", "lib.webworker.iterable.d.ts"],
35560         ["scripthost", "lib.scripthost.d.ts"],
35561         // ES2015 Or ESNext By-feature options
35562         ["es2015.core", "lib.es2015.core.d.ts"],
35563         ["es2015.collection", "lib.es2015.collection.d.ts"],
35564         ["es2015.generator", "lib.es2015.generator.d.ts"],
35565         ["es2015.iterable", "lib.es2015.iterable.d.ts"],
35566         ["es2015.promise", "lib.es2015.promise.d.ts"],
35567         ["es2015.proxy", "lib.es2015.proxy.d.ts"],
35568         ["es2015.reflect", "lib.es2015.reflect.d.ts"],
35569         ["es2015.symbol", "lib.es2015.symbol.d.ts"],
35570         ["es2015.symbol.wellknown", "lib.es2015.symbol.wellknown.d.ts"],
35571         ["es2016.array.include", "lib.es2016.array.include.d.ts"],
35572         ["es2017.object", "lib.es2017.object.d.ts"],
35573         ["es2017.sharedmemory", "lib.es2017.sharedmemory.d.ts"],
35574         ["es2017.string", "lib.es2017.string.d.ts"],
35575         ["es2017.intl", "lib.es2017.intl.d.ts"],
35576         ["es2017.typedarrays", "lib.es2017.typedarrays.d.ts"],
35577         ["es2018.asyncgenerator", "lib.es2018.asyncgenerator.d.ts"],
35578         ["es2018.asynciterable", "lib.es2018.asynciterable.d.ts"],
35579         ["es2018.intl", "lib.es2018.intl.d.ts"],
35580         ["es2018.promise", "lib.es2018.promise.d.ts"],
35581         ["es2018.regexp", "lib.es2018.regexp.d.ts"],
35582         ["es2019.array", "lib.es2019.array.d.ts"],
35583         ["es2019.object", "lib.es2019.object.d.ts"],
35584         ["es2019.string", "lib.es2019.string.d.ts"],
35585         ["es2019.symbol", "lib.es2019.symbol.d.ts"],
35586         ["es2020.bigint", "lib.es2020.bigint.d.ts"],
35587         ["es2020.promise", "lib.es2020.promise.d.ts"],
35588         ["es2020.sharedmemory", "lib.es2020.sharedmemory.d.ts"],
35589         ["es2020.string", "lib.es2020.string.d.ts"],
35590         ["es2020.symbol.wellknown", "lib.es2020.symbol.wellknown.d.ts"],
35591         ["es2020.intl", "lib.es2020.intl.d.ts"],
35592         ["esnext.array", "lib.es2019.array.d.ts"],
35593         ["esnext.symbol", "lib.es2019.symbol.d.ts"],
35594         ["esnext.asynciterable", "lib.es2018.asynciterable.d.ts"],
35595         ["esnext.intl", "lib.esnext.intl.d.ts"],
35596         ["esnext.bigint", "lib.es2020.bigint.d.ts"],
35597         ["esnext.string", "lib.esnext.string.d.ts"],
35598         ["esnext.promise", "lib.esnext.promise.d.ts"],
35599         ["esnext.weakref", "lib.esnext.weakref.d.ts"]
35600     ];
35601     /**
35602      * An array of supported "lib" reference file names used to determine the order for inclusion
35603      * when referenced, as well as for spelling suggestions. This ensures the correct ordering for
35604      * overload resolution when a type declared in one lib is extended by another.
35605      */
35606     /* @internal */
35607     ts.libs = libEntries.map(function (entry) { return entry[0]; });
35608     /**
35609      * A map of lib names to lib files. This map is used both for parsing the "lib" command line
35610      * option as well as for resolving lib reference directives.
35611      */
35612     /* @internal */
35613     ts.libMap = new ts.Map(libEntries);
35614     // Watch related options
35615     /* @internal */
35616     ts.optionsForWatch = [
35617         {
35618             name: "watchFile",
35619             type: new ts.Map(ts.getEntries({
35620                 fixedpollinginterval: ts.WatchFileKind.FixedPollingInterval,
35621                 prioritypollinginterval: ts.WatchFileKind.PriorityPollingInterval,
35622                 dynamicprioritypolling: ts.WatchFileKind.DynamicPriorityPolling,
35623                 usefsevents: ts.WatchFileKind.UseFsEvents,
35624                 usefseventsonparentdirectory: ts.WatchFileKind.UseFsEventsOnParentDirectory,
35625             })),
35626             category: ts.Diagnostics.Advanced_Options,
35627             description: ts.Diagnostics.Specify_strategy_for_watching_file_Colon_FixedPollingInterval_default_PriorityPollingInterval_DynamicPriorityPolling_UseFsEvents_UseFsEventsOnParentDirectory,
35628         },
35629         {
35630             name: "watchDirectory",
35631             type: new ts.Map(ts.getEntries({
35632                 usefsevents: ts.WatchDirectoryKind.UseFsEvents,
35633                 fixedpollinginterval: ts.WatchDirectoryKind.FixedPollingInterval,
35634                 dynamicprioritypolling: ts.WatchDirectoryKind.DynamicPriorityPolling,
35635             })),
35636             category: ts.Diagnostics.Advanced_Options,
35637             description: ts.Diagnostics.Specify_strategy_for_watching_directory_on_platforms_that_don_t_support_recursive_watching_natively_Colon_UseFsEvents_default_FixedPollingInterval_DynamicPriorityPolling,
35638         },
35639         {
35640             name: "fallbackPolling",
35641             type: new ts.Map(ts.getEntries({
35642                 fixedinterval: ts.PollingWatchKind.FixedInterval,
35643                 priorityinterval: ts.PollingWatchKind.PriorityInterval,
35644                 dynamicpriority: ts.PollingWatchKind.DynamicPriority,
35645             })),
35646             category: ts.Diagnostics.Advanced_Options,
35647             description: ts.Diagnostics.Specify_strategy_for_creating_a_polling_watch_when_it_fails_to_create_using_file_system_events_Colon_FixedInterval_default_PriorityInterval_DynamicPriority,
35648         },
35649         {
35650             name: "synchronousWatchDirectory",
35651             type: "boolean",
35652             category: ts.Diagnostics.Advanced_Options,
35653             description: ts.Diagnostics.Synchronously_call_callbacks_and_update_the_state_of_directory_watchers_on_platforms_that_don_t_support_recursive_watching_natively,
35654         },
35655     ];
35656     /* @internal */
35657     ts.commonOptionsWithBuild = [
35658         {
35659             name: "help",
35660             shortName: "h",
35661             type: "boolean",
35662             showInSimplifiedHelpView: true,
35663             category: ts.Diagnostics.Command_line_Options,
35664             description: ts.Diagnostics.Print_this_message,
35665         },
35666         {
35667             name: "help",
35668             shortName: "?",
35669             type: "boolean"
35670         },
35671         {
35672             name: "watch",
35673             shortName: "w",
35674             type: "boolean",
35675             showInSimplifiedHelpView: true,
35676             category: ts.Diagnostics.Command_line_Options,
35677             description: ts.Diagnostics.Watch_input_files,
35678         },
35679         {
35680             name: "preserveWatchOutput",
35681             type: "boolean",
35682             showInSimplifiedHelpView: false,
35683             category: ts.Diagnostics.Command_line_Options,
35684             description: ts.Diagnostics.Whether_to_keep_outdated_console_output_in_watch_mode_instead_of_clearing_the_screen,
35685         },
35686         {
35687             name: "listFiles",
35688             type: "boolean",
35689             category: ts.Diagnostics.Advanced_Options,
35690             description: ts.Diagnostics.Print_names_of_files_part_of_the_compilation
35691         },
35692         {
35693             name: "listEmittedFiles",
35694             type: "boolean",
35695             category: ts.Diagnostics.Advanced_Options,
35696             description: ts.Diagnostics.Print_names_of_generated_files_part_of_the_compilation
35697         },
35698         {
35699             name: "pretty",
35700             type: "boolean",
35701             showInSimplifiedHelpView: true,
35702             category: ts.Diagnostics.Command_line_Options,
35703             description: ts.Diagnostics.Stylize_errors_and_messages_using_color_and_context_experimental
35704         },
35705         {
35706             name: "traceResolution",
35707             type: "boolean",
35708             category: ts.Diagnostics.Advanced_Options,
35709             description: ts.Diagnostics.Enable_tracing_of_the_name_resolution_process
35710         },
35711         {
35712             name: "diagnostics",
35713             type: "boolean",
35714             category: ts.Diagnostics.Advanced_Options,
35715             description: ts.Diagnostics.Show_diagnostic_information
35716         },
35717         {
35718             name: "extendedDiagnostics",
35719             type: "boolean",
35720             category: ts.Diagnostics.Advanced_Options,
35721             description: ts.Diagnostics.Show_verbose_diagnostic_information
35722         },
35723         {
35724             name: "generateCpuProfile",
35725             type: "string",
35726             isFilePath: true,
35727             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
35728             category: ts.Diagnostics.Advanced_Options,
35729             description: ts.Diagnostics.Generates_a_CPU_profile
35730         },
35731         {
35732             name: "generateTrace",
35733             type: "string",
35734             isFilePath: true,
35735             isCommandLineOnly: true,
35736             paramType: ts.Diagnostics.DIRECTORY,
35737             category: ts.Diagnostics.Advanced_Options,
35738             description: ts.Diagnostics.Generates_an_event_trace_and_a_list_of_types
35739         },
35740         {
35741             name: "incremental",
35742             shortName: "i",
35743             type: "boolean",
35744             category: ts.Diagnostics.Basic_Options,
35745             description: ts.Diagnostics.Enable_incremental_compilation,
35746             transpileOptionValue: undefined
35747         },
35748         {
35749             name: "assumeChangesOnlyAffectDirectDependencies",
35750             type: "boolean",
35751             affectsSemanticDiagnostics: true,
35752             affectsEmit: true,
35753             category: ts.Diagnostics.Advanced_Options,
35754             description: ts.Diagnostics.Have_recompiles_in_incremental_and_watch_assume_that_changes_within_a_file_will_only_affect_files_directly_depending_on_it
35755         },
35756         {
35757             name: "locale",
35758             type: "string",
35759             category: ts.Diagnostics.Advanced_Options,
35760             description: ts.Diagnostics.The_locale_used_when_displaying_messages_to_the_user_e_g_en_us
35761         },
35762     ];
35763     /* @internal */
35764     ts.optionDeclarations = __spreadArrays(ts.commonOptionsWithBuild, [
35765         {
35766             name: "all",
35767             type: "boolean",
35768             showInSimplifiedHelpView: true,
35769             category: ts.Diagnostics.Command_line_Options,
35770             description: ts.Diagnostics.Show_all_compiler_options,
35771         },
35772         {
35773             name: "version",
35774             shortName: "v",
35775             type: "boolean",
35776             showInSimplifiedHelpView: true,
35777             category: ts.Diagnostics.Command_line_Options,
35778             description: ts.Diagnostics.Print_the_compiler_s_version,
35779         },
35780         {
35781             name: "init",
35782             type: "boolean",
35783             showInSimplifiedHelpView: true,
35784             category: ts.Diagnostics.Command_line_Options,
35785             description: ts.Diagnostics.Initializes_a_TypeScript_project_and_creates_a_tsconfig_json_file,
35786         },
35787         {
35788             name: "project",
35789             shortName: "p",
35790             type: "string",
35791             isFilePath: true,
35792             showInSimplifiedHelpView: true,
35793             category: ts.Diagnostics.Command_line_Options,
35794             paramType: ts.Diagnostics.FILE_OR_DIRECTORY,
35795             description: ts.Diagnostics.Compile_the_project_given_the_path_to_its_configuration_file_or_to_a_folder_with_a_tsconfig_json,
35796         },
35797         {
35798             name: "build",
35799             type: "boolean",
35800             shortName: "b",
35801             showInSimplifiedHelpView: true,
35802             category: ts.Diagnostics.Command_line_Options,
35803             description: ts.Diagnostics.Build_one_or_more_projects_and_their_dependencies_if_out_of_date
35804         },
35805         {
35806             name: "showConfig",
35807             type: "boolean",
35808             category: ts.Diagnostics.Command_line_Options,
35809             isCommandLineOnly: true,
35810             description: ts.Diagnostics.Print_the_final_configuration_instead_of_building
35811         },
35812         {
35813             name: "listFilesOnly",
35814             type: "boolean",
35815             category: ts.Diagnostics.Command_line_Options,
35816             affectsSemanticDiagnostics: true,
35817             affectsEmit: true,
35818             isCommandLineOnly: true,
35819             description: ts.Diagnostics.Print_names_of_files_that_are_part_of_the_compilation_and_then_stop_processing
35820         },
35821         // Basic
35822         {
35823             name: "target",
35824             shortName: "t",
35825             type: new ts.Map(ts.getEntries({
35826                 es3: 0 /* ES3 */,
35827                 es5: 1 /* ES5 */,
35828                 es6: 2 /* ES2015 */,
35829                 es2015: 2 /* ES2015 */,
35830                 es2016: 3 /* ES2016 */,
35831                 es2017: 4 /* ES2017 */,
35832                 es2018: 5 /* ES2018 */,
35833                 es2019: 6 /* ES2019 */,
35834                 es2020: 7 /* ES2020 */,
35835                 esnext: 99 /* ESNext */,
35836             })),
35837             affectsSourceFile: true,
35838             affectsModuleResolution: true,
35839             affectsEmit: true,
35840             paramType: ts.Diagnostics.VERSION,
35841             showInSimplifiedHelpView: true,
35842             category: ts.Diagnostics.Basic_Options,
35843             description: ts.Diagnostics.Specify_ECMAScript_target_version_Colon_ES3_default_ES5_ES2015_ES2016_ES2017_ES2018_ES2019_ES2020_or_ESNEXT,
35844         },
35845         {
35846             name: "module",
35847             shortName: "m",
35848             type: new ts.Map(ts.getEntries({
35849                 none: ts.ModuleKind.None,
35850                 commonjs: ts.ModuleKind.CommonJS,
35851                 amd: ts.ModuleKind.AMD,
35852                 system: ts.ModuleKind.System,
35853                 umd: ts.ModuleKind.UMD,
35854                 es6: ts.ModuleKind.ES2015,
35855                 es2015: ts.ModuleKind.ES2015,
35856                 es2020: ts.ModuleKind.ES2020,
35857                 esnext: ts.ModuleKind.ESNext
35858             })),
35859             affectsModuleResolution: true,
35860             affectsEmit: true,
35861             paramType: ts.Diagnostics.KIND,
35862             showInSimplifiedHelpView: true,
35863             category: ts.Diagnostics.Basic_Options,
35864             description: ts.Diagnostics.Specify_module_code_generation_Colon_none_commonjs_amd_system_umd_es2015_es2020_or_ESNext,
35865         },
35866         {
35867             name: "lib",
35868             type: "list",
35869             element: {
35870                 name: "lib",
35871                 type: ts.libMap
35872             },
35873             affectsModuleResolution: true,
35874             showInSimplifiedHelpView: true,
35875             category: ts.Diagnostics.Basic_Options,
35876             description: ts.Diagnostics.Specify_library_files_to_be_included_in_the_compilation,
35877             transpileOptionValue: undefined
35878         },
35879         {
35880             name: "allowJs",
35881             type: "boolean",
35882             affectsModuleResolution: true,
35883             showInSimplifiedHelpView: true,
35884             category: ts.Diagnostics.Basic_Options,
35885             description: ts.Diagnostics.Allow_javascript_files_to_be_compiled
35886         },
35887         {
35888             name: "checkJs",
35889             type: "boolean",
35890             category: ts.Diagnostics.Basic_Options,
35891             description: ts.Diagnostics.Report_errors_in_js_files
35892         },
35893         {
35894             name: "jsx",
35895             type: jsxOptionMap,
35896             affectsSourceFile: true,
35897             affectsEmit: true,
35898             affectsModuleResolution: true,
35899             paramType: ts.Diagnostics.KIND,
35900             showInSimplifiedHelpView: true,
35901             category: ts.Diagnostics.Basic_Options,
35902             description: ts.Diagnostics.Specify_JSX_code_generation_Colon_preserve_react_native_or_react,
35903         },
35904         {
35905             name: "declaration",
35906             shortName: "d",
35907             type: "boolean",
35908             affectsEmit: true,
35909             showInSimplifiedHelpView: true,
35910             category: ts.Diagnostics.Basic_Options,
35911             description: ts.Diagnostics.Generates_corresponding_d_ts_file,
35912             transpileOptionValue: undefined
35913         },
35914         {
35915             name: "declarationMap",
35916             type: "boolean",
35917             affectsEmit: true,
35918             showInSimplifiedHelpView: true,
35919             category: ts.Diagnostics.Basic_Options,
35920             description: ts.Diagnostics.Generates_a_sourcemap_for_each_corresponding_d_ts_file,
35921             transpileOptionValue: undefined
35922         },
35923         {
35924             name: "emitDeclarationOnly",
35925             type: "boolean",
35926             affectsEmit: true,
35927             category: ts.Diagnostics.Advanced_Options,
35928             description: ts.Diagnostics.Only_emit_d_ts_declaration_files,
35929             transpileOptionValue: undefined
35930         },
35931         {
35932             name: "sourceMap",
35933             type: "boolean",
35934             affectsEmit: true,
35935             showInSimplifiedHelpView: true,
35936             category: ts.Diagnostics.Basic_Options,
35937             description: ts.Diagnostics.Generates_corresponding_map_file,
35938         },
35939         {
35940             name: "outFile",
35941             type: "string",
35942             affectsEmit: true,
35943             isFilePath: true,
35944             paramType: ts.Diagnostics.FILE,
35945             showInSimplifiedHelpView: true,
35946             category: ts.Diagnostics.Basic_Options,
35947             description: ts.Diagnostics.Concatenate_and_emit_output_to_single_file,
35948             transpileOptionValue: undefined
35949         },
35950         {
35951             name: "outDir",
35952             type: "string",
35953             affectsEmit: true,
35954             isFilePath: true,
35955             paramType: ts.Diagnostics.DIRECTORY,
35956             showInSimplifiedHelpView: true,
35957             category: ts.Diagnostics.Basic_Options,
35958             description: ts.Diagnostics.Redirect_output_structure_to_the_directory,
35959         },
35960         {
35961             name: "rootDir",
35962             type: "string",
35963             affectsEmit: true,
35964             isFilePath: true,
35965             paramType: ts.Diagnostics.LOCATION,
35966             category: ts.Diagnostics.Basic_Options,
35967             description: ts.Diagnostics.Specify_the_root_directory_of_input_files_Use_to_control_the_output_directory_structure_with_outDir,
35968         },
35969         {
35970             name: "composite",
35971             type: "boolean",
35972             affectsEmit: true,
35973             isTSConfigOnly: true,
35974             category: ts.Diagnostics.Basic_Options,
35975             description: ts.Diagnostics.Enable_project_compilation,
35976             transpileOptionValue: undefined
35977         },
35978         {
35979             name: "tsBuildInfoFile",
35980             type: "string",
35981             affectsEmit: true,
35982             isFilePath: true,
35983             paramType: ts.Diagnostics.FILE,
35984             category: ts.Diagnostics.Basic_Options,
35985             description: ts.Diagnostics.Specify_file_to_store_incremental_compilation_information,
35986             transpileOptionValue: undefined
35987         },
35988         {
35989             name: "removeComments",
35990             type: "boolean",
35991             affectsEmit: true,
35992             showInSimplifiedHelpView: true,
35993             category: ts.Diagnostics.Basic_Options,
35994             description: ts.Diagnostics.Do_not_emit_comments_to_output,
35995         },
35996         {
35997             name: "noEmit",
35998             type: "boolean",
35999             showInSimplifiedHelpView: true,
36000             category: ts.Diagnostics.Basic_Options,
36001             description: ts.Diagnostics.Do_not_emit_outputs,
36002             transpileOptionValue: undefined
36003         },
36004         {
36005             name: "importHelpers",
36006             type: "boolean",
36007             affectsEmit: true,
36008             category: ts.Diagnostics.Basic_Options,
36009             description: ts.Diagnostics.Import_emit_helpers_from_tslib
36010         },
36011         {
36012             name: "importsNotUsedAsValues",
36013             type: new ts.Map(ts.getEntries({
36014                 remove: 0 /* Remove */,
36015                 preserve: 1 /* Preserve */,
36016                 error: 2 /* Error */
36017             })),
36018             affectsEmit: true,
36019             affectsSemanticDiagnostics: true,
36020             category: ts.Diagnostics.Advanced_Options,
36021             description: ts.Diagnostics.Specify_emit_Slashchecking_behavior_for_imports_that_are_only_used_for_types
36022         },
36023         {
36024             name: "downlevelIteration",
36025             type: "boolean",
36026             affectsEmit: true,
36027             category: ts.Diagnostics.Basic_Options,
36028             description: ts.Diagnostics.Provide_full_support_for_iterables_in_for_of_spread_and_destructuring_when_targeting_ES5_or_ES3
36029         },
36030         {
36031             name: "isolatedModules",
36032             type: "boolean",
36033             category: ts.Diagnostics.Basic_Options,
36034             description: ts.Diagnostics.Transpile_each_file_as_a_separate_module_similar_to_ts_transpileModule,
36035             transpileOptionValue: true
36036         },
36037         // Strict Type Checks
36038         {
36039             name: "strict",
36040             type: "boolean",
36041             showInSimplifiedHelpView: true,
36042             category: ts.Diagnostics.Strict_Type_Checking_Options,
36043             description: ts.Diagnostics.Enable_all_strict_type_checking_options
36044         },
36045         {
36046             name: "noImplicitAny",
36047             type: "boolean",
36048             affectsSemanticDiagnostics: true,
36049             strictFlag: true,
36050             showInSimplifiedHelpView: true,
36051             category: ts.Diagnostics.Strict_Type_Checking_Options,
36052             description: ts.Diagnostics.Raise_error_on_expressions_and_declarations_with_an_implied_any_type
36053         },
36054         {
36055             name: "strictNullChecks",
36056             type: "boolean",
36057             affectsSemanticDiagnostics: true,
36058             strictFlag: true,
36059             showInSimplifiedHelpView: true,
36060             category: ts.Diagnostics.Strict_Type_Checking_Options,
36061             description: ts.Diagnostics.Enable_strict_null_checks
36062         },
36063         {
36064             name: "strictFunctionTypes",
36065             type: "boolean",
36066             affectsSemanticDiagnostics: true,
36067             strictFlag: true,
36068             showInSimplifiedHelpView: true,
36069             category: ts.Diagnostics.Strict_Type_Checking_Options,
36070             description: ts.Diagnostics.Enable_strict_checking_of_function_types
36071         },
36072         {
36073             name: "strictBindCallApply",
36074             type: "boolean",
36075             strictFlag: true,
36076             showInSimplifiedHelpView: true,
36077             category: ts.Diagnostics.Strict_Type_Checking_Options,
36078             description: ts.Diagnostics.Enable_strict_bind_call_and_apply_methods_on_functions
36079         },
36080         {
36081             name: "strictPropertyInitialization",
36082             type: "boolean",
36083             affectsSemanticDiagnostics: true,
36084             strictFlag: true,
36085             showInSimplifiedHelpView: true,
36086             category: ts.Diagnostics.Strict_Type_Checking_Options,
36087             description: ts.Diagnostics.Enable_strict_checking_of_property_initialization_in_classes
36088         },
36089         {
36090             name: "noImplicitThis",
36091             type: "boolean",
36092             affectsSemanticDiagnostics: true,
36093             strictFlag: true,
36094             showInSimplifiedHelpView: true,
36095             category: ts.Diagnostics.Strict_Type_Checking_Options,
36096             description: ts.Diagnostics.Raise_error_on_this_expressions_with_an_implied_any_type,
36097         },
36098         {
36099             name: "alwaysStrict",
36100             type: "boolean",
36101             affectsSourceFile: true,
36102             strictFlag: true,
36103             showInSimplifiedHelpView: true,
36104             category: ts.Diagnostics.Strict_Type_Checking_Options,
36105             description: ts.Diagnostics.Parse_in_strict_mode_and_emit_use_strict_for_each_source_file
36106         },
36107         // Additional Checks
36108         {
36109             name: "noUnusedLocals",
36110             type: "boolean",
36111             affectsSemanticDiagnostics: true,
36112             showInSimplifiedHelpView: true,
36113             category: ts.Diagnostics.Additional_Checks,
36114             description: ts.Diagnostics.Report_errors_on_unused_locals,
36115         },
36116         {
36117             name: "noUnusedParameters",
36118             type: "boolean",
36119             affectsSemanticDiagnostics: true,
36120             showInSimplifiedHelpView: true,
36121             category: ts.Diagnostics.Additional_Checks,
36122             description: ts.Diagnostics.Report_errors_on_unused_parameters,
36123         },
36124         {
36125             name: "noImplicitReturns",
36126             type: "boolean",
36127             affectsSemanticDiagnostics: true,
36128             showInSimplifiedHelpView: true,
36129             category: ts.Diagnostics.Additional_Checks,
36130             description: ts.Diagnostics.Report_error_when_not_all_code_paths_in_function_return_a_value
36131         },
36132         {
36133             name: "noFallthroughCasesInSwitch",
36134             type: "boolean",
36135             affectsBindDiagnostics: true,
36136             affectsSemanticDiagnostics: true,
36137             showInSimplifiedHelpView: true,
36138             category: ts.Diagnostics.Additional_Checks,
36139             description: ts.Diagnostics.Report_errors_for_fallthrough_cases_in_switch_statement
36140         },
36141         {
36142             name: "noUncheckedIndexedAccess",
36143             type: "boolean",
36144             affectsSemanticDiagnostics: true,
36145             showInSimplifiedHelpView: false,
36146             category: ts.Diagnostics.Additional_Checks,
36147             description: ts.Diagnostics.Include_undefined_in_index_signature_results
36148         },
36149         // Module Resolution
36150         {
36151             name: "moduleResolution",
36152             type: new ts.Map(ts.getEntries({
36153                 node: ts.ModuleResolutionKind.NodeJs,
36154                 classic: ts.ModuleResolutionKind.Classic,
36155             })),
36156             affectsModuleResolution: true,
36157             paramType: ts.Diagnostics.STRATEGY,
36158             category: ts.Diagnostics.Module_Resolution_Options,
36159             description: ts.Diagnostics.Specify_module_resolution_strategy_Colon_node_Node_js_or_classic_TypeScript_pre_1_6,
36160         },
36161         {
36162             name: "baseUrl",
36163             type: "string",
36164             affectsModuleResolution: true,
36165             isFilePath: true,
36166             category: ts.Diagnostics.Module_Resolution_Options,
36167             description: ts.Diagnostics.Base_directory_to_resolve_non_absolute_module_names
36168         },
36169         {
36170             // this option can only be specified in tsconfig.json
36171             // use type = object to copy the value as-is
36172             name: "paths",
36173             type: "object",
36174             affectsModuleResolution: true,
36175             isTSConfigOnly: true,
36176             category: ts.Diagnostics.Module_Resolution_Options,
36177             description: ts.Diagnostics.A_series_of_entries_which_re_map_imports_to_lookup_locations_relative_to_the_baseUrl,
36178             transpileOptionValue: undefined
36179         },
36180         {
36181             // this option can only be specified in tsconfig.json
36182             // use type = object to copy the value as-is
36183             name: "rootDirs",
36184             type: "list",
36185             isTSConfigOnly: true,
36186             element: {
36187                 name: "rootDirs",
36188                 type: "string",
36189                 isFilePath: true
36190             },
36191             affectsModuleResolution: true,
36192             category: ts.Diagnostics.Module_Resolution_Options,
36193             description: ts.Diagnostics.List_of_root_folders_whose_combined_content_represents_the_structure_of_the_project_at_runtime,
36194             transpileOptionValue: undefined
36195         },
36196         {
36197             name: "typeRoots",
36198             type: "list",
36199             element: {
36200                 name: "typeRoots",
36201                 type: "string",
36202                 isFilePath: true
36203             },
36204             affectsModuleResolution: true,
36205             category: ts.Diagnostics.Module_Resolution_Options,
36206             description: ts.Diagnostics.List_of_folders_to_include_type_definitions_from
36207         },
36208         {
36209             name: "types",
36210             type: "list",
36211             element: {
36212                 name: "types",
36213                 type: "string"
36214             },
36215             affectsModuleResolution: true,
36216             showInSimplifiedHelpView: true,
36217             category: ts.Diagnostics.Module_Resolution_Options,
36218             description: ts.Diagnostics.Type_declaration_files_to_be_included_in_compilation,
36219             transpileOptionValue: undefined
36220         },
36221         {
36222             name: "allowSyntheticDefaultImports",
36223             type: "boolean",
36224             affectsSemanticDiagnostics: true,
36225             category: ts.Diagnostics.Module_Resolution_Options,
36226             description: ts.Diagnostics.Allow_default_imports_from_modules_with_no_default_export_This_does_not_affect_code_emit_just_typechecking
36227         },
36228         {
36229             name: "esModuleInterop",
36230             type: "boolean",
36231             affectsSemanticDiagnostics: true,
36232             affectsEmit: true,
36233             showInSimplifiedHelpView: true,
36234             category: ts.Diagnostics.Module_Resolution_Options,
36235             description: ts.Diagnostics.Enables_emit_interoperability_between_CommonJS_and_ES_Modules_via_creation_of_namespace_objects_for_all_imports_Implies_allowSyntheticDefaultImports
36236         },
36237         {
36238             name: "preserveSymlinks",
36239             type: "boolean",
36240             category: ts.Diagnostics.Module_Resolution_Options,
36241             description: ts.Diagnostics.Do_not_resolve_the_real_path_of_symlinks,
36242         },
36243         {
36244             name: "allowUmdGlobalAccess",
36245             type: "boolean",
36246             affectsSemanticDiagnostics: true,
36247             category: ts.Diagnostics.Module_Resolution_Options,
36248             description: ts.Diagnostics.Allow_accessing_UMD_globals_from_modules,
36249         },
36250         // Source Maps
36251         {
36252             name: "sourceRoot",
36253             type: "string",
36254             affectsEmit: true,
36255             paramType: ts.Diagnostics.LOCATION,
36256             category: ts.Diagnostics.Source_Map_Options,
36257             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_TypeScript_files_instead_of_source_locations,
36258         },
36259         {
36260             name: "mapRoot",
36261             type: "string",
36262             affectsEmit: true,
36263             paramType: ts.Diagnostics.LOCATION,
36264             category: ts.Diagnostics.Source_Map_Options,
36265             description: ts.Diagnostics.Specify_the_location_where_debugger_should_locate_map_files_instead_of_generated_locations,
36266         },
36267         {
36268             name: "inlineSourceMap",
36269             type: "boolean",
36270             affectsEmit: true,
36271             category: ts.Diagnostics.Source_Map_Options,
36272             description: ts.Diagnostics.Emit_a_single_file_with_source_maps_instead_of_having_a_separate_file
36273         },
36274         {
36275             name: "inlineSources",
36276             type: "boolean",
36277             affectsEmit: true,
36278             category: ts.Diagnostics.Source_Map_Options,
36279             description: ts.Diagnostics.Emit_the_source_alongside_the_sourcemaps_within_a_single_file_requires_inlineSourceMap_or_sourceMap_to_be_set
36280         },
36281         // Experimental
36282         {
36283             name: "experimentalDecorators",
36284             type: "boolean",
36285             affectsSemanticDiagnostics: true,
36286             category: ts.Diagnostics.Experimental_Options,
36287             description: ts.Diagnostics.Enables_experimental_support_for_ES7_decorators
36288         },
36289         {
36290             name: "emitDecoratorMetadata",
36291             type: "boolean",
36292             affectsSemanticDiagnostics: true,
36293             affectsEmit: true,
36294             category: ts.Diagnostics.Experimental_Options,
36295             description: ts.Diagnostics.Enables_experimental_support_for_emitting_type_metadata_for_decorators
36296         },
36297         // Advanced
36298         {
36299             name: "jsxFactory",
36300             type: "string",
36301             category: ts.Diagnostics.Advanced_Options,
36302             description: ts.Diagnostics.Specify_the_JSX_factory_function_to_use_when_targeting_react_JSX_emit_e_g_React_createElement_or_h
36303         },
36304         {
36305             name: "jsxFragmentFactory",
36306             type: "string",
36307             category: ts.Diagnostics.Advanced_Options,
36308             description: ts.Diagnostics.Specify_the_JSX_fragment_factory_function_to_use_when_targeting_react_JSX_emit_with_jsxFactory_compiler_option_is_specified_e_g_Fragment
36309         },
36310         {
36311             name: "jsxImportSource",
36312             type: "string",
36313             affectsSemanticDiagnostics: true,
36314             affectsEmit: true,
36315             affectsModuleResolution: true,
36316             category: ts.Diagnostics.Advanced_Options,
36317             description: ts.Diagnostics.Specify_the_module_specifier_to_be_used_to_import_the_jsx_and_jsxs_factory_functions_from_eg_react
36318         },
36319         {
36320             name: "resolveJsonModule",
36321             type: "boolean",
36322             affectsModuleResolution: true,
36323             category: ts.Diagnostics.Advanced_Options,
36324             description: ts.Diagnostics.Include_modules_imported_with_json_extension
36325         },
36326         {
36327             name: "out",
36328             type: "string",
36329             affectsEmit: true,
36330             isFilePath: false,
36331             // for correct behaviour, please use outFile
36332             category: ts.Diagnostics.Advanced_Options,
36333             paramType: ts.Diagnostics.FILE,
36334             description: ts.Diagnostics.Deprecated_Use_outFile_instead_Concatenate_and_emit_output_to_single_file,
36335             transpileOptionValue: undefined
36336         },
36337         {
36338             name: "reactNamespace",
36339             type: "string",
36340             affectsEmit: true,
36341             category: ts.Diagnostics.Advanced_Options,
36342             description: ts.Diagnostics.Deprecated_Use_jsxFactory_instead_Specify_the_object_invoked_for_createElement_when_targeting_react_JSX_emit
36343         },
36344         {
36345             name: "skipDefaultLibCheck",
36346             type: "boolean",
36347             category: ts.Diagnostics.Advanced_Options,
36348             description: ts.Diagnostics.Deprecated_Use_skipLibCheck_instead_Skip_type_checking_of_default_library_declaration_files
36349         },
36350         {
36351             name: "charset",
36352             type: "string",
36353             category: ts.Diagnostics.Advanced_Options,
36354             description: ts.Diagnostics.The_character_set_of_the_input_files
36355         },
36356         {
36357             name: "emitBOM",
36358             type: "boolean",
36359             affectsEmit: true,
36360             category: ts.Diagnostics.Advanced_Options,
36361             description: ts.Diagnostics.Emit_a_UTF_8_Byte_Order_Mark_BOM_in_the_beginning_of_output_files
36362         },
36363         {
36364             name: "newLine",
36365             type: new ts.Map(ts.getEntries({
36366                 crlf: 0 /* CarriageReturnLineFeed */,
36367                 lf: 1 /* LineFeed */
36368             })),
36369             affectsEmit: true,
36370             paramType: ts.Diagnostics.NEWLINE,
36371             category: ts.Diagnostics.Advanced_Options,
36372             description: ts.Diagnostics.Specify_the_end_of_line_sequence_to_be_used_when_emitting_files_Colon_CRLF_dos_or_LF_unix,
36373         },
36374         {
36375             name: "noErrorTruncation",
36376             type: "boolean",
36377             affectsSemanticDiagnostics: true,
36378             category: ts.Diagnostics.Advanced_Options,
36379             description: ts.Diagnostics.Do_not_truncate_error_messages
36380         },
36381         {
36382             name: "noLib",
36383             type: "boolean",
36384             affectsModuleResolution: true,
36385             category: ts.Diagnostics.Advanced_Options,
36386             description: ts.Diagnostics.Do_not_include_the_default_library_file_lib_d_ts,
36387             // We are not returning a sourceFile for lib file when asked by the program,
36388             // so pass --noLib to avoid reporting a file not found error.
36389             transpileOptionValue: true
36390         },
36391         {
36392             name: "noResolve",
36393             type: "boolean",
36394             affectsModuleResolution: true,
36395             category: ts.Diagnostics.Advanced_Options,
36396             description: ts.Diagnostics.Do_not_add_triple_slash_references_or_imported_modules_to_the_list_of_compiled_files,
36397             // We are not doing a full typecheck, we are not resolving the whole context,
36398             // so pass --noResolve to avoid reporting missing file errors.
36399             transpileOptionValue: true
36400         },
36401         {
36402             name: "stripInternal",
36403             type: "boolean",
36404             affectsEmit: true,
36405             category: ts.Diagnostics.Advanced_Options,
36406             description: ts.Diagnostics.Do_not_emit_declarations_for_code_that_has_an_internal_annotation,
36407         },
36408         {
36409             name: "disableSizeLimit",
36410             type: "boolean",
36411             affectsSourceFile: true,
36412             category: ts.Diagnostics.Advanced_Options,
36413             description: ts.Diagnostics.Disable_size_limitations_on_JavaScript_projects
36414         },
36415         {
36416             name: "disableSourceOfProjectReferenceRedirect",
36417             type: "boolean",
36418             isTSConfigOnly: true,
36419             category: ts.Diagnostics.Advanced_Options,
36420             description: ts.Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
36421         },
36422         {
36423             name: "disableSolutionSearching",
36424             type: "boolean",
36425             isTSConfigOnly: true,
36426             category: ts.Diagnostics.Advanced_Options,
36427             description: ts.Diagnostics.Disable_solution_searching_for_this_project
36428         },
36429         {
36430             name: "disableReferencedProjectLoad",
36431             type: "boolean",
36432             isTSConfigOnly: true,
36433             category: ts.Diagnostics.Advanced_Options,
36434             description: ts.Diagnostics.Disable_loading_referenced_projects
36435         },
36436         {
36437             name: "noImplicitUseStrict",
36438             type: "boolean",
36439             affectsSemanticDiagnostics: true,
36440             category: ts.Diagnostics.Advanced_Options,
36441             description: ts.Diagnostics.Do_not_emit_use_strict_directives_in_module_output
36442         },
36443         {
36444             name: "noEmitHelpers",
36445             type: "boolean",
36446             affectsEmit: true,
36447             category: ts.Diagnostics.Advanced_Options,
36448             description: ts.Diagnostics.Do_not_generate_custom_helper_functions_like_extends_in_compiled_output
36449         },
36450         {
36451             name: "noEmitOnError",
36452             type: "boolean",
36453             affectsEmit: true,
36454             category: ts.Diagnostics.Advanced_Options,
36455             description: ts.Diagnostics.Do_not_emit_outputs_if_any_errors_were_reported,
36456             transpileOptionValue: undefined
36457         },
36458         {
36459             name: "preserveConstEnums",
36460             type: "boolean",
36461             affectsEmit: true,
36462             category: ts.Diagnostics.Advanced_Options,
36463             description: ts.Diagnostics.Do_not_erase_const_enum_declarations_in_generated_code
36464         },
36465         {
36466             name: "declarationDir",
36467             type: "string",
36468             affectsEmit: true,
36469             isFilePath: true,
36470             paramType: ts.Diagnostics.DIRECTORY,
36471             category: ts.Diagnostics.Advanced_Options,
36472             description: ts.Diagnostics.Output_directory_for_generated_declaration_files,
36473             transpileOptionValue: undefined
36474         },
36475         {
36476             name: "skipLibCheck",
36477             type: "boolean",
36478             category: ts.Diagnostics.Advanced_Options,
36479             description: ts.Diagnostics.Skip_type_checking_of_declaration_files,
36480         },
36481         {
36482             name: "allowUnusedLabels",
36483             type: "boolean",
36484             affectsBindDiagnostics: true,
36485             affectsSemanticDiagnostics: true,
36486             category: ts.Diagnostics.Advanced_Options,
36487             description: ts.Diagnostics.Do_not_report_errors_on_unused_labels
36488         },
36489         {
36490             name: "allowUnreachableCode",
36491             type: "boolean",
36492             affectsBindDiagnostics: true,
36493             affectsSemanticDiagnostics: true,
36494             category: ts.Diagnostics.Advanced_Options,
36495             description: ts.Diagnostics.Do_not_report_errors_on_unreachable_code
36496         },
36497         {
36498             name: "suppressExcessPropertyErrors",
36499             type: "boolean",
36500             affectsSemanticDiagnostics: true,
36501             category: ts.Diagnostics.Advanced_Options,
36502             description: ts.Diagnostics.Suppress_excess_property_checks_for_object_literals,
36503         },
36504         {
36505             name: "suppressImplicitAnyIndexErrors",
36506             type: "boolean",
36507             affectsSemanticDiagnostics: true,
36508             category: ts.Diagnostics.Advanced_Options,
36509             description: ts.Diagnostics.Suppress_noImplicitAny_errors_for_indexing_objects_lacking_index_signatures,
36510         },
36511         {
36512             name: "forceConsistentCasingInFileNames",
36513             type: "boolean",
36514             affectsModuleResolution: true,
36515             category: ts.Diagnostics.Advanced_Options,
36516             description: ts.Diagnostics.Disallow_inconsistently_cased_references_to_the_same_file
36517         },
36518         {
36519             name: "maxNodeModuleJsDepth",
36520             type: "number",
36521             affectsModuleResolution: true,
36522             category: ts.Diagnostics.Advanced_Options,
36523             description: ts.Diagnostics.The_maximum_dependency_depth_to_search_under_node_modules_and_load_JavaScript_files
36524         },
36525         {
36526             name: "noStrictGenericChecks",
36527             type: "boolean",
36528             affectsSemanticDiagnostics: true,
36529             category: ts.Diagnostics.Advanced_Options,
36530             description: ts.Diagnostics.Disable_strict_checking_of_generic_signatures_in_function_types,
36531         },
36532         {
36533             name: "useDefineForClassFields",
36534             type: "boolean",
36535             affectsSemanticDiagnostics: true,
36536             affectsEmit: true,
36537             category: ts.Diagnostics.Advanced_Options,
36538             description: ts.Diagnostics.Emit_class_fields_with_Define_instead_of_Set,
36539         },
36540         {
36541             name: "keyofStringsOnly",
36542             type: "boolean",
36543             category: ts.Diagnostics.Advanced_Options,
36544             description: ts.Diagnostics.Resolve_keyof_to_string_valued_property_names_only_no_numbers_or_symbols,
36545         },
36546         {
36547             // A list of plugins to load in the language service
36548             name: "plugins",
36549             type: "list",
36550             isTSConfigOnly: true,
36551             element: {
36552                 name: "plugin",
36553                 type: "object"
36554             },
36555             description: ts.Diagnostics.List_of_language_service_plugins
36556         },
36557     ]);
36558     /* @internal */
36559     ts.semanticDiagnosticsOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsSemanticDiagnostics; });
36560     /* @internal */
36561     ts.affectsEmitOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsEmit; });
36562     /* @internal */
36563     ts.moduleResolutionOptionDeclarations = ts.optionDeclarations.filter(function (option) { return !!option.affectsModuleResolution; });
36564     /* @internal */
36565     ts.sourceFileAffectingCompilerOptions = ts.optionDeclarations.filter(function (option) {
36566         return !!option.affectsSourceFile || !!option.affectsModuleResolution || !!option.affectsBindDiagnostics;
36567     });
36568     /* @internal */
36569     ts.transpileOptionValueCompilerOptions = ts.optionDeclarations.filter(function (option) {
36570         return ts.hasProperty(option, "transpileOptionValue");
36571     });
36572     /* @internal */
36573     ts.buildOpts = __spreadArrays(ts.commonOptionsWithBuild, [
36574         {
36575             name: "verbose",
36576             shortName: "v",
36577             category: ts.Diagnostics.Command_line_Options,
36578             description: ts.Diagnostics.Enable_verbose_logging,
36579             type: "boolean"
36580         },
36581         {
36582             name: "dry",
36583             shortName: "d",
36584             category: ts.Diagnostics.Command_line_Options,
36585             description: ts.Diagnostics.Show_what_would_be_built_or_deleted_if_specified_with_clean,
36586             type: "boolean"
36587         },
36588         {
36589             name: "force",
36590             shortName: "f",
36591             category: ts.Diagnostics.Command_line_Options,
36592             description: ts.Diagnostics.Build_all_projects_including_those_that_appear_to_be_up_to_date,
36593             type: "boolean"
36594         },
36595         {
36596             name: "clean",
36597             category: ts.Diagnostics.Command_line_Options,
36598             description: ts.Diagnostics.Delete_the_outputs_of_all_projects,
36599             type: "boolean"
36600         }
36601     ]);
36602     /* @internal */
36603     ts.typeAcquisitionDeclarations = [
36604         {
36605             /* @deprecated typingOptions.enableAutoDiscovery
36606              * Use typeAcquisition.enable instead.
36607              */
36608             name: "enableAutoDiscovery",
36609             type: "boolean",
36610         },
36611         {
36612             name: "enable",
36613             type: "boolean",
36614         },
36615         {
36616             name: "include",
36617             type: "list",
36618             element: {
36619                 name: "include",
36620                 type: "string"
36621             }
36622         },
36623         {
36624             name: "exclude",
36625             type: "list",
36626             element: {
36627                 name: "exclude",
36628                 type: "string"
36629             }
36630         },
36631         {
36632             name: "disableFilenameBasedTypeAcquisition",
36633             type: "boolean",
36634         },
36635     ];
36636     /*@internal*/
36637     function createOptionNameMap(optionDeclarations) {
36638         var optionsNameMap = new ts.Map();
36639         var shortOptionNames = new ts.Map();
36640         ts.forEach(optionDeclarations, function (option) {
36641             optionsNameMap.set(option.name.toLowerCase(), option);
36642             if (option.shortName) {
36643                 shortOptionNames.set(option.shortName, option.name);
36644             }
36645         });
36646         return { optionsNameMap: optionsNameMap, shortOptionNames: shortOptionNames };
36647     }
36648     ts.createOptionNameMap = createOptionNameMap;
36649     var optionsNameMapCache;
36650     /* @internal */
36651     function getOptionsNameMap() {
36652         return optionsNameMapCache || (optionsNameMapCache = createOptionNameMap(ts.optionDeclarations));
36653     }
36654     ts.getOptionsNameMap = getOptionsNameMap;
36655     /* @internal */
36656     ts.defaultInitCompilerOptions = {
36657         module: ts.ModuleKind.CommonJS,
36658         target: 1 /* ES5 */,
36659         strict: true,
36660         esModuleInterop: true,
36661         forceConsistentCasingInFileNames: true,
36662         skipLibCheck: true
36663     };
36664     /* @internal */
36665     function convertEnableAutoDiscoveryToEnable(typeAcquisition) {
36666         // Convert deprecated typingOptions.enableAutoDiscovery to typeAcquisition.enable
36667         if (typeAcquisition && typeAcquisition.enableAutoDiscovery !== undefined && typeAcquisition.enable === undefined) {
36668             return {
36669                 enable: typeAcquisition.enableAutoDiscovery,
36670                 include: typeAcquisition.include || [],
36671                 exclude: typeAcquisition.exclude || []
36672             };
36673         }
36674         return typeAcquisition;
36675     }
36676     ts.convertEnableAutoDiscoveryToEnable = convertEnableAutoDiscoveryToEnable;
36677     /* @internal */
36678     function createCompilerDiagnosticForInvalidCustomType(opt) {
36679         return createDiagnosticForInvalidCustomType(opt, ts.createCompilerDiagnostic);
36680     }
36681     ts.createCompilerDiagnosticForInvalidCustomType = createCompilerDiagnosticForInvalidCustomType;
36682     function createDiagnosticForInvalidCustomType(opt, createDiagnostic) {
36683         var namesOfType = ts.arrayFrom(opt.type.keys()).map(function (key) { return "'" + key + "'"; }).join(", ");
36684         return createDiagnostic(ts.Diagnostics.Argument_for_0_option_must_be_Colon_1, "--" + opt.name, namesOfType);
36685     }
36686     /* @internal */
36687     function parseCustomTypeOption(opt, value, errors) {
36688         return convertJsonOptionOfCustomType(opt, trimString(value || ""), errors);
36689     }
36690     ts.parseCustomTypeOption = parseCustomTypeOption;
36691     /* @internal */
36692     function parseListTypeOption(opt, value, errors) {
36693         if (value === void 0) { value = ""; }
36694         value = trimString(value);
36695         if (ts.startsWith(value, "-")) {
36696             return undefined;
36697         }
36698         if (value === "") {
36699             return [];
36700         }
36701         var values = value.split(",");
36702         switch (opt.element.type) {
36703             case "number":
36704                 return ts.map(values, parseInt);
36705             case "string":
36706                 return ts.map(values, function (v) { return v || ""; });
36707             default:
36708                 return ts.mapDefined(values, function (v) { return parseCustomTypeOption(opt.element, v, errors); });
36709         }
36710     }
36711     ts.parseListTypeOption = parseListTypeOption;
36712     function getOptionName(option) {
36713         return option.name;
36714     }
36715     function createUnknownOptionError(unknownOption, diagnostics, createDiagnostics, unknownOptionErrorText) {
36716         var possibleOption = ts.getSpellingSuggestion(unknownOption, diagnostics.optionDeclarations, getOptionName);
36717         return possibleOption ?
36718             createDiagnostics(diagnostics.unknownDidYouMeanDiagnostic, unknownOptionErrorText || unknownOption, possibleOption.name) :
36719             createDiagnostics(diagnostics.unknownOptionDiagnostic, unknownOptionErrorText || unknownOption);
36720     }
36721     /*@internal*/
36722     function parseCommandLineWorker(diagnostics, commandLine, readFile) {
36723         var options = {};
36724         var watchOptions;
36725         var fileNames = [];
36726         var errors = [];
36727         parseStrings(commandLine);
36728         return {
36729             options: options,
36730             watchOptions: watchOptions,
36731             fileNames: fileNames,
36732             errors: errors
36733         };
36734         function parseStrings(args) {
36735             var i = 0;
36736             while (i < args.length) {
36737                 var s = args[i];
36738                 i++;
36739                 if (s.charCodeAt(0) === 64 /* at */) {
36740                     parseResponseFile(s.slice(1));
36741                 }
36742                 else if (s.charCodeAt(0) === 45 /* minus */) {
36743                     var inputOptionName = s.slice(s.charCodeAt(1) === 45 /* minus */ ? 2 : 1);
36744                     var opt = getOptionDeclarationFromName(diagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
36745                     if (opt) {
36746                         i = parseOptionValue(args, i, diagnostics, opt, options, errors);
36747                     }
36748                     else {
36749                         var watchOpt = getOptionDeclarationFromName(watchOptionsDidYouMeanDiagnostics.getOptionsNameMap, inputOptionName, /*allowShort*/ true);
36750                         if (watchOpt) {
36751                             i = parseOptionValue(args, i, watchOptionsDidYouMeanDiagnostics, watchOpt, watchOptions || (watchOptions = {}), errors);
36752                         }
36753                         else {
36754                             errors.push(createUnknownOptionError(inputOptionName, diagnostics, ts.createCompilerDiagnostic, s));
36755                         }
36756                     }
36757                 }
36758                 else {
36759                     fileNames.push(s);
36760                 }
36761             }
36762         }
36763         function parseResponseFile(fileName) {
36764             var text = tryReadFile(fileName, readFile || (function (fileName) { return ts.sys.readFile(fileName); }));
36765             if (!ts.isString(text)) {
36766                 errors.push(text);
36767                 return;
36768             }
36769             var args = [];
36770             var pos = 0;
36771             while (true) {
36772                 while (pos < text.length && text.charCodeAt(pos) <= 32 /* space */)
36773                     pos++;
36774                 if (pos >= text.length)
36775                     break;
36776                 var start = pos;
36777                 if (text.charCodeAt(start) === 34 /* doubleQuote */) {
36778                     pos++;
36779                     while (pos < text.length && text.charCodeAt(pos) !== 34 /* doubleQuote */)
36780                         pos++;
36781                     if (pos < text.length) {
36782                         args.push(text.substring(start + 1, pos));
36783                         pos++;
36784                     }
36785                     else {
36786                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unterminated_quoted_string_in_response_file_0, fileName));
36787                     }
36788                 }
36789                 else {
36790                     while (text.charCodeAt(pos) > 32 /* space */)
36791                         pos++;
36792                     args.push(text.substring(start, pos));
36793                 }
36794             }
36795             parseStrings(args);
36796         }
36797     }
36798     ts.parseCommandLineWorker = parseCommandLineWorker;
36799     function parseOptionValue(args, i, diagnostics, opt, options, errors) {
36800         if (opt.isTSConfigOnly) {
36801             var optValue = args[i];
36802             if (optValue === "null") {
36803                 options[opt.name] = undefined;
36804                 i++;
36805             }
36806             else if (opt.type === "boolean") {
36807                 if (optValue === "false") {
36808                     options[opt.name] = false;
36809                     i++;
36810                 }
36811                 else {
36812                     if (optValue === "true")
36813                         i++;
36814                     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));
36815                 }
36816             }
36817             else {
36818                 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));
36819                 if (optValue && !ts.startsWith(optValue, "-"))
36820                     i++;
36821             }
36822         }
36823         else {
36824             // Check to see if no argument was provided (e.g. "--locale" is the last command-line argument).
36825             if (!args[i] && opt.type !== "boolean") {
36826                 errors.push(ts.createCompilerDiagnostic(diagnostics.optionTypeMismatchDiagnostic, opt.name, getCompilerOptionValueTypeString(opt)));
36827             }
36828             if (args[i] !== "null") {
36829                 switch (opt.type) {
36830                     case "number":
36831                         options[opt.name] = parseInt(args[i]);
36832                         i++;
36833                         break;
36834                     case "boolean":
36835                         // boolean flag has optional value true, false, others
36836                         var optValue = args[i];
36837                         options[opt.name] = optValue !== "false";
36838                         // consume next argument as boolean flag value
36839                         if (optValue === "false" || optValue === "true") {
36840                             i++;
36841                         }
36842                         break;
36843                     case "string":
36844                         options[opt.name] = args[i] || "";
36845                         i++;
36846                         break;
36847                     case "list":
36848                         var result = parseListTypeOption(opt, args[i], errors);
36849                         options[opt.name] = result || [];
36850                         if (result) {
36851                             i++;
36852                         }
36853                         break;
36854                     // If not a primitive, the possible types are specified in what is effectively a map of options.
36855                     default:
36856                         options[opt.name] = parseCustomTypeOption(opt, args[i], errors);
36857                         i++;
36858                         break;
36859                 }
36860             }
36861             else {
36862                 options[opt.name] = undefined;
36863                 i++;
36864             }
36865         }
36866         return i;
36867     }
36868     /*@internal*/
36869     ts.compilerOptionsDidYouMeanDiagnostics = {
36870         getOptionsNameMap: getOptionsNameMap,
36871         optionDeclarations: ts.optionDeclarations,
36872         unknownOptionDiagnostic: ts.Diagnostics.Unknown_compiler_option_0,
36873         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_compiler_option_0_Did_you_mean_1,
36874         optionTypeMismatchDiagnostic: ts.Diagnostics.Compiler_option_0_expects_an_argument
36875     };
36876     function parseCommandLine(commandLine, readFile) {
36877         return parseCommandLineWorker(ts.compilerOptionsDidYouMeanDiagnostics, commandLine, readFile);
36878     }
36879     ts.parseCommandLine = parseCommandLine;
36880     /** @internal */
36881     function getOptionFromName(optionName, allowShort) {
36882         return getOptionDeclarationFromName(getOptionsNameMap, optionName, allowShort);
36883     }
36884     ts.getOptionFromName = getOptionFromName;
36885     function getOptionDeclarationFromName(getOptionNameMap, optionName, allowShort) {
36886         if (allowShort === void 0) { allowShort = false; }
36887         optionName = optionName.toLowerCase();
36888         var _a = getOptionNameMap(), optionsNameMap = _a.optionsNameMap, shortOptionNames = _a.shortOptionNames;
36889         // Try to translate short option names to their full equivalents.
36890         if (allowShort) {
36891             var short = shortOptionNames.get(optionName);
36892             if (short !== undefined) {
36893                 optionName = short;
36894             }
36895         }
36896         return optionsNameMap.get(optionName);
36897     }
36898     var buildOptionsNameMapCache;
36899     function getBuildOptionsNameMap() {
36900         return buildOptionsNameMapCache || (buildOptionsNameMapCache = createOptionNameMap(ts.buildOpts));
36901     }
36902     var buildOptionsDidYouMeanDiagnostics = {
36903         getOptionsNameMap: getBuildOptionsNameMap,
36904         optionDeclarations: ts.buildOpts,
36905         unknownOptionDiagnostic: ts.Diagnostics.Unknown_build_option_0,
36906         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_build_option_0_Did_you_mean_1,
36907         optionTypeMismatchDiagnostic: ts.Diagnostics.Build_option_0_requires_a_value_of_type_1
36908     };
36909     /*@internal*/
36910     function parseBuildCommand(args) {
36911         var _a = parseCommandLineWorker(buildOptionsDidYouMeanDiagnostics, args), options = _a.options, watchOptions = _a.watchOptions, projects = _a.fileNames, errors = _a.errors;
36912         var buildOptions = options;
36913         if (projects.length === 0) {
36914             // tsc -b invoked with no extra arguments; act as if invoked with "tsc -b ."
36915             projects.push(".");
36916         }
36917         // Nonsensical combinations
36918         if (buildOptions.clean && buildOptions.force) {
36919             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "force"));
36920         }
36921         if (buildOptions.clean && buildOptions.verbose) {
36922             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "verbose"));
36923         }
36924         if (buildOptions.clean && buildOptions.watch) {
36925             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "clean", "watch"));
36926         }
36927         if (buildOptions.watch && buildOptions.dry) {
36928             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Options_0_and_1_cannot_be_combined, "watch", "dry"));
36929         }
36930         return { buildOptions: buildOptions, watchOptions: watchOptions, projects: projects, errors: errors };
36931     }
36932     ts.parseBuildCommand = parseBuildCommand;
36933     /* @internal */
36934     function getDiagnosticText(_message) {
36935         var _args = [];
36936         for (var _i = 1; _i < arguments.length; _i++) {
36937             _args[_i - 1] = arguments[_i];
36938         }
36939         var diagnostic = ts.createCompilerDiagnostic.apply(undefined, arguments);
36940         return diagnostic.messageText;
36941     }
36942     ts.getDiagnosticText = getDiagnosticText;
36943     /**
36944      * Reads the config file, reports errors if any and exits if the config file cannot be found
36945      */
36946     function getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, extendedConfigCache, watchOptionsToExtend, extraFileExtensions) {
36947         var configFileText = tryReadFile(configFileName, function (fileName) { return host.readFile(fileName); });
36948         if (!ts.isString(configFileText)) {
36949             host.onUnRecoverableConfigFileDiagnostic(configFileText);
36950             return undefined;
36951         }
36952         var result = ts.parseJsonText(configFileName, configFileText);
36953         var cwd = host.getCurrentDirectory();
36954         result.path = ts.toPath(configFileName, cwd, ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames));
36955         result.resolvedPath = result.path;
36956         result.originalFileName = result.fileName;
36957         return parseJsonSourceFileConfigFileContent(result, host, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), cwd), optionsToExtend, ts.getNormalizedAbsolutePath(configFileName, cwd), 
36958         /*resolutionStack*/ undefined, extraFileExtensions, extendedConfigCache, watchOptionsToExtend);
36959     }
36960     ts.getParsedCommandLineOfConfigFile = getParsedCommandLineOfConfigFile;
36961     /**
36962      * Read tsconfig.json file
36963      * @param fileName The path to the config file
36964      */
36965     function readConfigFile(fileName, readFile) {
36966         var textOrDiagnostic = tryReadFile(fileName, readFile);
36967         return ts.isString(textOrDiagnostic) ? parseConfigFileTextToJson(fileName, textOrDiagnostic) : { config: {}, error: textOrDiagnostic };
36968     }
36969     ts.readConfigFile = readConfigFile;
36970     /**
36971      * Parse the text of the tsconfig.json file
36972      * @param fileName The path to the config file
36973      * @param jsonText The text of the config file
36974      */
36975     function parseConfigFileTextToJson(fileName, jsonText) {
36976         var jsonSourceFile = ts.parseJsonText(fileName, jsonText);
36977         return {
36978             config: convertToObject(jsonSourceFile, jsonSourceFile.parseDiagnostics),
36979             error: jsonSourceFile.parseDiagnostics.length ? jsonSourceFile.parseDiagnostics[0] : undefined
36980         };
36981     }
36982     ts.parseConfigFileTextToJson = parseConfigFileTextToJson;
36983     /**
36984      * Read tsconfig.json file
36985      * @param fileName The path to the config file
36986      */
36987     function readJsonConfigFile(fileName, readFile) {
36988         var textOrDiagnostic = tryReadFile(fileName, readFile);
36989         return ts.isString(textOrDiagnostic) ? ts.parseJsonText(fileName, textOrDiagnostic) : { fileName: fileName, parseDiagnostics: [textOrDiagnostic] };
36990     }
36991     ts.readJsonConfigFile = readJsonConfigFile;
36992     /*@internal*/
36993     function tryReadFile(fileName, readFile) {
36994         var text;
36995         try {
36996             text = readFile(fileName);
36997         }
36998         catch (e) {
36999             return ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0_Colon_1, fileName, e.message);
37000         }
37001         return text === undefined ? ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_read_file_0, fileName) : text;
37002     }
37003     ts.tryReadFile = tryReadFile;
37004     function commandLineOptionsToMap(options) {
37005         return ts.arrayToMap(options, getOptionName);
37006     }
37007     var typeAcquisitionDidYouMeanDiagnostics = {
37008         optionDeclarations: ts.typeAcquisitionDeclarations,
37009         unknownOptionDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0,
37010         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_type_acquisition_option_0_Did_you_mean_1,
37011     };
37012     var watchOptionsNameMapCache;
37013     function getWatchOptionsNameMap() {
37014         return watchOptionsNameMapCache || (watchOptionsNameMapCache = createOptionNameMap(ts.optionsForWatch));
37015     }
37016     var watchOptionsDidYouMeanDiagnostics = {
37017         getOptionsNameMap: getWatchOptionsNameMap,
37018         optionDeclarations: ts.optionsForWatch,
37019         unknownOptionDiagnostic: ts.Diagnostics.Unknown_watch_option_0,
37020         unknownDidYouMeanDiagnostic: ts.Diagnostics.Unknown_watch_option_0_Did_you_mean_1,
37021         optionTypeMismatchDiagnostic: ts.Diagnostics.Watch_option_0_requires_a_value_of_type_1
37022     };
37023     var commandLineCompilerOptionsMapCache;
37024     function getCommandLineCompilerOptionsMap() {
37025         return commandLineCompilerOptionsMapCache || (commandLineCompilerOptionsMapCache = commandLineOptionsToMap(ts.optionDeclarations));
37026     }
37027     var commandLineWatchOptionsMapCache;
37028     function getCommandLineWatchOptionsMap() {
37029         return commandLineWatchOptionsMapCache || (commandLineWatchOptionsMapCache = commandLineOptionsToMap(ts.optionsForWatch));
37030     }
37031     var commandLineTypeAcquisitionMapCache;
37032     function getCommandLineTypeAcquisitionMap() {
37033         return commandLineTypeAcquisitionMapCache || (commandLineTypeAcquisitionMapCache = commandLineOptionsToMap(ts.typeAcquisitionDeclarations));
37034     }
37035     var _tsconfigRootOptions;
37036     function getTsconfigRootOptionsMap() {
37037         if (_tsconfigRootOptions === undefined) {
37038             _tsconfigRootOptions = {
37039                 name: undefined,
37040                 type: "object",
37041                 elementOptions: commandLineOptionsToMap([
37042                     {
37043                         name: "compilerOptions",
37044                         type: "object",
37045                         elementOptions: getCommandLineCompilerOptionsMap(),
37046                         extraKeyDiagnostics: ts.compilerOptionsDidYouMeanDiagnostics,
37047                     },
37048                     {
37049                         name: "watchOptions",
37050                         type: "object",
37051                         elementOptions: getCommandLineWatchOptionsMap(),
37052                         extraKeyDiagnostics: watchOptionsDidYouMeanDiagnostics,
37053                     },
37054                     {
37055                         name: "typingOptions",
37056                         type: "object",
37057                         elementOptions: getCommandLineTypeAcquisitionMap(),
37058                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics,
37059                     },
37060                     {
37061                         name: "typeAcquisition",
37062                         type: "object",
37063                         elementOptions: getCommandLineTypeAcquisitionMap(),
37064                         extraKeyDiagnostics: typeAcquisitionDidYouMeanDiagnostics
37065                     },
37066                     {
37067                         name: "extends",
37068                         type: "string"
37069                     },
37070                     {
37071                         name: "references",
37072                         type: "list",
37073                         element: {
37074                             name: "references",
37075                             type: "object"
37076                         }
37077                     },
37078                     {
37079                         name: "files",
37080                         type: "list",
37081                         element: {
37082                             name: "files",
37083                             type: "string"
37084                         }
37085                     },
37086                     {
37087                         name: "include",
37088                         type: "list",
37089                         element: {
37090                             name: "include",
37091                             type: "string"
37092                         }
37093                     },
37094                     {
37095                         name: "exclude",
37096                         type: "list",
37097                         element: {
37098                             name: "exclude",
37099                             type: "string"
37100                         }
37101                     },
37102                     ts.compileOnSaveCommandLineOption
37103                 ])
37104             };
37105         }
37106         return _tsconfigRootOptions;
37107     }
37108     /**
37109      * Convert the json syntax tree into the json value
37110      */
37111     function convertToObject(sourceFile, errors) {
37112         return convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, /*knownRootOptions*/ undefined, /*jsonConversionNotifier*/ undefined);
37113     }
37114     ts.convertToObject = convertToObject;
37115     /**
37116      * Convert the json syntax tree into the json value and report errors
37117      * This returns the json value (apart from checking errors) only if returnValue provided is true.
37118      * Otherwise it just checks the errors and returns undefined
37119      */
37120     /*@internal*/
37121     function convertToObjectWorker(sourceFile, errors, returnValue, knownRootOptions, jsonConversionNotifier) {
37122         if (!sourceFile.statements.length) {
37123             return returnValue ? {} : undefined;
37124         }
37125         return convertPropertyValueToJson(sourceFile.statements[0].expression, knownRootOptions);
37126         function isRootOptionMap(knownOptions) {
37127             return knownRootOptions && knownRootOptions.elementOptions === knownOptions;
37128         }
37129         function convertObjectLiteralExpressionToJson(node, knownOptions, extraKeyDiagnostics, parentOption) {
37130             var result = returnValue ? {} : undefined;
37131             var _loop_4 = function (element) {
37132                 if (element.kind !== 288 /* PropertyAssignment */) {
37133                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element, ts.Diagnostics.Property_assignment_expected));
37134                     return "continue";
37135                 }
37136                 if (element.questionToken) {
37137                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.questionToken, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
37138                 }
37139                 if (!isDoubleQuotedString(element.name)) {
37140                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, ts.Diagnostics.String_literal_with_double_quotes_expected));
37141                 }
37142                 var textOfKey = ts.isComputedNonLiteralName(element.name) ? undefined : ts.getTextOfPropertyName(element.name);
37143                 var keyText = textOfKey && ts.unescapeLeadingUnderscores(textOfKey);
37144                 var option = keyText && knownOptions ? knownOptions.get(keyText) : undefined;
37145                 if (keyText && extraKeyDiagnostics && !option) {
37146                     if (knownOptions) {
37147                         errors.push(createUnknownOptionError(keyText, extraKeyDiagnostics, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, message, arg0, arg1); }));
37148                     }
37149                     else {
37150                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, element.name, extraKeyDiagnostics.unknownOptionDiagnostic, keyText));
37151                     }
37152                 }
37153                 var value = convertPropertyValueToJson(element.initializer, option);
37154                 if (typeof keyText !== "undefined") {
37155                     if (returnValue) {
37156                         result[keyText] = value;
37157                     }
37158                     // Notify key value set, if user asked for it
37159                     if (jsonConversionNotifier &&
37160                         // Current callbacks are only on known parent option or if we are setting values in the root
37161                         (parentOption || isRootOptionMap(knownOptions))) {
37162                         var isValidOptionValue = isCompilerOptionsValue(option, value);
37163                         if (parentOption) {
37164                             if (isValidOptionValue) {
37165                                 // Notify option set in the parent if its a valid option value
37166                                 jsonConversionNotifier.onSetValidOptionKeyValueInParent(parentOption, option, value);
37167                             }
37168                         }
37169                         else if (isRootOptionMap(knownOptions)) {
37170                             if (isValidOptionValue) {
37171                                 // Notify about the valid root key value being set
37172                                 jsonConversionNotifier.onSetValidOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
37173                             }
37174                             else if (!option) {
37175                                 // Notify about the unknown root key value being set
37176                                 jsonConversionNotifier.onSetUnknownOptionKeyValueInRoot(keyText, element.name, value, element.initializer);
37177                             }
37178                         }
37179                     }
37180                 }
37181             };
37182             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
37183                 var element = _a[_i];
37184                 _loop_4(element);
37185             }
37186             return result;
37187         }
37188         function convertArrayLiteralExpressionToJson(elements, elementOption) {
37189             if (!returnValue) {
37190                 return elements.forEach(function (element) { return convertPropertyValueToJson(element, elementOption); });
37191             }
37192             // Filter out invalid values
37193             return ts.filter(elements.map(function (element) { return convertPropertyValueToJson(element, elementOption); }), function (v) { return v !== undefined; });
37194         }
37195         function convertPropertyValueToJson(valueExpression, option) {
37196             switch (valueExpression.kind) {
37197                 case 109 /* TrueKeyword */:
37198                     reportInvalidOptionValue(option && option.type !== "boolean");
37199                     return true;
37200                 case 94 /* FalseKeyword */:
37201                     reportInvalidOptionValue(option && option.type !== "boolean");
37202                     return false;
37203                 case 103 /* NullKeyword */:
37204                     reportInvalidOptionValue(option && option.name === "extends"); // "extends" is the only option we don't allow null/undefined for
37205                     return null; // eslint-disable-line no-null/no-null
37206                 case 10 /* StringLiteral */:
37207                     if (!isDoubleQuotedString(valueExpression)) {
37208                         errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.String_literal_with_double_quotes_expected));
37209                     }
37210                     reportInvalidOptionValue(option && (ts.isString(option.type) && option.type !== "string"));
37211                     var text = valueExpression.text;
37212                     if (option && !ts.isString(option.type)) {
37213                         var customOption = option;
37214                         // Validate custom option type
37215                         if (!customOption.type.has(text.toLowerCase())) {
37216                             errors.push(createDiagnosticForInvalidCustomType(customOption, function (message, arg0, arg1) { return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, message, arg0, arg1); }));
37217                         }
37218                     }
37219                     return text;
37220                 case 8 /* NumericLiteral */:
37221                     reportInvalidOptionValue(option && option.type !== "number");
37222                     return Number(valueExpression.text);
37223                 case 214 /* PrefixUnaryExpression */:
37224                     if (valueExpression.operator !== 40 /* MinusToken */ || valueExpression.operand.kind !== 8 /* NumericLiteral */) {
37225                         break; // not valid JSON syntax
37226                     }
37227                     reportInvalidOptionValue(option && option.type !== "number");
37228                     return -Number(valueExpression.operand.text);
37229                 case 200 /* ObjectLiteralExpression */:
37230                     reportInvalidOptionValue(option && option.type !== "object");
37231                     var objectLiteralExpression = valueExpression;
37232                     // Currently having element option declaration in the tsconfig with type "object"
37233                     // determines if it needs onSetValidOptionKeyValueInParent callback or not
37234                     // At moment there are only "compilerOptions", "typeAcquisition" and "typingOptions"
37235                     // that satifies it and need it to modify options set in them (for normalizing file paths)
37236                     // vs what we set in the json
37237                     // If need arises, we can modify this interface and callbacks as needed
37238                     if (option) {
37239                         var _a = option, elementOptions = _a.elementOptions, extraKeyDiagnostics = _a.extraKeyDiagnostics, optionName = _a.name;
37240                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, elementOptions, extraKeyDiagnostics, optionName);
37241                     }
37242                     else {
37243                         return convertObjectLiteralExpressionToJson(objectLiteralExpression, /* knownOptions*/ undefined, 
37244                         /*extraKeyDiagnosticMessage */ undefined, /*parentOption*/ undefined);
37245                     }
37246                 case 199 /* ArrayLiteralExpression */:
37247                     reportInvalidOptionValue(option && option.type !== "list");
37248                     return convertArrayLiteralExpressionToJson(valueExpression.elements, option && option.element);
37249             }
37250             // Not in expected format
37251             if (option) {
37252                 reportInvalidOptionValue(/*isError*/ true);
37253             }
37254             else {
37255                 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));
37256             }
37257             return undefined;
37258             function reportInvalidOptionValue(isError) {
37259                 if (isError) {
37260                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, valueExpression, ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, option.name, getCompilerOptionValueTypeString(option)));
37261                 }
37262             }
37263         }
37264         function isDoubleQuotedString(node) {
37265             return ts.isStringLiteral(node) && ts.isStringDoubleQuoted(node, sourceFile);
37266         }
37267     }
37268     ts.convertToObjectWorker = convertToObjectWorker;
37269     function getCompilerOptionValueTypeString(option) {
37270         return option.type === "list" ?
37271             "Array" :
37272             ts.isString(option.type) ? option.type : "string";
37273     }
37274     function isCompilerOptionsValue(option, value) {
37275         if (option) {
37276             if (isNullOrUndefined(value))
37277                 return true; // All options are undefinable/nullable
37278             if (option.type === "list") {
37279                 return ts.isArray(value);
37280             }
37281             var expectedType = ts.isString(option.type) ? option.type : "string";
37282             return typeof value === expectedType;
37283         }
37284         return false;
37285     }
37286     /**
37287      * Generate an uncommented, complete tsconfig for use with "--showConfig"
37288      * @param configParseResult options to be generated into tsconfig.json
37289      * @param configFileName name of the parsed config file - output paths will be generated relative to this
37290      * @param host provides current directory and case sensitivity services
37291      */
37292     /** @internal */
37293     function convertToTSConfig(configParseResult, configFileName, host) {
37294         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
37295         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); });
37296         var optionMap = serializeCompilerOptions(configParseResult.options, { configFilePath: ts.getNormalizedAbsolutePath(configFileName, host.getCurrentDirectory()), useCaseSensitiveFileNames: host.useCaseSensitiveFileNames });
37297         var watchOptionMap = configParseResult.watchOptions && serializeWatchOptions(configParseResult.watchOptions);
37298         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 ? {
37299             include: filterSameAsDefaultInclude(configParseResult.configFileSpecs.validatedIncludeSpecs),
37300             exclude: configParseResult.configFileSpecs.validatedExcludeSpecs
37301         } : {})), { compileOnSave: !!configParseResult.compileOnSave ? true : undefined });
37302         return config;
37303     }
37304     ts.convertToTSConfig = convertToTSConfig;
37305     function optionMapToObject(optionMap) {
37306         return __assign({}, ts.arrayFrom(optionMap.entries()).reduce(function (prev, cur) {
37307             var _a;
37308             return (__assign(__assign({}, prev), (_a = {}, _a[cur[0]] = cur[1], _a)));
37309         }, {}));
37310     }
37311     function filterSameAsDefaultInclude(specs) {
37312         if (!ts.length(specs))
37313             return undefined;
37314         if (ts.length(specs) !== 1)
37315             return specs;
37316         if (specs[0] === "**/*")
37317             return undefined;
37318         return specs;
37319     }
37320     function matchesSpecs(path, includeSpecs, excludeSpecs, host) {
37321         if (!includeSpecs)
37322             return function (_) { return true; };
37323         var patterns = ts.getFileMatcherPatterns(path, excludeSpecs, includeSpecs, host.useCaseSensitiveFileNames, host.getCurrentDirectory());
37324         var excludeRe = patterns.excludePattern && ts.getRegexFromPattern(patterns.excludePattern, host.useCaseSensitiveFileNames);
37325         var includeRe = patterns.includeFilePattern && ts.getRegexFromPattern(patterns.includeFilePattern, host.useCaseSensitiveFileNames);
37326         if (includeRe) {
37327             if (excludeRe) {
37328                 return function (path) { return !(includeRe.test(path) && !excludeRe.test(path)); };
37329             }
37330             return function (path) { return !includeRe.test(path); };
37331         }
37332         if (excludeRe) {
37333             return function (path) { return excludeRe.test(path); };
37334         }
37335         return function (_) { return true; };
37336     }
37337     function getCustomTypeMapOfCommandLineOption(optionDefinition) {
37338         if (optionDefinition.type === "string" || optionDefinition.type === "number" || optionDefinition.type === "boolean" || optionDefinition.type === "object") {
37339             // this is of a type CommandLineOptionOfPrimitiveType
37340             return undefined;
37341         }
37342         else if (optionDefinition.type === "list") {
37343             return getCustomTypeMapOfCommandLineOption(optionDefinition.element);
37344         }
37345         else {
37346             return optionDefinition.type;
37347         }
37348     }
37349     function getNameOfCompilerOptionValue(value, customTypeMap) {
37350         // There is a typeMap associated with this command-line option so use it to map value back to its name
37351         return ts.forEachEntry(customTypeMap, function (mapValue, key) {
37352             if (mapValue === value) {
37353                 return key;
37354             }
37355         });
37356     }
37357     function serializeCompilerOptions(options, pathOptions) {
37358         return serializeOptionBaseObject(options, getOptionsNameMap(), pathOptions);
37359     }
37360     function serializeWatchOptions(options) {
37361         return serializeOptionBaseObject(options, getWatchOptionsNameMap());
37362     }
37363     function serializeOptionBaseObject(options, _a, pathOptions) {
37364         var optionsNameMap = _a.optionsNameMap;
37365         var result = new ts.Map();
37366         var getCanonicalFileName = pathOptions && ts.createGetCanonicalFileName(pathOptions.useCaseSensitiveFileNames);
37367         var _loop_5 = function (name) {
37368             if (ts.hasProperty(options, name)) {
37369                 // tsconfig only options cannot be specified via command line,
37370                 // so we can assume that only types that can appear here string | number | boolean
37371                 if (optionsNameMap.has(name) && optionsNameMap.get(name).category === ts.Diagnostics.Command_line_Options) {
37372                     return "continue";
37373                 }
37374                 var value = options[name];
37375                 var optionDefinition = optionsNameMap.get(name.toLowerCase());
37376                 if (optionDefinition) {
37377                     var customTypeMap_1 = getCustomTypeMapOfCommandLineOption(optionDefinition);
37378                     if (!customTypeMap_1) {
37379                         // There is no map associated with this compiler option then use the value as-is
37380                         // This is the case if the value is expect to be string, number, boolean or list of string
37381                         if (pathOptions && optionDefinition.isFilePath) {
37382                             result.set(name, ts.getRelativePathFromFile(pathOptions.configFilePath, ts.getNormalizedAbsolutePath(value, ts.getDirectoryPath(pathOptions.configFilePath)), getCanonicalFileName));
37383                         }
37384                         else {
37385                             result.set(name, value);
37386                         }
37387                     }
37388                     else {
37389                         if (optionDefinition.type === "list") {
37390                             result.set(name, value.map(function (element) { return getNameOfCompilerOptionValue(element, customTypeMap_1); })); // TODO: GH#18217
37391                         }
37392                         else {
37393                             // There is a typeMap associated with this command-line option so use it to map value back to its name
37394                             result.set(name, getNameOfCompilerOptionValue(value, customTypeMap_1));
37395                         }
37396                     }
37397                 }
37398             }
37399         };
37400         for (var name in options) {
37401             _loop_5(name);
37402         }
37403         return result;
37404     }
37405     /**
37406      * Generate tsconfig configuration when running command line "--init"
37407      * @param options commandlineOptions to be generated into tsconfig.json
37408      * @param fileNames array of filenames to be generated into tsconfig.json
37409      */
37410     /* @internal */
37411     function generateTSConfig(options, fileNames, newLine) {
37412         var compilerOptions = ts.extend(options, ts.defaultInitCompilerOptions);
37413         var compilerOptionsMap = serializeCompilerOptions(compilerOptions);
37414         return writeConfigurations();
37415         function getDefaultValueForOption(option) {
37416             switch (option.type) {
37417                 case "number":
37418                     return 1;
37419                 case "boolean":
37420                     return true;
37421                 case "string":
37422                     return option.isFilePath ? "./" : "";
37423                 case "list":
37424                     return [];
37425                 case "object":
37426                     return {};
37427                 default:
37428                     var iterResult = option.type.keys().next();
37429                     if (!iterResult.done)
37430                         return iterResult.value;
37431                     return ts.Debug.fail("Expected 'option.type' to have entries.");
37432             }
37433         }
37434         function makePadding(paddingLength) {
37435             return Array(paddingLength + 1).join(" ");
37436         }
37437         function isAllowedOption(_a) {
37438             var category = _a.category, name = _a.name;
37439             // Skip options which do not have a category or have category `Command_line_Options`
37440             // Exclude all possible `Advanced_Options` in tsconfig.json which were NOT defined in command line
37441             return category !== undefined
37442                 && category !== ts.Diagnostics.Command_line_Options
37443                 && (category !== ts.Diagnostics.Advanced_Options || compilerOptionsMap.has(name));
37444         }
37445         function writeConfigurations() {
37446             // Filter applicable options to place in the file
37447             var categorizedOptions = ts.createMultiMap();
37448             for (var _i = 0, optionDeclarations_1 = ts.optionDeclarations; _i < optionDeclarations_1.length; _i++) {
37449                 var option = optionDeclarations_1[_i];
37450                 var category = option.category;
37451                 if (isAllowedOption(option)) {
37452                     categorizedOptions.add(ts.getLocaleSpecificMessage(category), option);
37453                 }
37454             }
37455             // Serialize all options and their descriptions
37456             var marginLength = 0;
37457             var seenKnownKeys = 0;
37458             var entries = [];
37459             categorizedOptions.forEach(function (options, category) {
37460                 if (entries.length !== 0) {
37461                     entries.push({ value: "" });
37462                 }
37463                 entries.push({ value: "/* " + category + " */" });
37464                 for (var _i = 0, options_1 = options; _i < options_1.length; _i++) {
37465                     var option = options_1[_i];
37466                     var optionName = void 0;
37467                     if (compilerOptionsMap.has(option.name)) {
37468                         optionName = "\"" + option.name + "\": " + JSON.stringify(compilerOptionsMap.get(option.name)) + ((seenKnownKeys += 1) === compilerOptionsMap.size ? "" : ",");
37469                     }
37470                     else {
37471                         optionName = "// \"" + option.name + "\": " + JSON.stringify(getDefaultValueForOption(option)) + ",";
37472                     }
37473                     entries.push({
37474                         value: optionName,
37475                         description: "/* " + (option.description && ts.getLocaleSpecificMessage(option.description) || option.name) + " */"
37476                     });
37477                     marginLength = Math.max(optionName.length, marginLength);
37478                 }
37479             });
37480             // Write the output
37481             var tab = makePadding(2);
37482             var result = [];
37483             result.push("{");
37484             result.push(tab + "\"compilerOptions\": {");
37485             result.push("" + tab + tab + "/* " + ts.getLocaleSpecificMessage(ts.Diagnostics.Visit_https_Colon_Slash_Slashaka_ms_Slashtsconfig_json_to_read_more_about_this_file) + " */");
37486             result.push("");
37487             // Print out each row, aligning all the descriptions on the same column.
37488             for (var _a = 0, entries_2 = entries; _a < entries_2.length; _a++) {
37489                 var entry = entries_2[_a];
37490                 var value = entry.value, _b = entry.description, description = _b === void 0 ? "" : _b;
37491                 result.push(value && "" + tab + tab + value + (description && (makePadding(marginLength - value.length + 2) + description)));
37492             }
37493             if (fileNames.length) {
37494                 result.push(tab + "},");
37495                 result.push(tab + "\"files\": [");
37496                 for (var i = 0; i < fileNames.length; i++) {
37497                     result.push("" + tab + tab + JSON.stringify(fileNames[i]) + (i === fileNames.length - 1 ? "" : ","));
37498                 }
37499                 result.push(tab + "]");
37500             }
37501             else {
37502                 result.push(tab + "}");
37503             }
37504             result.push("}");
37505             return result.join(newLine) + newLine;
37506         }
37507     }
37508     ts.generateTSConfig = generateTSConfig;
37509     /* @internal */
37510     function convertToOptionsWithAbsolutePaths(options, toAbsolutePath) {
37511         var result = {};
37512         var optionsNameMap = getOptionsNameMap().optionsNameMap;
37513         for (var name in options) {
37514             if (ts.hasProperty(options, name)) {
37515                 result[name] = convertToOptionValueWithAbsolutePaths(optionsNameMap.get(name.toLowerCase()), options[name], toAbsolutePath);
37516             }
37517         }
37518         if (result.configFilePath) {
37519             result.configFilePath = toAbsolutePath(result.configFilePath);
37520         }
37521         return result;
37522     }
37523     ts.convertToOptionsWithAbsolutePaths = convertToOptionsWithAbsolutePaths;
37524     function convertToOptionValueWithAbsolutePaths(option, value, toAbsolutePath) {
37525         if (option && !isNullOrUndefined(value)) {
37526             if (option.type === "list") {
37527                 var values = value;
37528                 if (option.element.isFilePath && values.length) {
37529                     return values.map(toAbsolutePath);
37530                 }
37531             }
37532             else if (option.isFilePath) {
37533                 return toAbsolutePath(value);
37534             }
37535         }
37536         return value;
37537     }
37538     /**
37539      * Parse the contents of a config file (tsconfig.json).
37540      * @param json The contents of the config file to parse
37541      * @param host Instance of ParseConfigHost used to enumerate files in folder.
37542      * @param basePath A root directory to resolve relative path entries in the config
37543      *    file to. e.g. outDir
37544      */
37545     function parseJsonConfigFileContent(json, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
37546         return parseJsonConfigFileContentWorker(json, /*sourceFile*/ undefined, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
37547     }
37548     ts.parseJsonConfigFileContent = parseJsonConfigFileContent;
37549     /**
37550      * Parse the contents of a config file (tsconfig.json).
37551      * @param jsonNode The contents of the config file to parse
37552      * @param host Instance of ParseConfigHost used to enumerate files in folder.
37553      * @param basePath A root directory to resolve relative path entries in the config
37554      *    file to. e.g. outDir
37555      */
37556     function parseJsonSourceFileConfigFileContent(sourceFile, host, basePath, existingOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache, existingWatchOptions) {
37557         return parseJsonConfigFileContentWorker(/*json*/ undefined, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache);
37558     }
37559     ts.parseJsonSourceFileConfigFileContent = parseJsonSourceFileConfigFileContent;
37560     /*@internal*/
37561     function setConfigFileInOptions(options, configFile) {
37562         if (configFile) {
37563             Object.defineProperty(options, "configFile", { enumerable: false, writable: false, value: configFile });
37564         }
37565     }
37566     ts.setConfigFileInOptions = setConfigFileInOptions;
37567     function isNullOrUndefined(x) {
37568         return x === undefined || x === null; // eslint-disable-line no-null/no-null
37569     }
37570     function directoryOfCombinedPath(fileName, basePath) {
37571         // Use the `getNormalizedAbsolutePath` function to avoid canonicalizing the path, as it must remain noncanonical
37572         // until consistent casing errors are reported
37573         return ts.getDirectoryPath(ts.getNormalizedAbsolutePath(fileName, basePath));
37574     }
37575     /**
37576      * Parse the contents of a config file from json or json source file (tsconfig.json).
37577      * @param json The contents of the config file to parse
37578      * @param sourceFile sourceFile corresponding to the Json
37579      * @param host Instance of ParseConfigHost used to enumerate files in folder.
37580      * @param basePath A root directory to resolve relative path entries in the config
37581      *    file to. e.g. outDir
37582      * @param resolutionStack Only present for backwards-compatibility. Should be empty.
37583      */
37584     function parseJsonConfigFileContentWorker(json, sourceFile, host, basePath, existingOptions, existingWatchOptions, configFileName, resolutionStack, extraFileExtensions, extendedConfigCache) {
37585         if (existingOptions === void 0) { existingOptions = {}; }
37586         if (resolutionStack === void 0) { resolutionStack = []; }
37587         if (extraFileExtensions === void 0) { extraFileExtensions = []; }
37588         ts.Debug.assert((json === undefined && sourceFile !== undefined) || (json !== undefined && sourceFile === undefined));
37589         var errors = [];
37590         var parsedConfig = parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache);
37591         var raw = parsedConfig.raw;
37592         var options = ts.extend(existingOptions, parsedConfig.options || {});
37593         var watchOptions = existingWatchOptions && parsedConfig.watchOptions ?
37594             ts.extend(existingWatchOptions, parsedConfig.watchOptions) :
37595             parsedConfig.watchOptions || existingWatchOptions;
37596         options.configFilePath = configFileName && ts.normalizeSlashes(configFileName);
37597         setConfigFileInOptions(options, sourceFile);
37598         var projectReferences;
37599         var _a = getFileNames(), fileNames = _a.fileNames, wildcardDirectories = _a.wildcardDirectories, spec = _a.spec;
37600         return {
37601             options: options,
37602             watchOptions: watchOptions,
37603             fileNames: fileNames,
37604             projectReferences: projectReferences,
37605             typeAcquisition: parsedConfig.typeAcquisition || getDefaultTypeAcquisition(),
37606             raw: raw,
37607             errors: errors,
37608             wildcardDirectories: wildcardDirectories,
37609             compileOnSave: !!raw.compileOnSave,
37610             configFileSpecs: spec
37611         };
37612         function getFileNames() {
37613             var referencesOfRaw = getPropFromRaw("references", function (element) { return typeof element === "object"; }, "object");
37614             if (ts.isArray(referencesOfRaw)) {
37615                 for (var _i = 0, referencesOfRaw_1 = referencesOfRaw; _i < referencesOfRaw_1.length; _i++) {
37616                     var ref = referencesOfRaw_1[_i];
37617                     if (typeof ref.path !== "string") {
37618                         createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "reference.path", "string");
37619                     }
37620                     else {
37621                         (projectReferences || (projectReferences = [])).push({
37622                             path: ts.getNormalizedAbsolutePath(ref.path, basePath),
37623                             originalPath: ref.path,
37624                             prepend: ref.prepend,
37625                             circular: ref.circular
37626                         });
37627                     }
37628                 }
37629             }
37630             var filesSpecs = toPropValue(getSpecsFromRaw("files"));
37631             if (filesSpecs) {
37632                 var hasZeroOrNoReferences = referencesOfRaw === "no-prop" || ts.isArray(referencesOfRaw) && referencesOfRaw.length === 0;
37633                 var hasExtends = ts.hasProperty(raw, "extends");
37634                 if (filesSpecs.length === 0 && hasZeroOrNoReferences && !hasExtends) {
37635                     if (sourceFile) {
37636                         var fileName = configFileName || "tsconfig.json";
37637                         var diagnosticMessage = ts.Diagnostics.The_files_list_in_config_file_0_is_empty;
37638                         var nodeValue = ts.firstDefined(ts.getTsConfigPropArray(sourceFile, "files"), function (property) { return property.initializer; });
37639                         var error = nodeValue
37640                             ? ts.createDiagnosticForNodeInSourceFile(sourceFile, nodeValue, diagnosticMessage, fileName)
37641                             : ts.createCompilerDiagnostic(diagnosticMessage, fileName);
37642                         errors.push(error);
37643                     }
37644                     else {
37645                         createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.The_files_list_in_config_file_0_is_empty, configFileName || "tsconfig.json");
37646                     }
37647                 }
37648             }
37649             var includeSpecs = toPropValue(getSpecsFromRaw("include"));
37650             var excludeOfRaw = getSpecsFromRaw("exclude");
37651             var excludeSpecs = toPropValue(excludeOfRaw);
37652             if (excludeOfRaw === "no-prop" && raw.compilerOptions) {
37653                 var outDir = raw.compilerOptions.outDir;
37654                 var declarationDir = raw.compilerOptions.declarationDir;
37655                 if (outDir || declarationDir) {
37656                     excludeSpecs = [outDir, declarationDir].filter(function (d) { return !!d; });
37657                 }
37658             }
37659             if (filesSpecs === undefined && includeSpecs === undefined) {
37660                 includeSpecs = ["**/*"];
37661             }
37662             var result = matchFileNames(filesSpecs, includeSpecs, excludeSpecs, configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath, options, host, errors, extraFileExtensions, sourceFile);
37663             if (shouldReportNoInputFiles(result, canJsonReportNoInputFiles(raw), resolutionStack)) {
37664                 errors.push(getErrorForNoInputFiles(result.spec, configFileName));
37665             }
37666             return result;
37667         }
37668         function toPropValue(specResult) {
37669             return ts.isArray(specResult) ? specResult : undefined;
37670         }
37671         function getSpecsFromRaw(prop) {
37672             return getPropFromRaw(prop, ts.isString, "string");
37673         }
37674         function getPropFromRaw(prop, validateElement, elementTypeName) {
37675             if (ts.hasProperty(raw, prop) && !isNullOrUndefined(raw[prop])) {
37676                 if (ts.isArray(raw[prop])) {
37677                     var result = raw[prop];
37678                     if (!sourceFile && !ts.every(result, validateElement)) {
37679                         errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, elementTypeName));
37680                     }
37681                     return result;
37682                 }
37683                 else {
37684                     createCompilerDiagnosticOnlyIfJson(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, prop, "Array");
37685                     return "not-array";
37686                 }
37687             }
37688             return "no-prop";
37689         }
37690         function createCompilerDiagnosticOnlyIfJson(message, arg0, arg1) {
37691             if (!sourceFile) {
37692                 errors.push(ts.createCompilerDiagnostic(message, arg0, arg1));
37693             }
37694         }
37695     }
37696     function isErrorNoInputFiles(error) {
37697         return error.code === ts.Diagnostics.No_inputs_were_found_in_config_file_0_Specified_include_paths_were_1_and_exclude_paths_were_2.code;
37698     }
37699     function getErrorForNoInputFiles(_a, configFileName) {
37700         var includeSpecs = _a.includeSpecs, excludeSpecs = _a.excludeSpecs;
37701         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 || []));
37702     }
37703     function shouldReportNoInputFiles(result, canJsonReportNoInutFiles, resolutionStack) {
37704         return result.fileNames.length === 0 && canJsonReportNoInutFiles && (!resolutionStack || resolutionStack.length === 0);
37705     }
37706     /*@internal*/
37707     function canJsonReportNoInputFiles(raw) {
37708         return !ts.hasProperty(raw, "files") && !ts.hasProperty(raw, "references");
37709     }
37710     ts.canJsonReportNoInputFiles = canJsonReportNoInputFiles;
37711     /*@internal*/
37712     function updateErrorForNoInputFiles(result, configFileName, configFileSpecs, configParseDiagnostics, canJsonReportNoInutFiles) {
37713         var existingErrors = configParseDiagnostics.length;
37714         if (shouldReportNoInputFiles(result, canJsonReportNoInutFiles)) {
37715             configParseDiagnostics.push(getErrorForNoInputFiles(configFileSpecs, configFileName));
37716         }
37717         else {
37718             ts.filterMutate(configParseDiagnostics, function (error) { return !isErrorNoInputFiles(error); });
37719         }
37720         return existingErrors !== configParseDiagnostics.length;
37721     }
37722     ts.updateErrorForNoInputFiles = updateErrorForNoInputFiles;
37723     function isSuccessfulParsedTsconfig(value) {
37724         return !!value.options;
37725     }
37726     /**
37727      * This *just* extracts options/include/exclude/files out of a config file.
37728      * It does *not* resolve the included files.
37729      */
37730     function parseConfig(json, sourceFile, host, basePath, configFileName, resolutionStack, errors, extendedConfigCache) {
37731         var _a;
37732         basePath = ts.normalizeSlashes(basePath);
37733         var resolvedPath = ts.getNormalizedAbsolutePath(configFileName || "", basePath);
37734         if (resolutionStack.indexOf(resolvedPath) >= 0) {
37735             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Circularity_detected_while_resolving_configuration_Colon_0, __spreadArrays(resolutionStack, [resolvedPath]).join(" -> ")));
37736             return { raw: json || convertToObject(sourceFile, errors) };
37737         }
37738         var ownConfig = json ?
37739             parseOwnConfigOfJson(json, host, basePath, configFileName, errors) :
37740             parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors);
37741         if ((_a = ownConfig.options) === null || _a === void 0 ? void 0 : _a.paths) {
37742             // If we end up needing to resolve relative paths from 'paths' relative to
37743             // the config file location, we'll need to know where that config file was.
37744             // Since 'paths' can be inherited from an extended config in another directory,
37745             // we wouldn't know which directory to use unless we store it here.
37746             ownConfig.options.pathsBasePath = basePath;
37747         }
37748         if (ownConfig.extendedConfigPath) {
37749             // copy the resolution stack so it is never reused between branches in potential diamond-problem scenarios.
37750             resolutionStack = resolutionStack.concat([resolvedPath]);
37751             var extendedConfig = getExtendedConfig(sourceFile, ownConfig.extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache);
37752             if (extendedConfig && isSuccessfulParsedTsconfig(extendedConfig)) {
37753                 var baseRaw_1 = extendedConfig.raw;
37754                 var raw_1 = ownConfig.raw;
37755                 var setPropertyInRawIfNotUndefined = function (propertyName) {
37756                     var value = raw_1[propertyName] || baseRaw_1[propertyName];
37757                     if (value) {
37758                         raw_1[propertyName] = value;
37759                     }
37760                 };
37761                 setPropertyInRawIfNotUndefined("include");
37762                 setPropertyInRawIfNotUndefined("exclude");
37763                 setPropertyInRawIfNotUndefined("files");
37764                 if (raw_1.compileOnSave === undefined) {
37765                     raw_1.compileOnSave = baseRaw_1.compileOnSave;
37766                 }
37767                 ownConfig.options = ts.assign({}, extendedConfig.options, ownConfig.options);
37768                 ownConfig.watchOptions = ownConfig.watchOptions && extendedConfig.watchOptions ?
37769                     ts.assign({}, extendedConfig.watchOptions, ownConfig.watchOptions) :
37770                     ownConfig.watchOptions || extendedConfig.watchOptions;
37771                 // TODO extend type typeAcquisition
37772             }
37773         }
37774         return ownConfig;
37775     }
37776     function parseOwnConfigOfJson(json, host, basePath, configFileName, errors) {
37777         if (ts.hasProperty(json, "excludes")) {
37778             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
37779         }
37780         var options = convertCompilerOptionsFromJsonWorker(json.compilerOptions, basePath, errors, configFileName);
37781         // typingOptions has been deprecated and is only supported for backward compatibility purposes.
37782         // It should be removed in future releases - use typeAcquisition instead.
37783         var typeAcquisition = convertTypeAcquisitionFromJsonWorker(json.typeAcquisition || json.typingOptions, basePath, errors, configFileName);
37784         var watchOptions = convertWatchOptionsFromJsonWorker(json.watchOptions, basePath, errors);
37785         json.compileOnSave = convertCompileOnSaveOptionFromJson(json, basePath, errors);
37786         var extendedConfigPath;
37787         if (json.extends) {
37788             if (!ts.isString(json.extends)) {
37789                 errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, "extends", "string"));
37790             }
37791             else {
37792                 var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
37793                 extendedConfigPath = getExtendsConfigPath(json.extends, host, newBase, errors, ts.createCompilerDiagnostic);
37794             }
37795         }
37796         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
37797     }
37798     function parseOwnConfigOfJsonSourceFile(sourceFile, host, basePath, configFileName, errors) {
37799         var options = getDefaultCompilerOptions(configFileName);
37800         var typeAcquisition, typingOptionstypeAcquisition;
37801         var watchOptions;
37802         var extendedConfigPath;
37803         var optionsIterator = {
37804             onSetValidOptionKeyValueInParent: function (parentOption, option, value) {
37805                 var currentOption;
37806                 switch (parentOption) {
37807                     case "compilerOptions":
37808                         currentOption = options;
37809                         break;
37810                     case "watchOptions":
37811                         currentOption = (watchOptions || (watchOptions = {}));
37812                         break;
37813                     case "typeAcquisition":
37814                         currentOption = (typeAcquisition || (typeAcquisition = getDefaultTypeAcquisition(configFileName)));
37815                         break;
37816                     case "typingOptions":
37817                         currentOption = (typingOptionstypeAcquisition || (typingOptionstypeAcquisition = getDefaultTypeAcquisition(configFileName)));
37818                         break;
37819                     default:
37820                         ts.Debug.fail("Unknown option");
37821                 }
37822                 currentOption[option.name] = normalizeOptionValue(option, basePath, value);
37823             },
37824             onSetValidOptionKeyValueInRoot: function (key, _keyNode, value, valueNode) {
37825                 switch (key) {
37826                     case "extends":
37827                         var newBase = configFileName ? directoryOfCombinedPath(configFileName, basePath) : basePath;
37828                         extendedConfigPath = getExtendsConfigPath(value, host, newBase, errors, function (message, arg0) {
37829                             return ts.createDiagnosticForNodeInSourceFile(sourceFile, valueNode, message, arg0);
37830                         });
37831                         return;
37832                 }
37833             },
37834             onSetUnknownOptionKeyValueInRoot: function (key, keyNode, _value, _valueNode) {
37835                 if (key === "excludes") {
37836                     errors.push(ts.createDiagnosticForNodeInSourceFile(sourceFile, keyNode, ts.Diagnostics.Unknown_option_excludes_Did_you_mean_exclude));
37837                 }
37838             }
37839         };
37840         var json = convertToObjectWorker(sourceFile, errors, /*returnValue*/ true, getTsconfigRootOptionsMap(), optionsIterator);
37841         if (!typeAcquisition) {
37842             if (typingOptionstypeAcquisition) {
37843                 typeAcquisition = (typingOptionstypeAcquisition.enableAutoDiscovery !== undefined) ?
37844                     {
37845                         enable: typingOptionstypeAcquisition.enableAutoDiscovery,
37846                         include: typingOptionstypeAcquisition.include,
37847                         exclude: typingOptionstypeAcquisition.exclude
37848                     } :
37849                     typingOptionstypeAcquisition;
37850             }
37851             else {
37852                 typeAcquisition = getDefaultTypeAcquisition(configFileName);
37853             }
37854         }
37855         return { raw: json, options: options, watchOptions: watchOptions, typeAcquisition: typeAcquisition, extendedConfigPath: extendedConfigPath };
37856     }
37857     function getExtendsConfigPath(extendedConfig, host, basePath, errors, createDiagnostic) {
37858         extendedConfig = ts.normalizeSlashes(extendedConfig);
37859         if (ts.isRootedDiskPath(extendedConfig) || ts.startsWith(extendedConfig, "./") || ts.startsWith(extendedConfig, "../")) {
37860             var extendedConfigPath = ts.getNormalizedAbsolutePath(extendedConfig, basePath);
37861             if (!host.fileExists(extendedConfigPath) && !ts.endsWith(extendedConfigPath, ".json" /* Json */)) {
37862                 extendedConfigPath = extendedConfigPath + ".json";
37863                 if (!host.fileExists(extendedConfigPath)) {
37864                     errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
37865                     return undefined;
37866                 }
37867             }
37868             return extendedConfigPath;
37869         }
37870         // If the path isn't a rooted or relative path, resolve like a module
37871         var resolved = ts.nodeModuleNameResolver(extendedConfig, ts.combinePaths(basePath, "tsconfig.json"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, host, /*cache*/ undefined, /*projectRefs*/ undefined, /*lookupConfig*/ true);
37872         if (resolved.resolvedModule) {
37873             return resolved.resolvedModule.resolvedFileName;
37874         }
37875         errors.push(createDiagnostic(ts.Diagnostics.File_0_not_found, extendedConfig));
37876         return undefined;
37877     }
37878     function getExtendedConfig(sourceFile, extendedConfigPath, host, basePath, resolutionStack, errors, extendedConfigCache) {
37879         var _a;
37880         var path = host.useCaseSensitiveFileNames ? extendedConfigPath : ts.toFileNameLowerCase(extendedConfigPath);
37881         var value;
37882         var extendedResult;
37883         var extendedConfig;
37884         if (extendedConfigCache && (value = extendedConfigCache.get(path))) {
37885             (extendedResult = value.extendedResult, extendedConfig = value.extendedConfig);
37886         }
37887         else {
37888             extendedResult = readJsonConfigFile(extendedConfigPath, function (path) { return host.readFile(path); });
37889             if (!extendedResult.parseDiagnostics.length) {
37890                 var extendedDirname = ts.getDirectoryPath(extendedConfigPath);
37891                 extendedConfig = parseConfig(/*json*/ undefined, extendedResult, host, extendedDirname, ts.getBaseFileName(extendedConfigPath), resolutionStack, errors, extendedConfigCache);
37892                 if (isSuccessfulParsedTsconfig(extendedConfig)) {
37893                     // Update the paths to reflect base path
37894                     var relativeDifference_1 = ts.convertToRelativePath(extendedDirname, basePath, ts.identity);
37895                     var updatePath_1 = function (path) { return ts.isRootedDiskPath(path) ? path : ts.combinePaths(relativeDifference_1, path); };
37896                     var mapPropertiesInRawIfNotUndefined = function (propertyName) {
37897                         if (raw_2[propertyName]) {
37898                             raw_2[propertyName] = ts.map(raw_2[propertyName], updatePath_1);
37899                         }
37900                     };
37901                     var raw_2 = extendedConfig.raw;
37902                     mapPropertiesInRawIfNotUndefined("include");
37903                     mapPropertiesInRawIfNotUndefined("exclude");
37904                     mapPropertiesInRawIfNotUndefined("files");
37905                 }
37906             }
37907             if (extendedConfigCache) {
37908                 extendedConfigCache.set(path, { extendedResult: extendedResult, extendedConfig: extendedConfig });
37909             }
37910         }
37911         if (sourceFile) {
37912             sourceFile.extendedSourceFiles = [extendedResult.fileName];
37913             if (extendedResult.extendedSourceFiles) {
37914                 (_a = sourceFile.extendedSourceFiles).push.apply(_a, extendedResult.extendedSourceFiles);
37915             }
37916         }
37917         if (extendedResult.parseDiagnostics.length) {
37918             errors.push.apply(errors, extendedResult.parseDiagnostics);
37919             return undefined;
37920         }
37921         return extendedConfig;
37922     }
37923     function convertCompileOnSaveOptionFromJson(jsonOption, basePath, errors) {
37924         if (!ts.hasProperty(jsonOption, ts.compileOnSaveCommandLineOption.name)) {
37925             return false;
37926         }
37927         var result = convertJsonOption(ts.compileOnSaveCommandLineOption, jsonOption.compileOnSave, basePath, errors);
37928         return typeof result === "boolean" && result;
37929     }
37930     function convertCompilerOptionsFromJson(jsonOptions, basePath, configFileName) {
37931         var errors = [];
37932         var options = convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName);
37933         return { options: options, errors: errors };
37934     }
37935     ts.convertCompilerOptionsFromJson = convertCompilerOptionsFromJson;
37936     function convertTypeAcquisitionFromJson(jsonOptions, basePath, configFileName) {
37937         var errors = [];
37938         var options = convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName);
37939         return { options: options, errors: errors };
37940     }
37941     ts.convertTypeAcquisitionFromJson = convertTypeAcquisitionFromJson;
37942     function getDefaultCompilerOptions(configFileName) {
37943         var options = configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json"
37944             ? { allowJs: true, maxNodeModuleJsDepth: 2, allowSyntheticDefaultImports: true, skipLibCheck: true, noEmit: true }
37945             : {};
37946         return options;
37947     }
37948     function convertCompilerOptionsFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
37949         var options = getDefaultCompilerOptions(configFileName);
37950         convertOptionsFromJson(getCommandLineCompilerOptionsMap(), jsonOptions, basePath, options, ts.compilerOptionsDidYouMeanDiagnostics, errors);
37951         if (configFileName) {
37952             options.configFilePath = ts.normalizeSlashes(configFileName);
37953         }
37954         return options;
37955     }
37956     function getDefaultTypeAcquisition(configFileName) {
37957         return { enable: !!configFileName && ts.getBaseFileName(configFileName) === "jsconfig.json", include: [], exclude: [] };
37958     }
37959     function convertTypeAcquisitionFromJsonWorker(jsonOptions, basePath, errors, configFileName) {
37960         var options = getDefaultTypeAcquisition(configFileName);
37961         var typeAcquisition = convertEnableAutoDiscoveryToEnable(jsonOptions);
37962         convertOptionsFromJson(getCommandLineTypeAcquisitionMap(), typeAcquisition, basePath, options, typeAcquisitionDidYouMeanDiagnostics, errors);
37963         return options;
37964     }
37965     function convertWatchOptionsFromJsonWorker(jsonOptions, basePath, errors) {
37966         return convertOptionsFromJson(getCommandLineWatchOptionsMap(), jsonOptions, basePath, /*defaultOptions*/ undefined, watchOptionsDidYouMeanDiagnostics, errors);
37967     }
37968     function convertOptionsFromJson(optionsNameMap, jsonOptions, basePath, defaultOptions, diagnostics, errors) {
37969         if (!jsonOptions) {
37970             return;
37971         }
37972         for (var id in jsonOptions) {
37973             var opt = optionsNameMap.get(id);
37974             if (opt) {
37975                 (defaultOptions || (defaultOptions = {}))[opt.name] = convertJsonOption(opt, jsonOptions[id], basePath, errors);
37976             }
37977             else {
37978                 errors.push(createUnknownOptionError(id, diagnostics, ts.createCompilerDiagnostic));
37979             }
37980         }
37981         return defaultOptions;
37982     }
37983     function convertJsonOption(opt, value, basePath, errors) {
37984         if (isCompilerOptionsValue(opt, value)) {
37985             var optType = opt.type;
37986             if (optType === "list" && ts.isArray(value)) {
37987                 return convertJsonOptionOfListType(opt, value, basePath, errors);
37988             }
37989             else if (!ts.isString(optType)) {
37990                 return convertJsonOptionOfCustomType(opt, value, errors);
37991             }
37992             return normalizeNonListOptionValue(opt, basePath, value);
37993         }
37994         else {
37995             errors.push(ts.createCompilerDiagnostic(ts.Diagnostics.Compiler_option_0_requires_a_value_of_type_1, opt.name, getCompilerOptionValueTypeString(opt)));
37996         }
37997     }
37998     function normalizeOptionValue(option, basePath, value) {
37999         if (isNullOrUndefined(value))
38000             return undefined;
38001         if (option.type === "list") {
38002             var listOption_1 = option;
38003             if (listOption_1.element.isFilePath || !ts.isString(listOption_1.element.type)) {
38004                 return ts.filter(ts.map(value, function (v) { return normalizeOptionValue(listOption_1.element, basePath, v); }), function (v) { return !!v; });
38005             }
38006             return value;
38007         }
38008         else if (!ts.isString(option.type)) {
38009             return option.type.get(ts.isString(value) ? value.toLowerCase() : value);
38010         }
38011         return normalizeNonListOptionValue(option, basePath, value);
38012     }
38013     function normalizeNonListOptionValue(option, basePath, value) {
38014         if (option.isFilePath) {
38015             value = ts.getNormalizedAbsolutePath(value, basePath);
38016             if (value === "") {
38017                 value = ".";
38018             }
38019         }
38020         return value;
38021     }
38022     function convertJsonOptionOfCustomType(opt, value, errors) {
38023         if (isNullOrUndefined(value))
38024             return undefined;
38025         var key = value.toLowerCase();
38026         var val = opt.type.get(key);
38027         if (val !== undefined) {
38028             return val;
38029         }
38030         else {
38031             errors.push(createCompilerDiagnosticForInvalidCustomType(opt));
38032         }
38033     }
38034     function convertJsonOptionOfListType(option, values, basePath, errors) {
38035         return ts.filter(ts.map(values, function (v) { return convertJsonOption(option.element, v, basePath, errors); }), function (v) { return !!v; });
38036     }
38037     function trimString(s) {
38038         return typeof s.trim === "function" ? s.trim() : s.replace(/^[\s]+|[\s]+$/g, "");
38039     }
38040     /**
38041      * Tests for a path that ends in a recursive directory wildcard.
38042      * Matches **, \**, **\, and \**\, but not a**b.
38043      *
38044      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38045      *
38046      * Breakdown:
38047      *  (^|\/)      # matches either the beginning of the string or a directory separator.
38048      *  \*\*        # matches the recursive directory wildcard "**".
38049      *  \/?$        # matches an optional trailing directory separator at the end of the string.
38050      */
38051     var invalidTrailingRecursionPattern = /(^|\/)\*\*\/?$/;
38052     /**
38053      * Tests for a path where .. appears after a recursive directory wildcard.
38054      * Matches **\..\*, **\a\..\*, and **\.., but not ..\**\*
38055      *
38056      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38057      *
38058      * Breakdown:
38059      *  (^|\/)      # matches either the beginning of the string or a directory separator.
38060      *  \*\*\/      # matches a recursive directory wildcard "**" followed by a directory separator.
38061      *  (.*\/)?     # optionally matches any number of characters followed by a directory separator.
38062      *  \.\.        # matches a parent directory path component ".."
38063      *  ($|\/)      # matches either the end of the string or a directory separator.
38064      */
38065     var invalidDotDotAfterRecursiveWildcardPattern = /(^|\/)\*\*\/(.*\/)?\.\.($|\/)/;
38066     /**
38067      * Tests for a path containing a wildcard character in a directory component of the path.
38068      * Matches \*\, \?\, and \a*b\, but not \a\ or \a\*.
38069      *
38070      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38071      *
38072      * Breakdown:
38073      *  \/          # matches a directory separator.
38074      *  [^/]*?      # matches any number of characters excluding directory separators (non-greedy).
38075      *  [*?]        # matches either a wildcard character (* or ?)
38076      *  [^/]*       # matches any number of characters excluding directory separators (greedy).
38077      *  \/          # matches a directory separator.
38078      */
38079     var watchRecursivePattern = /\/[^/]*?[*?][^/]*\//;
38080     /**
38081      * Matches the portion of a wildcard path that does not contain wildcards.
38082      * Matches \a of \a\*, or \a\b\c of \a\b\c\?\d.
38083      *
38084      * NOTE: used \ in place of / above to avoid issues with multiline comments.
38085      *
38086      * Breakdown:
38087      *  ^                   # matches the beginning of the string
38088      *  [^*?]*              # matches any number of non-wildcard characters
38089      *  (?=\/[^/]*[*?])     # lookahead that matches a directory separator followed by
38090      *                      # a path component that contains at least one wildcard character (* or ?).
38091      */
38092     var wildcardDirectoryPattern = /^[^*?]*(?=\/[^/]*[*?])/;
38093     /**
38094      * Expands an array of file specifications.
38095      *
38096      * @param filesSpecs The literal file names to include.
38097      * @param includeSpecs The wildcard file specifications to include.
38098      * @param excludeSpecs The wildcard file specifications to exclude.
38099      * @param basePath The base path for any relative file specifications.
38100      * @param options Compiler options.
38101      * @param host The host used to resolve files and directories.
38102      * @param errors An array for diagnostic reporting.
38103      */
38104     function matchFileNames(filesSpecs, includeSpecs, excludeSpecs, basePath, options, host, errors, extraFileExtensions, jsonSourceFile) {
38105         basePath = ts.normalizePath(basePath);
38106         var validatedIncludeSpecs, validatedExcludeSpecs;
38107         // The exclude spec list is converted into a regular expression, which allows us to quickly
38108         // test whether a file or directory should be excluded before recursively traversing the
38109         // file system.
38110         if (includeSpecs) {
38111             validatedIncludeSpecs = validateSpecs(includeSpecs, errors, /*allowTrailingRecursion*/ false, jsonSourceFile, "include");
38112         }
38113         if (excludeSpecs) {
38114             validatedExcludeSpecs = validateSpecs(excludeSpecs, errors, /*allowTrailingRecursion*/ true, jsonSourceFile, "exclude");
38115         }
38116         // Wildcard directories (provided as part of a wildcard path) are stored in a
38117         // file map that marks whether it was a regular wildcard match (with a `*` or `?` token),
38118         // or a recursive directory. This information is used by filesystem watchers to monitor for
38119         // new entries in these paths.
38120         var wildcardDirectories = getWildcardDirectories(validatedIncludeSpecs, validatedExcludeSpecs, basePath, host.useCaseSensitiveFileNames);
38121         var spec = {
38122             filesSpecs: filesSpecs,
38123             includeSpecs: includeSpecs,
38124             excludeSpecs: excludeSpecs,
38125             validatedFilesSpec: ts.filter(filesSpecs, ts.isString),
38126             validatedIncludeSpecs: validatedIncludeSpecs,
38127             validatedExcludeSpecs: validatedExcludeSpecs,
38128             wildcardDirectories: wildcardDirectories
38129         };
38130         return getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions);
38131     }
38132     /**
38133      * Gets the file names from the provided config file specs that contain, files, include, exclude and
38134      * other properties needed to resolve the file names
38135      * @param spec The config file specs extracted with file names to include, wildcards to include/exclude and other details
38136      * @param basePath The base path for any relative file specifications.
38137      * @param options Compiler options.
38138      * @param host The host used to resolve files and directories.
38139      * @param extraFileExtensions optionaly file extra file extension information from host
38140      */
38141     /* @internal */
38142     function getFileNamesFromConfigSpecs(spec, basePath, options, host, extraFileExtensions) {
38143         if (extraFileExtensions === void 0) { extraFileExtensions = ts.emptyArray; }
38144         basePath = ts.normalizePath(basePath);
38145         var keyMapper = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames);
38146         // Literal file names (provided via the "files" array in tsconfig.json) are stored in a
38147         // file map with a possibly case insensitive key. We use this map later when when including
38148         // wildcard paths.
38149         var literalFileMap = new ts.Map();
38150         // Wildcard paths (provided via the "includes" array in tsconfig.json) are stored in a
38151         // file map with a possibly case insensitive key. We use this map to store paths matched
38152         // via wildcard, and to handle extension priority.
38153         var wildcardFileMap = new ts.Map();
38154         // Wildcard paths of json files (provided via the "includes" array in tsconfig.json) are stored in a
38155         // file map with a possibly case insensitive key. We use this map to store paths matched
38156         // via wildcard of *.json kind
38157         var wildCardJsonFileMap = new ts.Map();
38158         var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs, wildcardDirectories = spec.wildcardDirectories;
38159         // Rather than requery this for each file and filespec, we query the supported extensions
38160         // once and store it on the expansion context.
38161         var supportedExtensions = ts.getSupportedExtensions(options, extraFileExtensions);
38162         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
38163         // Literal files are always included verbatim. An "include" or "exclude" specification cannot
38164         // remove a literal file.
38165         if (validatedFilesSpec) {
38166             for (var _i = 0, validatedFilesSpec_1 = validatedFilesSpec; _i < validatedFilesSpec_1.length; _i++) {
38167                 var fileName = validatedFilesSpec_1[_i];
38168                 var file = ts.getNormalizedAbsolutePath(fileName, basePath);
38169                 literalFileMap.set(keyMapper(file), file);
38170             }
38171         }
38172         var jsonOnlyIncludeRegexes;
38173         if (validatedIncludeSpecs && validatedIncludeSpecs.length > 0) {
38174             var _loop_6 = function (file) {
38175                 if (ts.fileExtensionIs(file, ".json" /* Json */)) {
38176                     // Valid only if *.json specified
38177                     if (!jsonOnlyIncludeRegexes) {
38178                         var includes = validatedIncludeSpecs.filter(function (s) { return ts.endsWith(s, ".json" /* Json */); });
38179                         var includeFilePatterns = ts.map(ts.getRegularExpressionsForWildcards(includes, basePath, "files"), function (pattern) { return "^" + pattern + "$"; });
38180                         jsonOnlyIncludeRegexes = includeFilePatterns ? includeFilePatterns.map(function (pattern) { return ts.getRegexFromPattern(pattern, host.useCaseSensitiveFileNames); }) : ts.emptyArray;
38181                     }
38182                     var includeIndex = ts.findIndex(jsonOnlyIncludeRegexes, function (re) { return re.test(file); });
38183                     if (includeIndex !== -1) {
38184                         var key_1 = keyMapper(file);
38185                         if (!literalFileMap.has(key_1) && !wildCardJsonFileMap.has(key_1)) {
38186                             wildCardJsonFileMap.set(key_1, file);
38187                         }
38188                     }
38189                     return "continue";
38190                 }
38191                 // If we have already included a literal or wildcard path with a
38192                 // higher priority extension, we should skip this file.
38193                 //
38194                 // This handles cases where we may encounter both <file>.ts and
38195                 // <file>.d.ts (or <file>.js if "allowJs" is enabled) in the same
38196                 // directory when they are compilation outputs.
38197                 if (hasFileWithHigherPriorityExtension(file, literalFileMap, wildcardFileMap, supportedExtensions, keyMapper)) {
38198                     return "continue";
38199                 }
38200                 // We may have included a wildcard path with a lower priority
38201                 // extension due to the user-defined order of entries in the
38202                 // "include" array. If there is a lower priority extension in the
38203                 // same directory, we should remove it.
38204                 removeWildcardFilesWithLowerPriorityExtension(file, wildcardFileMap, supportedExtensions, keyMapper);
38205                 var key = keyMapper(file);
38206                 if (!literalFileMap.has(key) && !wildcardFileMap.has(key)) {
38207                     wildcardFileMap.set(key, file);
38208                 }
38209             };
38210             for (var _a = 0, _b = host.readDirectory(basePath, supportedExtensionsWithJsonIfResolveJsonModule, validatedExcludeSpecs, validatedIncludeSpecs, /*depth*/ undefined); _a < _b.length; _a++) {
38211                 var file = _b[_a];
38212                 _loop_6(file);
38213             }
38214         }
38215         var literalFiles = ts.arrayFrom(literalFileMap.values());
38216         var wildcardFiles = ts.arrayFrom(wildcardFileMap.values());
38217         return {
38218             fileNames: literalFiles.concat(wildcardFiles, ts.arrayFrom(wildCardJsonFileMap.values())),
38219             wildcardDirectories: wildcardDirectories,
38220             spec: spec
38221         };
38222     }
38223     ts.getFileNamesFromConfigSpecs = getFileNamesFromConfigSpecs;
38224     /* @internal */
38225     function isExcludedFile(pathToCheck, spec, basePath, useCaseSensitiveFileNames, currentDirectory) {
38226         var validatedFilesSpec = spec.validatedFilesSpec, validatedIncludeSpecs = spec.validatedIncludeSpecs, validatedExcludeSpecs = spec.validatedExcludeSpecs;
38227         if (!ts.length(validatedIncludeSpecs) || !ts.length(validatedExcludeSpecs))
38228             return false;
38229         basePath = ts.normalizePath(basePath);
38230         var keyMapper = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
38231         if (validatedFilesSpec) {
38232             for (var _i = 0, validatedFilesSpec_2 = validatedFilesSpec; _i < validatedFilesSpec_2.length; _i++) {
38233                 var fileName = validatedFilesSpec_2[_i];
38234                 if (keyMapper(ts.getNormalizedAbsolutePath(fileName, basePath)) === pathToCheck)
38235                     return false;
38236             }
38237         }
38238         var excludePattern = ts.getRegularExpressionForWildcard(validatedExcludeSpecs, ts.combinePaths(ts.normalizePath(currentDirectory), basePath), "exclude");
38239         var excludeRegex = excludePattern && ts.getRegexFromPattern(excludePattern, useCaseSensitiveFileNames);
38240         if (!excludeRegex)
38241             return false;
38242         if (excludeRegex.test(pathToCheck))
38243             return true;
38244         return !ts.hasExtension(pathToCheck) && excludeRegex.test(ts.ensureTrailingDirectorySeparator(pathToCheck));
38245     }
38246     ts.isExcludedFile = isExcludedFile;
38247     function validateSpecs(specs, errors, allowTrailingRecursion, jsonSourceFile, specKey) {
38248         return specs.filter(function (spec) {
38249             if (!ts.isString(spec))
38250                 return false;
38251             var diag = specToDiagnostic(spec, allowTrailingRecursion);
38252             if (diag !== undefined) {
38253                 errors.push(createDiagnostic(diag, spec));
38254             }
38255             return diag === undefined;
38256         });
38257         function createDiagnostic(message, spec) {
38258             var element = ts.getTsConfigPropArrayElementValue(jsonSourceFile, specKey, spec);
38259             return element ?
38260                 ts.createDiagnosticForNodeInSourceFile(jsonSourceFile, element, message, spec) :
38261                 ts.createCompilerDiagnostic(message, spec);
38262         }
38263     }
38264     function specToDiagnostic(spec, allowTrailingRecursion) {
38265         if (!allowTrailingRecursion && invalidTrailingRecursionPattern.test(spec)) {
38266             return ts.Diagnostics.File_specification_cannot_end_in_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
38267         }
38268         else if (invalidDotDotAfterRecursiveWildcardPattern.test(spec)) {
38269             return ts.Diagnostics.File_specification_cannot_contain_a_parent_directory_that_appears_after_a_recursive_directory_wildcard_Asterisk_Asterisk_Colon_0;
38270         }
38271     }
38272     /**
38273      * Gets directories in a set of include patterns that should be watched for changes.
38274      */
38275     function getWildcardDirectories(include, exclude, path, useCaseSensitiveFileNames) {
38276         // We watch a directory recursively if it contains a wildcard anywhere in a directory segment
38277         // of the pattern:
38278         //
38279         //  /a/b/**/d   - Watch /a/b recursively to catch changes to any d in any subfolder recursively
38280         //  /a/b/*/d    - Watch /a/b recursively to catch any d in any immediate subfolder, even if a new subfolder is added
38281         //  /a/b        - Watch /a/b recursively to catch changes to anything in any recursive subfoler
38282         //
38283         // We watch a directory without recursion if it contains a wildcard in the file segment of
38284         // the pattern:
38285         //
38286         //  /a/b/*      - Watch /a/b directly to catch any new file
38287         //  /a/b/a?z    - Watch /a/b directly to catch any new file matching a?z
38288         var rawExcludeRegex = ts.getRegularExpressionForWildcard(exclude, path, "exclude");
38289         var excludeRegex = rawExcludeRegex && new RegExp(rawExcludeRegex, useCaseSensitiveFileNames ? "" : "i");
38290         var wildcardDirectories = {};
38291         if (include !== undefined) {
38292             var recursiveKeys = [];
38293             for (var _i = 0, include_1 = include; _i < include_1.length; _i++) {
38294                 var file = include_1[_i];
38295                 var spec = ts.normalizePath(ts.combinePaths(path, file));
38296                 if (excludeRegex && excludeRegex.test(spec)) {
38297                     continue;
38298                 }
38299                 var match = getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames);
38300                 if (match) {
38301                     var key = match.key, flags = match.flags;
38302                     var existingFlags = wildcardDirectories[key];
38303                     if (existingFlags === undefined || existingFlags < flags) {
38304                         wildcardDirectories[key] = flags;
38305                         if (flags === 1 /* Recursive */) {
38306                             recursiveKeys.push(key);
38307                         }
38308                     }
38309                 }
38310             }
38311             // Remove any subpaths under an existing recursively watched directory.
38312             for (var key in wildcardDirectories) {
38313                 if (ts.hasProperty(wildcardDirectories, key)) {
38314                     for (var _a = 0, recursiveKeys_1 = recursiveKeys; _a < recursiveKeys_1.length; _a++) {
38315                         var recursiveKey = recursiveKeys_1[_a];
38316                         if (key !== recursiveKey && ts.containsPath(recursiveKey, key, path, !useCaseSensitiveFileNames)) {
38317                             delete wildcardDirectories[key];
38318                         }
38319                     }
38320                 }
38321             }
38322         }
38323         return wildcardDirectories;
38324     }
38325     function getWildcardDirectoryFromSpec(spec, useCaseSensitiveFileNames) {
38326         var match = wildcardDirectoryPattern.exec(spec);
38327         if (match) {
38328             return {
38329                 key: useCaseSensitiveFileNames ? match[0] : ts.toFileNameLowerCase(match[0]),
38330                 flags: watchRecursivePattern.test(spec) ? 1 /* Recursive */ : 0 /* None */
38331             };
38332         }
38333         if (ts.isImplicitGlob(spec)) {
38334             return {
38335                 key: useCaseSensitiveFileNames ? spec : ts.toFileNameLowerCase(spec),
38336                 flags: 1 /* Recursive */
38337             };
38338         }
38339         return undefined;
38340     }
38341     /**
38342      * Determines whether a literal or wildcard file has already been included that has a higher
38343      * extension priority.
38344      *
38345      * @param file The path to the file.
38346      * @param extensionPriority The priority of the extension.
38347      * @param context The expansion context.
38348      */
38349     function hasFileWithHigherPriorityExtension(file, literalFiles, wildcardFiles, extensions, keyMapper) {
38350         var extensionPriority = ts.getExtensionPriority(file, extensions);
38351         var adjustedExtensionPriority = ts.adjustExtensionPriority(extensionPriority, extensions);
38352         for (var i = 0 /* Highest */; i < adjustedExtensionPriority; i++) {
38353             var higherPriorityExtension = extensions[i];
38354             var higherPriorityPath = keyMapper(ts.changeExtension(file, higherPriorityExtension));
38355             if (literalFiles.has(higherPriorityPath) || wildcardFiles.has(higherPriorityPath)) {
38356                 return true;
38357             }
38358         }
38359         return false;
38360     }
38361     /**
38362      * Removes files included via wildcard expansion with a lower extension priority that have
38363      * already been included.
38364      *
38365      * @param file The path to the file.
38366      * @param extensionPriority The priority of the extension.
38367      * @param context The expansion context.
38368      */
38369     function removeWildcardFilesWithLowerPriorityExtension(file, wildcardFiles, extensions, keyMapper) {
38370         var extensionPriority = ts.getExtensionPriority(file, extensions);
38371         var nextExtensionPriority = ts.getNextLowestExtensionPriority(extensionPriority, extensions);
38372         for (var i = nextExtensionPriority; i < extensions.length; i++) {
38373             var lowerPriorityExtension = extensions[i];
38374             var lowerPriorityPath = keyMapper(ts.changeExtension(file, lowerPriorityExtension));
38375             wildcardFiles.delete(lowerPriorityPath);
38376         }
38377     }
38378     /**
38379      * Produces a cleaned version of compiler options with personally identifying info (aka, paths) removed.
38380      * Also converts enum values back to strings.
38381      */
38382     /* @internal */
38383     function convertCompilerOptionsForTelemetry(opts) {
38384         var out = {};
38385         for (var key in opts) {
38386             if (opts.hasOwnProperty(key)) {
38387                 var type = getOptionFromName(key);
38388                 if (type !== undefined) { // Ignore unknown options
38389                     out[key] = getOptionValueWithEmptyStrings(opts[key], type);
38390                 }
38391             }
38392         }
38393         return out;
38394     }
38395     ts.convertCompilerOptionsForTelemetry = convertCompilerOptionsForTelemetry;
38396     function getOptionValueWithEmptyStrings(value, option) {
38397         switch (option.type) {
38398             case "object": // "paths". Can't get any useful information from the value since we blank out strings, so just return "".
38399                 return "";
38400             case "string": // Could be any arbitrary string -- use empty string instead.
38401                 return "";
38402             case "number": // Allow numbers, but be sure to check it's actually a number.
38403                 return typeof value === "number" ? value : "";
38404             case "boolean":
38405                 return typeof value === "boolean" ? value : "";
38406             case "list":
38407                 var elementType_1 = option.element;
38408                 return ts.isArray(value) ? value.map(function (v) { return getOptionValueWithEmptyStrings(v, elementType_1); }) : "";
38409             default:
38410                 return ts.forEachEntry(option.type, function (optionEnumValue, optionStringValue) {
38411                     if (optionEnumValue === value) {
38412                         return optionStringValue;
38413                     }
38414                 }); // TODO: GH#18217
38415         }
38416     }
38417 })(ts || (ts = {}));
38418 var ts;
38419 (function (ts) {
38420     function trace(host) {
38421         host.trace(ts.formatMessage.apply(undefined, arguments));
38422     }
38423     ts.trace = trace;
38424     /* @internal */
38425     function isTraceEnabled(compilerOptions, host) {
38426         return !!compilerOptions.traceResolution && host.trace !== undefined;
38427     }
38428     ts.isTraceEnabled = isTraceEnabled;
38429     function withPackageId(packageInfo, r) {
38430         var packageId;
38431         if (r && packageInfo) {
38432             var packageJsonContent = packageInfo.packageJsonContent;
38433             if (typeof packageJsonContent.name === "string" && typeof packageJsonContent.version === "string") {
38434                 packageId = {
38435                     name: packageJsonContent.name,
38436                     subModuleName: r.path.slice(packageInfo.packageDirectory.length + ts.directorySeparator.length),
38437                     version: packageJsonContent.version
38438                 };
38439             }
38440         }
38441         return r && { path: r.path, extension: r.ext, packageId: packageId };
38442     }
38443     function noPackageId(r) {
38444         return withPackageId(/*packageInfo*/ undefined, r);
38445     }
38446     function removeIgnoredPackageId(r) {
38447         if (r) {
38448             ts.Debug.assert(r.packageId === undefined);
38449             return { path: r.path, ext: r.extension };
38450         }
38451     }
38452     /**
38453      * Kinds of file that we are currently looking for.
38454      * Typically there is one pass with Extensions.TypeScript, then a second pass with Extensions.JavaScript.
38455      */
38456     var Extensions;
38457     (function (Extensions) {
38458         Extensions[Extensions["TypeScript"] = 0] = "TypeScript";
38459         Extensions[Extensions["JavaScript"] = 1] = "JavaScript";
38460         Extensions[Extensions["Json"] = 2] = "Json";
38461         Extensions[Extensions["TSConfig"] = 3] = "TSConfig";
38462         Extensions[Extensions["DtsOnly"] = 4] = "DtsOnly"; /** Only '.d.ts' */
38463     })(Extensions || (Extensions = {}));
38464     /** Used with `Extensions.DtsOnly` to extract the path from TypeScript results. */
38465     function resolvedTypeScriptOnly(resolved) {
38466         if (!resolved) {
38467             return undefined;
38468         }
38469         ts.Debug.assert(ts.extensionIsTS(resolved.extension));
38470         return { fileName: resolved.path, packageId: resolved.packageId };
38471     }
38472     function createResolvedModuleWithFailedLookupLocations(resolved, isExternalLibraryImport, failedLookupLocations, resultFromCache) {
38473         var _a;
38474         if (resultFromCache) {
38475             (_a = resultFromCache.failedLookupLocations).push.apply(_a, failedLookupLocations);
38476             return resultFromCache;
38477         }
38478         return {
38479             resolvedModule: resolved && { resolvedFileName: resolved.path, originalPath: resolved.originalPath === true ? undefined : resolved.originalPath, extension: resolved.extension, isExternalLibraryImport: isExternalLibraryImport, packageId: resolved.packageId },
38480             failedLookupLocations: failedLookupLocations
38481         };
38482     }
38483     function readPackageJsonField(jsonContent, fieldName, typeOfTag, state) {
38484         if (!ts.hasProperty(jsonContent, fieldName)) {
38485             if (state.traceEnabled) {
38486                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_0_field, fieldName);
38487             }
38488             return;
38489         }
38490         var value = jsonContent[fieldName];
38491         if (typeof value !== typeOfTag || value === null) { // eslint-disable-line no-null/no-null
38492             if (state.traceEnabled) {
38493                 // eslint-disable-next-line no-null/no-null
38494                 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);
38495             }
38496             return;
38497         }
38498         return value;
38499     }
38500     function readPackageJsonPathField(jsonContent, fieldName, baseDirectory, state) {
38501         var fileName = readPackageJsonField(jsonContent, fieldName, "string", state);
38502         if (fileName === undefined) {
38503             return;
38504         }
38505         if (!fileName) {
38506             if (state.traceEnabled) {
38507                 trace(state.host, ts.Diagnostics.package_json_had_a_falsy_0_field, fieldName);
38508             }
38509             return;
38510         }
38511         var path = ts.normalizePath(ts.combinePaths(baseDirectory, fileName));
38512         if (state.traceEnabled) {
38513             trace(state.host, ts.Diagnostics.package_json_has_0_field_1_that_references_2, fieldName, fileName, path);
38514         }
38515         return path;
38516     }
38517     function readPackageJsonTypesFields(jsonContent, baseDirectory, state) {
38518         return readPackageJsonPathField(jsonContent, "typings", baseDirectory, state)
38519             || readPackageJsonPathField(jsonContent, "types", baseDirectory, state);
38520     }
38521     function readPackageJsonTSConfigField(jsonContent, baseDirectory, state) {
38522         return readPackageJsonPathField(jsonContent, "tsconfig", baseDirectory, state);
38523     }
38524     function readPackageJsonMainField(jsonContent, baseDirectory, state) {
38525         return readPackageJsonPathField(jsonContent, "main", baseDirectory, state);
38526     }
38527     function readPackageJsonTypesVersionsField(jsonContent, state) {
38528         var typesVersions = readPackageJsonField(jsonContent, "typesVersions", "object", state);
38529         if (typesVersions === undefined)
38530             return;
38531         if (state.traceEnabled) {
38532             trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_field_with_version_specific_path_mappings);
38533         }
38534         return typesVersions;
38535     }
38536     function readPackageJsonTypesVersionPaths(jsonContent, state) {
38537         var typesVersions = readPackageJsonTypesVersionsField(jsonContent, state);
38538         if (typesVersions === undefined)
38539             return;
38540         if (state.traceEnabled) {
38541             for (var key in typesVersions) {
38542                 if (ts.hasProperty(typesVersions, key) && !ts.VersionRange.tryParse(key)) {
38543                     trace(state.host, ts.Diagnostics.package_json_has_a_typesVersions_entry_0_that_is_not_a_valid_semver_range, key);
38544                 }
38545             }
38546         }
38547         var result = getPackageJsonTypesVersionsPaths(typesVersions);
38548         if (!result) {
38549             if (state.traceEnabled) {
38550                 trace(state.host, ts.Diagnostics.package_json_does_not_have_a_typesVersions_entry_that_matches_version_0, ts.versionMajorMinor);
38551             }
38552             return;
38553         }
38554         var bestVersionKey = result.version, bestVersionPaths = result.paths;
38555         if (typeof bestVersionPaths !== "object") {
38556             if (state.traceEnabled) {
38557                 trace(state.host, ts.Diagnostics.Expected_type_of_0_field_in_package_json_to_be_1_got_2, "typesVersions['" + bestVersionKey + "']", "object", typeof bestVersionPaths);
38558             }
38559             return;
38560         }
38561         return result;
38562     }
38563     var typeScriptVersion;
38564     /* @internal */
38565     function getPackageJsonTypesVersionsPaths(typesVersions) {
38566         if (!typeScriptVersion)
38567             typeScriptVersion = new ts.Version(ts.version);
38568         for (var key in typesVersions) {
38569             if (!ts.hasProperty(typesVersions, key))
38570                 continue;
38571             var keyRange = ts.VersionRange.tryParse(key);
38572             if (keyRange === undefined) {
38573                 continue;
38574             }
38575             // return the first entry whose range matches the current compiler version.
38576             if (keyRange.test(typeScriptVersion)) {
38577                 return { version: key, paths: typesVersions[key] };
38578             }
38579         }
38580     }
38581     ts.getPackageJsonTypesVersionsPaths = getPackageJsonTypesVersionsPaths;
38582     function getEffectiveTypeRoots(options, host) {
38583         if (options.typeRoots) {
38584             return options.typeRoots;
38585         }
38586         var currentDirectory;
38587         if (options.configFilePath) {
38588             currentDirectory = ts.getDirectoryPath(options.configFilePath);
38589         }
38590         else if (host.getCurrentDirectory) {
38591             currentDirectory = host.getCurrentDirectory();
38592         }
38593         if (currentDirectory !== undefined) {
38594             return getDefaultTypeRoots(currentDirectory, host);
38595         }
38596     }
38597     ts.getEffectiveTypeRoots = getEffectiveTypeRoots;
38598     /**
38599      * Returns the path to every node_modules/@types directory from some ancestor directory.
38600      * Returns undefined if there are none.
38601      */
38602     function getDefaultTypeRoots(currentDirectory, host) {
38603         if (!host.directoryExists) {
38604             return [ts.combinePaths(currentDirectory, nodeModulesAtTypes)];
38605             // And if it doesn't exist, tough.
38606         }
38607         var typeRoots;
38608         ts.forEachAncestorDirectory(ts.normalizePath(currentDirectory), function (directory) {
38609             var atTypes = ts.combinePaths(directory, nodeModulesAtTypes);
38610             if (host.directoryExists(atTypes)) {
38611                 (typeRoots || (typeRoots = [])).push(atTypes);
38612             }
38613             return undefined;
38614         });
38615         return typeRoots;
38616     }
38617     var nodeModulesAtTypes = ts.combinePaths("node_modules", "@types");
38618     /**
38619      * @param {string | undefined} containingFile - file that contains type reference directive, can be undefined if containing file is unknown.
38620      * This is possible in case if resolution is performed for directives specified via 'types' parameter. In this case initial path for secondary lookups
38621      * is assumed to be the same as root directory of the project.
38622      */
38623     function resolveTypeReferenceDirective(typeReferenceDirectiveName, containingFile, options, host, redirectedReference) {
38624         var traceEnabled = isTraceEnabled(options, host);
38625         if (redirectedReference) {
38626             options = redirectedReference.commandLine.options;
38627         }
38628         var failedLookupLocations = [];
38629         var moduleResolutionState = { compilerOptions: options, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
38630         var typeRoots = getEffectiveTypeRoots(options, host);
38631         if (traceEnabled) {
38632             if (containingFile === undefined) {
38633                 if (typeRoots === undefined) {
38634                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_not_set, typeReferenceDirectiveName);
38635                 }
38636                 else {
38637                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_not_set_root_directory_1, typeReferenceDirectiveName, typeRoots);
38638                 }
38639             }
38640             else {
38641                 if (typeRoots === undefined) {
38642                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_not_set, typeReferenceDirectiveName, containingFile);
38643                 }
38644                 else {
38645                     trace(host, ts.Diagnostics.Resolving_type_reference_directive_0_containing_file_1_root_directory_2, typeReferenceDirectiveName, containingFile, typeRoots);
38646                 }
38647             }
38648             if (redirectedReference) {
38649                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
38650             }
38651         }
38652         var resolved = primaryLookup();
38653         var primary = true;
38654         if (!resolved) {
38655             resolved = secondaryLookup();
38656             primary = false;
38657         }
38658         var resolvedTypeReferenceDirective;
38659         if (resolved) {
38660             var fileName = resolved.fileName, packageId = resolved.packageId;
38661             var resolvedFileName = options.preserveSymlinks ? fileName : realPath(fileName, host, traceEnabled);
38662             if (traceEnabled) {
38663                 if (packageId) {
38664                     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);
38665                 }
38666                 else {
38667                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_successfully_resolved_to_1_primary_Colon_2, typeReferenceDirectiveName, resolvedFileName, primary);
38668                 }
38669             }
38670             resolvedTypeReferenceDirective = { primary: primary, resolvedFileName: resolvedFileName, packageId: packageId, isExternalLibraryImport: pathContainsNodeModules(fileName) };
38671         }
38672         return { resolvedTypeReferenceDirective: resolvedTypeReferenceDirective, failedLookupLocations: failedLookupLocations };
38673         function primaryLookup() {
38674             // Check primary library paths
38675             if (typeRoots && typeRoots.length) {
38676                 if (traceEnabled) {
38677                     trace(host, ts.Diagnostics.Resolving_with_primary_search_path_0, typeRoots.join(", "));
38678                 }
38679                 return ts.firstDefined(typeRoots, function (typeRoot) {
38680                     var candidate = ts.combinePaths(typeRoot, typeReferenceDirectiveName);
38681                     var candidateDirectory = ts.getDirectoryPath(candidate);
38682                     var directoryExists = ts.directoryProbablyExists(candidateDirectory, host);
38683                     if (!directoryExists && traceEnabled) {
38684                         trace(host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidateDirectory);
38685                     }
38686                     return resolvedTypeScriptOnly(loadNodeModuleFromDirectory(Extensions.DtsOnly, candidate, !directoryExists, moduleResolutionState));
38687                 });
38688             }
38689             else {
38690                 if (traceEnabled) {
38691                     trace(host, ts.Diagnostics.Root_directory_cannot_be_determined_skipping_primary_search_paths);
38692                 }
38693             }
38694         }
38695         function secondaryLookup() {
38696             var initialLocationForSecondaryLookup = containingFile && ts.getDirectoryPath(containingFile);
38697             if (initialLocationForSecondaryLookup !== undefined) {
38698                 // check secondary locations
38699                 if (traceEnabled) {
38700                     trace(host, ts.Diagnostics.Looking_up_in_node_modules_folder_initial_location_0, initialLocationForSecondaryLookup);
38701                 }
38702                 var result = void 0;
38703                 if (!ts.isExternalModuleNameRelative(typeReferenceDirectiveName)) {
38704                     var searchResult = loadModuleFromNearestNodeModulesDirectory(Extensions.DtsOnly, typeReferenceDirectiveName, initialLocationForSecondaryLookup, moduleResolutionState, /*cache*/ undefined, /*redirectedReference*/ undefined);
38705                     result = searchResult && searchResult.value;
38706                 }
38707                 else {
38708                     var candidate = ts.normalizePathAndParts(ts.combinePaths(initialLocationForSecondaryLookup, typeReferenceDirectiveName)).path;
38709                     result = nodeLoadModuleByRelativeName(Extensions.DtsOnly, candidate, /*onlyRecordFailures*/ false, moduleResolutionState, /*considerPackageJson*/ true);
38710                 }
38711                 var resolvedFile = resolvedTypeScriptOnly(result);
38712                 if (!resolvedFile && traceEnabled) {
38713                     trace(host, ts.Diagnostics.Type_reference_directive_0_was_not_resolved, typeReferenceDirectiveName);
38714                 }
38715                 return resolvedFile;
38716             }
38717             else {
38718                 if (traceEnabled) {
38719                     trace(host, ts.Diagnostics.Containing_file_is_not_specified_and_root_directory_cannot_be_determined_skipping_lookup_in_node_modules_folder);
38720                 }
38721             }
38722         }
38723     }
38724     ts.resolveTypeReferenceDirective = resolveTypeReferenceDirective;
38725     /**
38726      * Given a set of options, returns the set of type directive names
38727      *   that should be included for this program automatically.
38728      * This list could either come from the config file,
38729      *   or from enumerating the types root + initial secondary types lookup location.
38730      * More type directives might appear in the program later as a result of loading actual source files;
38731      *   this list is only the set of defaults that are implicitly included.
38732      */
38733     function getAutomaticTypeDirectiveNames(options, host) {
38734         // Use explicit type list from tsconfig.json
38735         if (options.types) {
38736             return options.types;
38737         }
38738         // Walk the primary type lookup locations
38739         var result = [];
38740         if (host.directoryExists && host.getDirectories) {
38741             var typeRoots = getEffectiveTypeRoots(options, host);
38742             if (typeRoots) {
38743                 for (var _i = 0, typeRoots_1 = typeRoots; _i < typeRoots_1.length; _i++) {
38744                     var root = typeRoots_1[_i];
38745                     if (host.directoryExists(root)) {
38746                         for (var _a = 0, _b = host.getDirectories(root); _a < _b.length; _a++) {
38747                             var typeDirectivePath = _b[_a];
38748                             var normalized = ts.normalizePath(typeDirectivePath);
38749                             var packageJsonPath = ts.combinePaths(root, normalized, "package.json");
38750                             // `types-publisher` sometimes creates packages with `"typings": null` for packages that don't provide their own types.
38751                             // See `createNotNeededPackageJSON` in the types-publisher` repo.
38752                             // eslint-disable-next-line no-null/no-null
38753                             var isNotNeededPackage = host.fileExists(packageJsonPath) && ts.readJson(packageJsonPath, host).typings === null;
38754                             if (!isNotNeededPackage) {
38755                                 var baseFileName = ts.getBaseFileName(normalized);
38756                                 // At this stage, skip results with leading dot.
38757                                 if (baseFileName.charCodeAt(0) !== 46 /* dot */) {
38758                                     // Return just the type directive names
38759                                     result.push(baseFileName);
38760                                 }
38761                             }
38762                         }
38763                     }
38764                 }
38765             }
38766         }
38767         return result;
38768     }
38769     ts.getAutomaticTypeDirectiveNames = getAutomaticTypeDirectiveNames;
38770     function createModuleResolutionCache(currentDirectory, getCanonicalFileName, options) {
38771         return createModuleResolutionCacheWithMaps(createCacheWithRedirects(options), createCacheWithRedirects(options), currentDirectory, getCanonicalFileName);
38772     }
38773     ts.createModuleResolutionCache = createModuleResolutionCache;
38774     /*@internal*/
38775     function createCacheWithRedirects(options) {
38776         var ownMap = new ts.Map();
38777         var redirectsMap = new ts.Map();
38778         return {
38779             ownMap: ownMap,
38780             redirectsMap: redirectsMap,
38781             getOrCreateMapOfCacheRedirects: getOrCreateMapOfCacheRedirects,
38782             clear: clear,
38783             setOwnOptions: setOwnOptions,
38784             setOwnMap: setOwnMap
38785         };
38786         function setOwnOptions(newOptions) {
38787             options = newOptions;
38788         }
38789         function setOwnMap(newOwnMap) {
38790             ownMap = newOwnMap;
38791         }
38792         function getOrCreateMapOfCacheRedirects(redirectedReference) {
38793             if (!redirectedReference) {
38794                 return ownMap;
38795             }
38796             var path = redirectedReference.sourceFile.path;
38797             var redirects = redirectsMap.get(path);
38798             if (!redirects) {
38799                 // Reuse map if redirected reference map uses same resolution
38800                 redirects = !options || ts.optionsHaveModuleResolutionChanges(options, redirectedReference.commandLine.options) ? new ts.Map() : ownMap;
38801                 redirectsMap.set(path, redirects);
38802             }
38803             return redirects;
38804         }
38805         function clear() {
38806             ownMap.clear();
38807             redirectsMap.clear();
38808         }
38809     }
38810     ts.createCacheWithRedirects = createCacheWithRedirects;
38811     /*@internal*/
38812     function createModuleResolutionCacheWithMaps(directoryToModuleNameMap, moduleNameToDirectoryMap, currentDirectory, getCanonicalFileName) {
38813         return { getOrCreateCacheForDirectory: getOrCreateCacheForDirectory, getOrCreateCacheForModuleName: getOrCreateCacheForModuleName, directoryToModuleNameMap: directoryToModuleNameMap, moduleNameToDirectoryMap: moduleNameToDirectoryMap };
38814         function getOrCreateCacheForDirectory(directoryName, redirectedReference) {
38815             var path = ts.toPath(directoryName, currentDirectory, getCanonicalFileName);
38816             return getOrCreateCache(directoryToModuleNameMap, redirectedReference, path, function () { return new ts.Map(); });
38817         }
38818         function getOrCreateCacheForModuleName(nonRelativeModuleName, redirectedReference) {
38819             ts.Debug.assert(!ts.isExternalModuleNameRelative(nonRelativeModuleName));
38820             return getOrCreateCache(moduleNameToDirectoryMap, redirectedReference, nonRelativeModuleName, createPerModuleNameCache);
38821         }
38822         function getOrCreateCache(cacheWithRedirects, redirectedReference, key, create) {
38823             var cache = cacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
38824             var result = cache.get(key);
38825             if (!result) {
38826                 result = create();
38827                 cache.set(key, result);
38828             }
38829             return result;
38830         }
38831         function createPerModuleNameCache() {
38832             var directoryPathMap = new ts.Map();
38833             return { get: get, set: set };
38834             function get(directory) {
38835                 return directoryPathMap.get(ts.toPath(directory, currentDirectory, getCanonicalFileName));
38836             }
38837             /**
38838              * At first this function add entry directory -> module resolution result to the table.
38839              * Then it computes the set of parent folders for 'directory' that should have the same module resolution result
38840              * and for every parent folder in set it adds entry: parent -> module resolution. .
38841              * Lets say we first directory name: /a/b/c/d/e and resolution result is: /a/b/bar.ts.
38842              * Set of parent folders that should have the same result will be:
38843              * [
38844              *     /a/b/c/d, /a/b/c, /a/b
38845              * ]
38846              * this means that request for module resolution from file in any of these folder will be immediately found in cache.
38847              */
38848             function set(directory, result) {
38849                 var path = ts.toPath(directory, currentDirectory, getCanonicalFileName);
38850                 // if entry is already in cache do nothing
38851                 if (directoryPathMap.has(path)) {
38852                     return;
38853                 }
38854                 directoryPathMap.set(path, result);
38855                 var resolvedFileName = result.resolvedModule &&
38856                     (result.resolvedModule.originalPath || result.resolvedModule.resolvedFileName);
38857                 // find common prefix between directory and resolved file name
38858                 // this common prefix should be the shortest path that has the same resolution
38859                 // directory: /a/b/c/d/e
38860                 // resolvedFileName: /a/b/foo.d.ts
38861                 // commonPrefix: /a/b
38862                 // for failed lookups cache the result for every directory up to root
38863                 var commonPrefix = resolvedFileName && getCommonPrefix(path, resolvedFileName);
38864                 var current = path;
38865                 while (current !== commonPrefix) {
38866                     var parent = ts.getDirectoryPath(current);
38867                     if (parent === current || directoryPathMap.has(parent)) {
38868                         break;
38869                     }
38870                     directoryPathMap.set(parent, result);
38871                     current = parent;
38872                 }
38873             }
38874             function getCommonPrefix(directory, resolution) {
38875                 var resolutionDirectory = ts.toPath(ts.getDirectoryPath(resolution), currentDirectory, getCanonicalFileName);
38876                 // find first position where directory and resolution differs
38877                 var i = 0;
38878                 var limit = Math.min(directory.length, resolutionDirectory.length);
38879                 while (i < limit && directory.charCodeAt(i) === resolutionDirectory.charCodeAt(i)) {
38880                     i++;
38881                 }
38882                 if (i === directory.length && (resolutionDirectory.length === i || resolutionDirectory[i] === ts.directorySeparator)) {
38883                     return directory;
38884                 }
38885                 var rootLength = ts.getRootLength(directory);
38886                 if (i < rootLength) {
38887                     return undefined;
38888                 }
38889                 var sep = directory.lastIndexOf(ts.directorySeparator, i - 1);
38890                 if (sep === -1) {
38891                     return undefined;
38892                 }
38893                 return directory.substr(0, Math.max(sep, rootLength));
38894             }
38895         }
38896     }
38897     ts.createModuleResolutionCacheWithMaps = createModuleResolutionCacheWithMaps;
38898     function resolveModuleNameFromCache(moduleName, containingFile, cache) {
38899         var containingDirectory = ts.getDirectoryPath(containingFile);
38900         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory);
38901         return perFolderCache && perFolderCache.get(moduleName);
38902     }
38903     ts.resolveModuleNameFromCache = resolveModuleNameFromCache;
38904     function resolveModuleName(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
38905         var traceEnabled = isTraceEnabled(compilerOptions, host);
38906         if (redirectedReference) {
38907             compilerOptions = redirectedReference.commandLine.options;
38908         }
38909         if (traceEnabled) {
38910             trace(host, ts.Diagnostics.Resolving_module_0_from_1, moduleName, containingFile);
38911             if (redirectedReference) {
38912                 trace(host, ts.Diagnostics.Using_compiler_options_of_project_reference_redirect_0, redirectedReference.sourceFile.fileName);
38913             }
38914         }
38915         var containingDirectory = ts.getDirectoryPath(containingFile);
38916         var perFolderCache = cache && cache.getOrCreateCacheForDirectory(containingDirectory, redirectedReference);
38917         var result = perFolderCache && perFolderCache.get(moduleName);
38918         if (result) {
38919             if (traceEnabled) {
38920                 trace(host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
38921             }
38922         }
38923         else {
38924             var moduleResolution = compilerOptions.moduleResolution;
38925             if (moduleResolution === undefined) {
38926                 moduleResolution = ts.getEmitModuleKind(compilerOptions) === ts.ModuleKind.CommonJS ? ts.ModuleResolutionKind.NodeJs : ts.ModuleResolutionKind.Classic;
38927                 if (traceEnabled) {
38928                     trace(host, ts.Diagnostics.Module_resolution_kind_is_not_specified_using_0, ts.ModuleResolutionKind[moduleResolution]);
38929                 }
38930             }
38931             else {
38932                 if (traceEnabled) {
38933                     trace(host, ts.Diagnostics.Explicitly_specified_module_resolution_kind_Colon_0, ts.ModuleResolutionKind[moduleResolution]);
38934                 }
38935             }
38936             ts.perfLogger.logStartResolveModule(moduleName /* , containingFile, ModuleResolutionKind[moduleResolution]*/);
38937             switch (moduleResolution) {
38938                 case ts.ModuleResolutionKind.NodeJs:
38939                     result = nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
38940                     break;
38941                 case ts.ModuleResolutionKind.Classic:
38942                     result = classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference);
38943                     break;
38944                 default:
38945                     return ts.Debug.fail("Unexpected moduleResolution: " + moduleResolution);
38946             }
38947             if (result && result.resolvedModule)
38948                 ts.perfLogger.logInfoEvent("Module \"" + moduleName + "\" resolved to \"" + result.resolvedModule.resolvedFileName + "\"");
38949             ts.perfLogger.logStopResolveModule((result && result.resolvedModule) ? "" + result.resolvedModule.resolvedFileName : "null");
38950             if (perFolderCache) {
38951                 perFolderCache.set(moduleName, result);
38952                 if (!ts.isExternalModuleNameRelative(moduleName)) {
38953                     // put result in per-module name cache
38954                     cache.getOrCreateCacheForModuleName(moduleName, redirectedReference).set(containingDirectory, result);
38955                 }
38956             }
38957         }
38958         if (traceEnabled) {
38959             if (result.resolvedModule) {
38960                 if (result.resolvedModule.packageId) {
38961                     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));
38962                 }
38963                 else {
38964                     trace(host, ts.Diagnostics.Module_name_0_was_successfully_resolved_to_1, moduleName, result.resolvedModule.resolvedFileName);
38965                 }
38966             }
38967             else {
38968                 trace(host, ts.Diagnostics.Module_name_0_was_not_resolved, moduleName);
38969             }
38970         }
38971         return result;
38972     }
38973     ts.resolveModuleName = resolveModuleName;
38974     /**
38975      * Any module resolution kind can be augmented with optional settings: 'baseUrl', 'paths' and 'rootDirs' - they are used to
38976      * mitigate differences between design time structure of the project and its runtime counterpart so the same import name
38977      * can be resolved successfully by TypeScript compiler and runtime module loader.
38978      * If these settings are set then loading procedure will try to use them to resolve module name and it can of failure it will
38979      * fallback to standard resolution routine.
38980      *
38981      * - baseUrl - this setting controls how non-relative module names are resolved. If this setting is specified then non-relative
38982      * names will be resolved relative to baseUrl: i.e. if baseUrl is '/a/b' then candidate location to resolve module name 'c/d' will
38983      * be '/a/b/c/d'
38984      * - paths - this setting can only be used when baseUrl is specified. allows to tune how non-relative module names
38985      * will be resolved based on the content of the module name.
38986      * Structure of 'paths' compiler options
38987      * 'paths': {
38988      *    pattern-1: [...substitutions],
38989      *    pattern-2: [...substitutions],
38990      *    ...
38991      *    pattern-n: [...substitutions]
38992      * }
38993      * Pattern here is a string that can contain zero or one '*' character. During module resolution module name will be matched against
38994      * all patterns in the list. Matching for patterns that don't contain '*' means that module name must be equal to pattern respecting the case.
38995      * If pattern contains '*' then to match pattern "<prefix>*<suffix>" module name must start with the <prefix> and end with <suffix>.
38996      * <MatchedStar> denotes part of the module name between <prefix> and <suffix>.
38997      * If module name can be matches with multiple patterns then pattern with the longest prefix will be picked.
38998      * After selecting pattern we'll use list of substitutions to get candidate locations of the module and the try to load module
38999      * from the candidate location.
39000      * Substitution is a string that can contain zero or one '*'. To get candidate location from substitution we'll pick every
39001      * substitution in the list and replace '*' with <MatchedStar> string. If candidate location is not rooted it
39002      * will be converted to absolute using baseUrl.
39003      * For example:
39004      * baseUrl: /a/b/c
39005      * "paths": {
39006      *     // match all module names
39007      *     "*": [
39008      *         "*",        // use matched name as is,
39009      *                     // <matched name> will be looked as /a/b/c/<matched name>
39010      *
39011      *         "folder1/*" // substitution will convert matched name to 'folder1/<matched name>',
39012      *                     // since it is not rooted then final candidate location will be /a/b/c/folder1/<matched name>
39013      *     ],
39014      *     // match module names that start with 'components/'
39015      *     "components/*": [ "/root/components/*" ] // substitution will convert /components/folder1/<matched name> to '/root/components/folder1/<matched name>',
39016      *                                              // it is rooted so it will be final candidate location
39017      * }
39018      *
39019      * 'rootDirs' allows the project to be spreaded across multiple locations and resolve modules with relative names as if
39020      * they were in the same location. For example lets say there are two files
39021      * '/local/src/content/file1.ts'
39022      * '/shared/components/contracts/src/content/protocols/file2.ts'
39023      * After bundling content of '/shared/components/contracts/src' will be merged with '/local/src' so
39024      * if file1 has the following import 'import {x} from "./protocols/file2"' it will be resolved successfully in runtime.
39025      * 'rootDirs' provides the way to tell compiler that in order to get the whole project it should behave as if content of all
39026      * root dirs were merged together.
39027      * I.e. for the example above 'rootDirs' will have two entries: [ '/local/src', '/shared/components/contracts/src' ].
39028      * Compiler will first convert './protocols/file2' into absolute path relative to the location of containing file:
39029      * '/local/src/content/protocols/file2' and try to load it - failure.
39030      * Then it will search 'rootDirs' looking for a longest matching prefix of this absolute path and if such prefix is found - absolute path will
39031      * be converted to a path relative to found rootDir entry './content/protocols/file2' (*). As a last step compiler will check all remaining
39032      * entries in 'rootDirs', use them to build absolute path out of (*) and try to resolve module from this location.
39033      */
39034     function tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state) {
39035         var resolved = tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state);
39036         if (resolved)
39037             return resolved.value;
39038         if (!ts.isExternalModuleNameRelative(moduleName)) {
39039             return tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state);
39040         }
39041         else {
39042             return tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state);
39043         }
39044     }
39045     function tryLoadModuleUsingPathsIfEligible(extensions, moduleName, loader, state) {
39046         var _a = state.compilerOptions, baseUrl = _a.baseUrl, paths = _a.paths;
39047         if (paths && !ts.pathIsRelative(moduleName)) {
39048             if (state.traceEnabled) {
39049                 if (baseUrl) {
39050                     trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
39051                 }
39052                 trace(state.host, ts.Diagnostics.paths_option_is_specified_looking_for_a_pattern_to_match_module_name_0, moduleName);
39053             }
39054             var baseDirectory = ts.getPathsBasePath(state.compilerOptions, state.host); // Always defined when 'paths' is defined
39055             return tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, /*onlyRecordFailures*/ false, state);
39056         }
39057     }
39058     function tryLoadModuleUsingRootDirs(extensions, moduleName, containingDirectory, loader, state) {
39059         if (!state.compilerOptions.rootDirs) {
39060             return undefined;
39061         }
39062         if (state.traceEnabled) {
39063             trace(state.host, ts.Diagnostics.rootDirs_option_is_set_using_it_to_resolve_relative_module_name_0, moduleName);
39064         }
39065         var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
39066         var matchedRootDir;
39067         var matchedNormalizedPrefix;
39068         for (var _i = 0, _a = state.compilerOptions.rootDirs; _i < _a.length; _i++) {
39069             var rootDir = _a[_i];
39070             // rootDirs are expected to be absolute
39071             // in case of tsconfig.json this will happen automatically - compiler will expand relative names
39072             // using location of tsconfig.json as base location
39073             var normalizedRoot = ts.normalizePath(rootDir);
39074             if (!ts.endsWith(normalizedRoot, ts.directorySeparator)) {
39075                 normalizedRoot += ts.directorySeparator;
39076             }
39077             var isLongestMatchingPrefix = ts.startsWith(candidate, normalizedRoot) &&
39078                 (matchedNormalizedPrefix === undefined || matchedNormalizedPrefix.length < normalizedRoot.length);
39079             if (state.traceEnabled) {
39080                 trace(state.host, ts.Diagnostics.Checking_if_0_is_the_longest_matching_prefix_for_1_2, normalizedRoot, candidate, isLongestMatchingPrefix);
39081             }
39082             if (isLongestMatchingPrefix) {
39083                 matchedNormalizedPrefix = normalizedRoot;
39084                 matchedRootDir = rootDir;
39085             }
39086         }
39087         if (matchedNormalizedPrefix) {
39088             if (state.traceEnabled) {
39089                 trace(state.host, ts.Diagnostics.Longest_matching_prefix_for_0_is_1, candidate, matchedNormalizedPrefix);
39090             }
39091             var suffix = candidate.substr(matchedNormalizedPrefix.length);
39092             // first - try to load from a initial location
39093             if (state.traceEnabled) {
39094                 trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, matchedNormalizedPrefix, candidate);
39095             }
39096             var resolvedFileName = loader(extensions, candidate, !ts.directoryProbablyExists(containingDirectory, state.host), state);
39097             if (resolvedFileName) {
39098                 return resolvedFileName;
39099             }
39100             if (state.traceEnabled) {
39101                 trace(state.host, ts.Diagnostics.Trying_other_entries_in_rootDirs);
39102             }
39103             // then try to resolve using remaining entries in rootDirs
39104             for (var _b = 0, _c = state.compilerOptions.rootDirs; _b < _c.length; _b++) {
39105                 var rootDir = _c[_b];
39106                 if (rootDir === matchedRootDir) {
39107                     // skip the initially matched entry
39108                     continue;
39109                 }
39110                 var candidate_1 = ts.combinePaths(ts.normalizePath(rootDir), suffix);
39111                 if (state.traceEnabled) {
39112                     trace(state.host, ts.Diagnostics.Loading_0_from_the_root_dir_1_candidate_location_2, suffix, rootDir, candidate_1);
39113                 }
39114                 var baseDirectory = ts.getDirectoryPath(candidate_1);
39115                 var resolvedFileName_1 = loader(extensions, candidate_1, !ts.directoryProbablyExists(baseDirectory, state.host), state);
39116                 if (resolvedFileName_1) {
39117                     return resolvedFileName_1;
39118                 }
39119             }
39120             if (state.traceEnabled) {
39121                 trace(state.host, ts.Diagnostics.Module_resolution_using_rootDirs_has_failed);
39122             }
39123         }
39124         return undefined;
39125     }
39126     function tryLoadModuleUsingBaseUrl(extensions, moduleName, loader, state) {
39127         var baseUrl = state.compilerOptions.baseUrl;
39128         if (!baseUrl) {
39129             return undefined;
39130         }
39131         if (state.traceEnabled) {
39132             trace(state.host, ts.Diagnostics.baseUrl_option_is_set_to_0_using_this_value_to_resolve_non_relative_module_name_1, baseUrl, moduleName);
39133         }
39134         var candidate = ts.normalizePath(ts.combinePaths(baseUrl, moduleName));
39135         if (state.traceEnabled) {
39136             trace(state.host, ts.Diagnostics.Resolving_module_name_0_relative_to_base_url_1_2, moduleName, baseUrl, candidate);
39137         }
39138         return loader(extensions, candidate, !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
39139     }
39140     /**
39141      * Expose resolution logic to allow us to use Node module resolution logic from arbitrary locations.
39142      * No way to do this with `require()`: https://github.com/nodejs/node/issues/5963
39143      * Throws an error if the module can't be resolved.
39144      */
39145     /* @internal */
39146     function resolveJSModule(moduleName, initialDir, host) {
39147         var _a = tryResolveJSModuleWorker(moduleName, initialDir, host), resolvedModule = _a.resolvedModule, failedLookupLocations = _a.failedLookupLocations;
39148         if (!resolvedModule) {
39149             throw new Error("Could not resolve JS module '" + moduleName + "' starting at '" + initialDir + "'. Looked in: " + failedLookupLocations.join(", "));
39150         }
39151         return resolvedModule.resolvedFileName;
39152     }
39153     ts.resolveJSModule = resolveJSModule;
39154     /* @internal */
39155     function tryResolveJSModule(moduleName, initialDir, host) {
39156         var resolvedModule = tryResolveJSModuleWorker(moduleName, initialDir, host).resolvedModule;
39157         return resolvedModule && resolvedModule.resolvedFileName;
39158     }
39159     ts.tryResolveJSModule = tryResolveJSModule;
39160     var jsOnlyExtensions = [Extensions.JavaScript];
39161     var tsExtensions = [Extensions.TypeScript, Extensions.JavaScript];
39162     var tsPlusJsonExtensions = __spreadArrays(tsExtensions, [Extensions.Json]);
39163     var tsconfigExtensions = [Extensions.TSConfig];
39164     function tryResolveJSModuleWorker(moduleName, initialDir, host) {
39165         return nodeModuleNameResolverWorker(moduleName, initialDir, { moduleResolution: ts.ModuleResolutionKind.NodeJs, allowJs: true }, host, /*cache*/ undefined, jsOnlyExtensions, /*redirectedReferences*/ undefined);
39166     }
39167     function nodeModuleNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference, lookupConfig) {
39168         return nodeModuleNameResolverWorker(moduleName, ts.getDirectoryPath(containingFile), compilerOptions, host, cache, lookupConfig ? tsconfigExtensions : (compilerOptions.resolveJsonModule ? tsPlusJsonExtensions : tsExtensions), redirectedReference);
39169     }
39170     ts.nodeModuleNameResolver = nodeModuleNameResolver;
39171     function nodeModuleNameResolverWorker(moduleName, containingDirectory, compilerOptions, host, cache, extensions, redirectedReference) {
39172         var _a, _b;
39173         var traceEnabled = isTraceEnabled(compilerOptions, host);
39174         var failedLookupLocations = [];
39175         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
39176         var result = ts.forEach(extensions, function (ext) { return tryResolve(ext); });
39177         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);
39178         function tryResolve(extensions) {
39179             var loader = function (extensions, candidate, onlyRecordFailures, state) { return nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ true); };
39180             var resolved = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loader, state);
39181             if (resolved) {
39182                 return toSearchResult({ resolved: resolved, isExternalLibraryImport: pathContainsNodeModules(resolved.path) });
39183             }
39184             if (!ts.isExternalModuleNameRelative(moduleName)) {
39185                 if (traceEnabled) {
39186                     trace(host, ts.Diagnostics.Loading_module_0_from_node_modules_folder_target_file_type_1, moduleName, Extensions[extensions]);
39187                 }
39188                 var resolved_1 = loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, containingDirectory, state, cache, redirectedReference);
39189                 if (!resolved_1)
39190                     return undefined;
39191                 var resolvedValue = resolved_1.value;
39192                 if (!compilerOptions.preserveSymlinks && resolvedValue && !resolvedValue.originalPath) {
39193                     var path = realPath(resolvedValue.path, host, traceEnabled);
39194                     var originalPath = path === resolvedValue.path ? undefined : resolvedValue.path;
39195                     resolvedValue = __assign(__assign({}, resolvedValue), { path: path, originalPath: originalPath });
39196                 }
39197                 // For node_modules lookups, get the real path so that multiple accesses to an `npm link`-ed module do not create duplicate files.
39198                 return { value: resolvedValue && { resolved: resolvedValue, isExternalLibraryImport: true } };
39199             }
39200             else {
39201                 var _a = ts.normalizePathAndParts(ts.combinePaths(containingDirectory, moduleName)), candidate = _a.path, parts = _a.parts;
39202                 var resolved_2 = nodeLoadModuleByRelativeName(extensions, candidate, /*onlyRecordFailures*/ false, state, /*considerPackageJson*/ true);
39203                 // Treat explicit "node_modules" import as an external library import.
39204                 return resolved_2 && toSearchResult({ resolved: resolved_2, isExternalLibraryImport: ts.contains(parts, "node_modules") });
39205             }
39206         }
39207     }
39208     function realPath(path, host, traceEnabled) {
39209         if (!host.realpath) {
39210             return path;
39211         }
39212         var real = ts.normalizePath(host.realpath(path));
39213         if (traceEnabled) {
39214             trace(host, ts.Diagnostics.Resolving_real_path_for_0_result_1, path, real);
39215         }
39216         ts.Debug.assert(host.fileExists(real), path + " linked to nonexistent file " + real);
39217         return real;
39218     }
39219     function nodeLoadModuleByRelativeName(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
39220         if (state.traceEnabled) {
39221             trace(state.host, ts.Diagnostics.Loading_module_as_file_Slash_folder_candidate_module_location_0_target_file_type_1, candidate, Extensions[extensions]);
39222         }
39223         if (!ts.hasTrailingDirectorySeparator(candidate)) {
39224             if (!onlyRecordFailures) {
39225                 var parentOfCandidate = ts.getDirectoryPath(candidate);
39226                 if (!ts.directoryProbablyExists(parentOfCandidate, state.host)) {
39227                     if (state.traceEnabled) {
39228                         trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, parentOfCandidate);
39229                     }
39230                     onlyRecordFailures = true;
39231                 }
39232             }
39233             var resolvedFromFile = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state);
39234             if (resolvedFromFile) {
39235                 var packageDirectory = considerPackageJson ? parseNodeModuleFromPath(resolvedFromFile) : undefined;
39236                 var packageInfo = packageDirectory ? getPackageJsonInfo(packageDirectory, /*onlyRecordFailures*/ false, state) : undefined;
39237                 return withPackageId(packageInfo, resolvedFromFile);
39238             }
39239         }
39240         if (!onlyRecordFailures) {
39241             var candidateExists = ts.directoryProbablyExists(candidate, state.host);
39242             if (!candidateExists) {
39243                 if (state.traceEnabled) {
39244                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, candidate);
39245                 }
39246                 onlyRecordFailures = true;
39247             }
39248         }
39249         return loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson);
39250     }
39251     /*@internal*/
39252     ts.nodeModulesPathPart = "/node_modules/";
39253     /*@internal*/
39254     function pathContainsNodeModules(path) {
39255         return ts.stringContains(path, ts.nodeModulesPathPart);
39256     }
39257     ts.pathContainsNodeModules = pathContainsNodeModules;
39258     /**
39259      * This will be called on the successfully resolved path from `loadModuleFromFile`.
39260      * (Not neeeded for `loadModuleFromNodeModules` as that looks up the `package.json` as part of resolution.)
39261      *
39262      * packageDirectory is the directory of the package itself.
39263      *   For `blah/node_modules/foo/index.d.ts` this is packageDirectory: "foo"
39264      *   For `/node_modules/foo/bar.d.ts` this is packageDirectory: "foo"
39265      *   For `/node_modules/@types/foo/bar/index.d.ts` this is packageDirectory: "@types/foo"
39266      *   For `/node_modules/foo/bar/index.d.ts` this is packageDirectory: "foo"
39267      */
39268     function parseNodeModuleFromPath(resolved) {
39269         var path = ts.normalizePath(resolved.path);
39270         var idx = path.lastIndexOf(ts.nodeModulesPathPart);
39271         if (idx === -1) {
39272             return undefined;
39273         }
39274         var indexAfterNodeModules = idx + ts.nodeModulesPathPart.length;
39275         var indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterNodeModules);
39276         if (path.charCodeAt(indexAfterNodeModules) === 64 /* at */) {
39277             indexAfterPackageName = moveToNextDirectorySeparatorIfAvailable(path, indexAfterPackageName);
39278         }
39279         return path.slice(0, indexAfterPackageName);
39280     }
39281     function moveToNextDirectorySeparatorIfAvailable(path, prevSeparatorIndex) {
39282         var nextSeparatorIndex = path.indexOf(ts.directorySeparator, prevSeparatorIndex + 1);
39283         return nextSeparatorIndex === -1 ? prevSeparatorIndex : nextSeparatorIndex;
39284     }
39285     function loadModuleFromFileNoPackageId(extensions, candidate, onlyRecordFailures, state) {
39286         return noPackageId(loadModuleFromFile(extensions, candidate, onlyRecordFailures, state));
39287     }
39288     /**
39289      * @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
39290      * 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.
39291      */
39292     function loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) {
39293         if (extensions === Extensions.Json || extensions === Extensions.TSConfig) {
39294             var extensionLess = ts.tryRemoveExtension(candidate, ".json" /* Json */);
39295             return (extensionLess === undefined && extensions === Extensions.Json) ? undefined : tryAddingExtensions(extensionLess || candidate, extensions, onlyRecordFailures, state);
39296         }
39297         // First, try adding an extension. An import of "foo" could be matched by a file "foo.ts", or "foo.js" by "foo.js.ts"
39298         var resolvedByAddingExtension = tryAddingExtensions(candidate, extensions, onlyRecordFailures, state);
39299         if (resolvedByAddingExtension) {
39300             return resolvedByAddingExtension;
39301         }
39302         // If that didn't work, try stripping a ".js" or ".jsx" extension and replacing it with a TypeScript one;
39303         // e.g. "./foo.js" can be matched by "./foo.ts" or "./foo.d.ts"
39304         if (ts.hasJSFileExtension(candidate)) {
39305             var extensionless = ts.removeFileExtension(candidate);
39306             if (state.traceEnabled) {
39307                 var extension = candidate.substring(extensionless.length);
39308                 trace(state.host, ts.Diagnostics.File_name_0_has_a_1_extension_stripping_it, candidate, extension);
39309             }
39310             return tryAddingExtensions(extensionless, extensions, onlyRecordFailures, state);
39311         }
39312     }
39313     /** Try to return an existing file that adds one of the `extensions` to `candidate`. */
39314     function tryAddingExtensions(candidate, extensions, onlyRecordFailures, state) {
39315         if (!onlyRecordFailures) {
39316             // check if containing folder exists - if it doesn't then just record failures for all supported extensions without disk probing
39317             var directory = ts.getDirectoryPath(candidate);
39318             if (directory) {
39319                 onlyRecordFailures = !ts.directoryProbablyExists(directory, state.host);
39320             }
39321         }
39322         switch (extensions) {
39323             case Extensions.DtsOnly:
39324                 return tryExtension(".d.ts" /* Dts */);
39325             case Extensions.TypeScript:
39326                 return tryExtension(".ts" /* Ts */) || tryExtension(".tsx" /* Tsx */) || tryExtension(".d.ts" /* Dts */);
39327             case Extensions.JavaScript:
39328                 return tryExtension(".js" /* Js */) || tryExtension(".jsx" /* Jsx */);
39329             case Extensions.TSConfig:
39330             case Extensions.Json:
39331                 return tryExtension(".json" /* Json */);
39332         }
39333         function tryExtension(ext) {
39334             var path = tryFile(candidate + ext, onlyRecordFailures, state);
39335             return path === undefined ? undefined : { path: path, ext: ext };
39336         }
39337     }
39338     /** Return the file if it exists. */
39339     function tryFile(fileName, onlyRecordFailures, state) {
39340         if (!onlyRecordFailures) {
39341             if (state.host.fileExists(fileName)) {
39342                 if (state.traceEnabled) {
39343                     trace(state.host, ts.Diagnostics.File_0_exist_use_it_as_a_name_resolution_result, fileName);
39344                 }
39345                 return fileName;
39346             }
39347             else {
39348                 if (state.traceEnabled) {
39349                     trace(state.host, ts.Diagnostics.File_0_does_not_exist, fileName);
39350                 }
39351             }
39352         }
39353         state.failedLookupLocations.push(fileName);
39354         return undefined;
39355     }
39356     function loadNodeModuleFromDirectory(extensions, candidate, onlyRecordFailures, state, considerPackageJson) {
39357         if (considerPackageJson === void 0) { considerPackageJson = true; }
39358         var packageInfo = considerPackageJson ? getPackageJsonInfo(candidate, onlyRecordFailures, state) : undefined;
39359         var packageJsonContent = packageInfo && packageInfo.packageJsonContent;
39360         var versionPaths = packageInfo && packageInfo.versionPaths;
39361         return withPackageId(packageInfo, loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageJsonContent, versionPaths));
39362     }
39363     function getPackageJsonInfo(packageDirectory, onlyRecordFailures, state) {
39364         var host = state.host, traceEnabled = state.traceEnabled;
39365         var directoryExists = !onlyRecordFailures && ts.directoryProbablyExists(packageDirectory, host);
39366         var packageJsonPath = ts.combinePaths(packageDirectory, "package.json");
39367         if (directoryExists && host.fileExists(packageJsonPath)) {
39368             var packageJsonContent = ts.readJson(packageJsonPath, host);
39369             if (traceEnabled) {
39370                 trace(host, ts.Diagnostics.Found_package_json_at_0, packageJsonPath);
39371             }
39372             var versionPaths = readPackageJsonTypesVersionPaths(packageJsonContent, state);
39373             return { packageDirectory: packageDirectory, packageJsonContent: packageJsonContent, versionPaths: versionPaths };
39374         }
39375         else {
39376             if (directoryExists && traceEnabled) {
39377                 trace(host, ts.Diagnostics.File_0_does_not_exist, packageJsonPath);
39378             }
39379             // record package json as one of failed lookup locations - in the future if this file will appear it will invalidate resolution results
39380             state.failedLookupLocations.push(packageJsonPath);
39381         }
39382     }
39383     function loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, jsonContent, versionPaths) {
39384         var packageFile;
39385         if (jsonContent) {
39386             switch (extensions) {
39387                 case Extensions.JavaScript:
39388                 case Extensions.Json:
39389                     packageFile = readPackageJsonMainField(jsonContent, candidate, state);
39390                     break;
39391                 case Extensions.TypeScript:
39392                     // When resolving typescript modules, try resolving using main field as well
39393                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state) || readPackageJsonMainField(jsonContent, candidate, state);
39394                     break;
39395                 case Extensions.DtsOnly:
39396                     packageFile = readPackageJsonTypesFields(jsonContent, candidate, state);
39397                     break;
39398                 case Extensions.TSConfig:
39399                     packageFile = readPackageJsonTSConfigField(jsonContent, candidate, state);
39400                     break;
39401                 default:
39402                     return ts.Debug.assertNever(extensions);
39403             }
39404         }
39405         var loader = function (extensions, candidate, onlyRecordFailures, state) {
39406             var fromFile = tryFile(candidate, onlyRecordFailures, state);
39407             if (fromFile) {
39408                 var resolved = resolvedIfExtensionMatches(extensions, fromFile);
39409                 if (resolved) {
39410                     return noPackageId(resolved);
39411                 }
39412                 if (state.traceEnabled) {
39413                     trace(state.host, ts.Diagnostics.File_0_has_an_unsupported_extension_so_skipping_it, fromFile);
39414                 }
39415             }
39416             // Even if extensions is DtsOnly, we can still look up a .ts file as a result of package.json "types"
39417             var nextExtensions = extensions === Extensions.DtsOnly ? Extensions.TypeScript : extensions;
39418             // Don't do package.json lookup recursively, because Node.js' package lookup doesn't.
39419             return nodeLoadModuleByRelativeName(nextExtensions, candidate, onlyRecordFailures, state, /*considerPackageJson*/ false);
39420         };
39421         var onlyRecordFailuresForPackageFile = packageFile ? !ts.directoryProbablyExists(ts.getDirectoryPath(packageFile), state.host) : undefined;
39422         var onlyRecordFailuresForIndex = onlyRecordFailures || !ts.directoryProbablyExists(candidate, state.host);
39423         var indexPath = ts.combinePaths(candidate, extensions === Extensions.TSConfig ? "tsconfig" : "index");
39424         if (versionPaths && (!packageFile || ts.containsPath(candidate, packageFile))) {
39425             var moduleName = ts.getRelativePathFromDirectory(candidate, packageFile || indexPath, /*ignoreCase*/ false);
39426             if (state.traceEnabled) {
39427                 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);
39428             }
39429             var result = tryLoadModuleUsingPaths(extensions, moduleName, candidate, versionPaths.paths, loader, onlyRecordFailuresForPackageFile || onlyRecordFailuresForIndex, state);
39430             if (result) {
39431                 return removeIgnoredPackageId(result.value);
39432             }
39433         }
39434         // It won't have a `packageId` set, because we disabled `considerPackageJson`.
39435         var packageFileResult = packageFile && removeIgnoredPackageId(loader(extensions, packageFile, onlyRecordFailuresForPackageFile, state));
39436         if (packageFileResult)
39437             return packageFileResult;
39438         return loadModuleFromFile(extensions, indexPath, onlyRecordFailuresForIndex, state);
39439     }
39440     /** Resolve from an arbitrarily specified file. Return `undefined` if it has an unsupported extension. */
39441     function resolvedIfExtensionMatches(extensions, path) {
39442         var ext = ts.tryGetExtensionFromPath(path);
39443         return ext !== undefined && extensionIsOk(extensions, ext) ? { path: path, ext: ext } : undefined;
39444     }
39445     /** True if `extension` is one of the supported `extensions`. */
39446     function extensionIsOk(extensions, extension) {
39447         switch (extensions) {
39448             case Extensions.JavaScript:
39449                 return extension === ".js" /* Js */ || extension === ".jsx" /* Jsx */;
39450             case Extensions.TSConfig:
39451             case Extensions.Json:
39452                 return extension === ".json" /* Json */;
39453             case Extensions.TypeScript:
39454                 return extension === ".ts" /* Ts */ || extension === ".tsx" /* Tsx */ || extension === ".d.ts" /* Dts */;
39455             case Extensions.DtsOnly:
39456                 return extension === ".d.ts" /* Dts */;
39457         }
39458     }
39459     /* @internal */
39460     function parsePackageName(moduleName) {
39461         var idx = moduleName.indexOf(ts.directorySeparator);
39462         if (moduleName[0] === "@") {
39463             idx = moduleName.indexOf(ts.directorySeparator, idx + 1);
39464         }
39465         return idx === -1 ? { packageName: moduleName, rest: "" } : { packageName: moduleName.slice(0, idx), rest: moduleName.slice(idx + 1) };
39466     }
39467     ts.parsePackageName = parsePackageName;
39468     function loadModuleFromNearestNodeModulesDirectory(extensions, moduleName, directory, state, cache, redirectedReference) {
39469         return loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, /*typesScopeOnly*/ false, cache, redirectedReference);
39470     }
39471     function loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, directory, state) {
39472         // Extensions parameter here doesn't actually matter, because typesOnly ensures we're just doing @types lookup, which is always DtsOnly.
39473         return loadModuleFromNearestNodeModulesDirectoryWorker(Extensions.DtsOnly, moduleName, directory, state, /*typesScopeOnly*/ true, /*cache*/ undefined, /*redirectedReference*/ undefined);
39474     }
39475     function loadModuleFromNearestNodeModulesDirectoryWorker(extensions, moduleName, directory, state, typesScopeOnly, cache, redirectedReference) {
39476         var perModuleNameCache = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
39477         return ts.forEachAncestorDirectory(ts.normalizeSlashes(directory), function (ancestorDirectory) {
39478             if (ts.getBaseFileName(ancestorDirectory) !== "node_modules") {
39479                 var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache, moduleName, ancestorDirectory, state);
39480                 if (resolutionFromCache) {
39481                     return resolutionFromCache;
39482                 }
39483                 return toSearchResult(loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, ancestorDirectory, state, typesScopeOnly));
39484             }
39485         });
39486     }
39487     function loadModuleFromImmediateNodeModulesDirectory(extensions, moduleName, directory, state, typesScopeOnly) {
39488         var nodeModulesFolder = ts.combinePaths(directory, "node_modules");
39489         var nodeModulesFolderExists = ts.directoryProbablyExists(nodeModulesFolder, state.host);
39490         if (!nodeModulesFolderExists && state.traceEnabled) {
39491             trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesFolder);
39492         }
39493         var packageResult = typesScopeOnly ? undefined : loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesFolder, nodeModulesFolderExists, state);
39494         if (packageResult) {
39495             return packageResult;
39496         }
39497         if (extensions === Extensions.TypeScript || extensions === Extensions.DtsOnly) {
39498             var nodeModulesAtTypes_1 = ts.combinePaths(nodeModulesFolder, "@types");
39499             var nodeModulesAtTypesExists = nodeModulesFolderExists;
39500             if (nodeModulesFolderExists && !ts.directoryProbablyExists(nodeModulesAtTypes_1, state.host)) {
39501                 if (state.traceEnabled) {
39502                     trace(state.host, ts.Diagnostics.Directory_0_does_not_exist_skipping_all_lookups_in_it, nodeModulesAtTypes_1);
39503                 }
39504                 nodeModulesAtTypesExists = false;
39505             }
39506             return loadModuleFromSpecificNodeModulesDirectory(Extensions.DtsOnly, mangleScopedPackageNameWithTrace(moduleName, state), nodeModulesAtTypes_1, nodeModulesAtTypesExists, state);
39507         }
39508     }
39509     function loadModuleFromSpecificNodeModulesDirectory(extensions, moduleName, nodeModulesDirectory, nodeModulesDirectoryExists, state) {
39510         var candidate = ts.normalizePath(ts.combinePaths(nodeModulesDirectory, moduleName));
39511         // First look for a nested package.json, as in `node_modules/foo/bar/package.json`.
39512         var packageInfo = getPackageJsonInfo(candidate, !nodeModulesDirectoryExists, state);
39513         if (packageInfo) {
39514             var fromFile = loadModuleFromFile(extensions, candidate, !nodeModulesDirectoryExists, state);
39515             if (fromFile) {
39516                 return noPackageId(fromFile);
39517             }
39518             var fromDirectory = loadNodeModuleFromDirectoryWorker(extensions, candidate, !nodeModulesDirectoryExists, state, packageInfo.packageJsonContent, packageInfo.versionPaths);
39519             return withPackageId(packageInfo, fromDirectory);
39520         }
39521         var loader = function (extensions, candidate, onlyRecordFailures, state) {
39522             var pathAndExtension = loadModuleFromFile(extensions, candidate, onlyRecordFailures, state) ||
39523                 loadNodeModuleFromDirectoryWorker(extensions, candidate, onlyRecordFailures, state, packageInfo && packageInfo.packageJsonContent, packageInfo && packageInfo.versionPaths);
39524             return withPackageId(packageInfo, pathAndExtension);
39525         };
39526         var _a = parsePackageName(moduleName), packageName = _a.packageName, rest = _a.rest;
39527         if (rest !== "") { // If "rest" is empty, we just did this search above.
39528             var packageDirectory = ts.combinePaths(nodeModulesDirectory, packageName);
39529             // 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.
39530             packageInfo = getPackageJsonInfo(packageDirectory, !nodeModulesDirectoryExists, state);
39531             if (packageInfo && packageInfo.versionPaths) {
39532                 if (state.traceEnabled) {
39533                     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);
39534                 }
39535                 var packageDirectoryExists = nodeModulesDirectoryExists && ts.directoryProbablyExists(packageDirectory, state.host);
39536                 var fromPaths = tryLoadModuleUsingPaths(extensions, rest, packageDirectory, packageInfo.versionPaths.paths, loader, !packageDirectoryExists, state);
39537                 if (fromPaths) {
39538                     return fromPaths.value;
39539                 }
39540             }
39541         }
39542         return loader(extensions, candidate, !nodeModulesDirectoryExists, state);
39543     }
39544     function tryLoadModuleUsingPaths(extensions, moduleName, baseDirectory, paths, loader, onlyRecordFailures, state) {
39545         var matchedPattern = ts.matchPatternOrExact(ts.getOwnKeys(paths), moduleName);
39546         if (matchedPattern) {
39547             var matchedStar_1 = ts.isString(matchedPattern) ? undefined : ts.matchedText(matchedPattern, moduleName);
39548             var matchedPatternText = ts.isString(matchedPattern) ? matchedPattern : ts.patternText(matchedPattern);
39549             if (state.traceEnabled) {
39550                 trace(state.host, ts.Diagnostics.Module_name_0_matched_pattern_1, moduleName, matchedPatternText);
39551             }
39552             var resolved = ts.forEach(paths[matchedPatternText], function (subst) {
39553                 var path = matchedStar_1 ? subst.replace("*", matchedStar_1) : subst;
39554                 // When baseUrl is not specified, the command line parser resolves relative paths to the config file location.
39555                 var candidate = ts.normalizePath(ts.combinePaths(baseDirectory, path));
39556                 if (state.traceEnabled) {
39557                     trace(state.host, ts.Diagnostics.Trying_substitution_0_candidate_module_location_Colon_1, subst, path);
39558                 }
39559                 // A path mapping may have an extension, in contrast to an import, which should omit it.
39560                 var extension = ts.tryGetExtensionFromPath(candidate);
39561                 if (extension !== undefined) {
39562                     var path_1 = tryFile(candidate, onlyRecordFailures, state);
39563                     if (path_1 !== undefined) {
39564                         return noPackageId({ path: path_1, ext: extension });
39565                     }
39566                 }
39567                 return loader(extensions, candidate, onlyRecordFailures || !ts.directoryProbablyExists(ts.getDirectoryPath(candidate), state.host), state);
39568             });
39569             return { value: resolved };
39570         }
39571     }
39572     /** Double underscores are used in DefinitelyTyped to delimit scoped packages. */
39573     var mangledScopedPackageSeparator = "__";
39574     /** For a scoped package, we must look in `@types/foo__bar` instead of `@types/@foo/bar`. */
39575     function mangleScopedPackageNameWithTrace(packageName, state) {
39576         var mangled = mangleScopedPackageName(packageName);
39577         if (state.traceEnabled && mangled !== packageName) {
39578             trace(state.host, ts.Diagnostics.Scoped_package_detected_looking_in_0, mangled);
39579         }
39580         return mangled;
39581     }
39582     /* @internal */
39583     function getTypesPackageName(packageName) {
39584         return "@types/" + mangleScopedPackageName(packageName);
39585     }
39586     ts.getTypesPackageName = getTypesPackageName;
39587     /* @internal */
39588     function mangleScopedPackageName(packageName) {
39589         if (ts.startsWith(packageName, "@")) {
39590             var replaceSlash = packageName.replace(ts.directorySeparator, mangledScopedPackageSeparator);
39591             if (replaceSlash !== packageName) {
39592                 return replaceSlash.slice(1); // Take off the "@"
39593             }
39594         }
39595         return packageName;
39596     }
39597     ts.mangleScopedPackageName = mangleScopedPackageName;
39598     /* @internal */
39599     function getPackageNameFromTypesPackageName(mangledName) {
39600         var withoutAtTypePrefix = ts.removePrefix(mangledName, "@types/");
39601         if (withoutAtTypePrefix !== mangledName) {
39602             return unmangleScopedPackageName(withoutAtTypePrefix);
39603         }
39604         return mangledName;
39605     }
39606     ts.getPackageNameFromTypesPackageName = getPackageNameFromTypesPackageName;
39607     /* @internal */
39608     function unmangleScopedPackageName(typesPackageName) {
39609         return ts.stringContains(typesPackageName, mangledScopedPackageSeparator) ?
39610             "@" + typesPackageName.replace(mangledScopedPackageSeparator, ts.directorySeparator) :
39611             typesPackageName;
39612     }
39613     ts.unmangleScopedPackageName = unmangleScopedPackageName;
39614     function tryFindNonRelativeModuleNameInCache(cache, moduleName, containingDirectory, state) {
39615         var result = cache && cache.get(containingDirectory);
39616         if (result) {
39617             if (state.traceEnabled) {
39618                 trace(state.host, ts.Diagnostics.Resolution_for_module_0_was_found_in_cache_from_location_1, moduleName, containingDirectory);
39619             }
39620             state.resultFromCache = result;
39621             return { value: result.resolvedModule && { path: result.resolvedModule.resolvedFileName, originalPath: result.resolvedModule.originalPath || true, extension: result.resolvedModule.extension, packageId: result.resolvedModule.packageId } };
39622         }
39623     }
39624     function classicNameResolver(moduleName, containingFile, compilerOptions, host, cache, redirectedReference) {
39625         var traceEnabled = isTraceEnabled(compilerOptions, host);
39626         var failedLookupLocations = [];
39627         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
39628         var containingDirectory = ts.getDirectoryPath(containingFile);
39629         var resolved = tryResolve(Extensions.TypeScript) || tryResolve(Extensions.JavaScript);
39630         // No originalPath because classic resolution doesn't resolve realPath
39631         return createResolvedModuleWithFailedLookupLocations(resolved && resolved.value, /*isExternalLibraryImport*/ false, failedLookupLocations, state.resultFromCache);
39632         function tryResolve(extensions) {
39633             var resolvedUsingSettings = tryLoadModuleUsingOptionalResolutionSettings(extensions, moduleName, containingDirectory, loadModuleFromFileNoPackageId, state);
39634             if (resolvedUsingSettings) {
39635                 return { value: resolvedUsingSettings };
39636             }
39637             if (!ts.isExternalModuleNameRelative(moduleName)) {
39638                 var perModuleNameCache_1 = cache && cache.getOrCreateCacheForModuleName(moduleName, redirectedReference);
39639                 // Climb up parent directories looking for a module.
39640                 var resolved_3 = ts.forEachAncestorDirectory(containingDirectory, function (directory) {
39641                     var resolutionFromCache = tryFindNonRelativeModuleNameInCache(perModuleNameCache_1, moduleName, directory, state);
39642                     if (resolutionFromCache) {
39643                         return resolutionFromCache;
39644                     }
39645                     var searchName = ts.normalizePath(ts.combinePaths(directory, moduleName));
39646                     return toSearchResult(loadModuleFromFileNoPackageId(extensions, searchName, /*onlyRecordFailures*/ false, state));
39647                 });
39648                 if (resolved_3) {
39649                     return resolved_3;
39650                 }
39651                 if (extensions === Extensions.TypeScript) {
39652                     // If we didn't find the file normally, look it up in @types.
39653                     return loadModuleFromNearestNodeModulesDirectoryTypesScope(moduleName, containingDirectory, state);
39654                 }
39655             }
39656             else {
39657                 var candidate = ts.normalizePath(ts.combinePaths(containingDirectory, moduleName));
39658                 return toSearchResult(loadModuleFromFileNoPackageId(extensions, candidate, /*onlyRecordFailures*/ false, state));
39659             }
39660         }
39661     }
39662     ts.classicNameResolver = classicNameResolver;
39663     /**
39664      * A host may load a module from a global cache of typings.
39665      * This is the minumum code needed to expose that functionality; the rest is in the host.
39666      */
39667     /* @internal */
39668     function loadModuleFromGlobalCache(moduleName, projectName, compilerOptions, host, globalCache) {
39669         var traceEnabled = isTraceEnabled(compilerOptions, host);
39670         if (traceEnabled) {
39671             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);
39672         }
39673         var failedLookupLocations = [];
39674         var state = { compilerOptions: compilerOptions, host: host, traceEnabled: traceEnabled, failedLookupLocations: failedLookupLocations };
39675         var resolved = loadModuleFromImmediateNodeModulesDirectory(Extensions.DtsOnly, moduleName, globalCache, state, /*typesScopeOnly*/ false);
39676         return createResolvedModuleWithFailedLookupLocations(resolved, /*isExternalLibraryImport*/ true, failedLookupLocations, state.resultFromCache);
39677     }
39678     ts.loadModuleFromGlobalCache = loadModuleFromGlobalCache;
39679     /**
39680      * Wraps value to SearchResult.
39681      * @returns undefined if value is undefined or { value } otherwise
39682      */
39683     function toSearchResult(value) {
39684         return value !== undefined ? { value: value } : undefined;
39685     }
39686 })(ts || (ts = {}));
39687 /* @internal */
39688 var ts;
39689 (function (ts) {
39690     var ModuleInstanceState;
39691     (function (ModuleInstanceState) {
39692         ModuleInstanceState[ModuleInstanceState["NonInstantiated"] = 0] = "NonInstantiated";
39693         ModuleInstanceState[ModuleInstanceState["Instantiated"] = 1] = "Instantiated";
39694         ModuleInstanceState[ModuleInstanceState["ConstEnumOnly"] = 2] = "ConstEnumOnly";
39695     })(ModuleInstanceState = ts.ModuleInstanceState || (ts.ModuleInstanceState = {}));
39696     function getModuleInstanceState(node, visited) {
39697         if (node.body && !node.body.parent) {
39698             // getModuleInstanceStateForAliasTarget needs to walk up the parent chain, so parent pointers must be set on this tree already
39699             ts.setParent(node.body, node);
39700             ts.setParentRecursive(node.body, /*incremental*/ false);
39701         }
39702         return node.body ? getModuleInstanceStateCached(node.body, visited) : 1 /* Instantiated */;
39703     }
39704     ts.getModuleInstanceState = getModuleInstanceState;
39705     function getModuleInstanceStateCached(node, visited) {
39706         if (visited === void 0) { visited = new ts.Map(); }
39707         var nodeId = ts.getNodeId(node);
39708         if (visited.has(nodeId)) {
39709             return visited.get(nodeId) || 0 /* NonInstantiated */;
39710         }
39711         visited.set(nodeId, undefined);
39712         var result = getModuleInstanceStateWorker(node, visited);
39713         visited.set(nodeId, result);
39714         return result;
39715     }
39716     function getModuleInstanceStateWorker(node, visited) {
39717         // A module is uninstantiated if it contains only
39718         switch (node.kind) {
39719             // 1. interface declarations, type alias declarations
39720             case 253 /* InterfaceDeclaration */:
39721             case 254 /* TypeAliasDeclaration */:
39722                 return 0 /* NonInstantiated */;
39723             // 2. const enum declarations
39724             case 255 /* EnumDeclaration */:
39725                 if (ts.isEnumConst(node)) {
39726                     return 2 /* ConstEnumOnly */;
39727                 }
39728                 break;
39729             // 3. non-exported import declarations
39730             case 261 /* ImportDeclaration */:
39731             case 260 /* ImportEqualsDeclaration */:
39732                 if (!(ts.hasSyntacticModifier(node, 1 /* Export */))) {
39733                     return 0 /* NonInstantiated */;
39734                 }
39735                 break;
39736             // 4. Export alias declarations pointing at only uninstantiated modules or things uninstantiated modules contain
39737             case 267 /* ExportDeclaration */:
39738                 var exportDeclaration = node;
39739                 if (!exportDeclaration.moduleSpecifier && exportDeclaration.exportClause && exportDeclaration.exportClause.kind === 268 /* NamedExports */) {
39740                     var state = 0 /* NonInstantiated */;
39741                     for (var _i = 0, _a = exportDeclaration.exportClause.elements; _i < _a.length; _i++) {
39742                         var specifier = _a[_i];
39743                         var specifierState = getModuleInstanceStateForAliasTarget(specifier, visited);
39744                         if (specifierState > state) {
39745                             state = specifierState;
39746                         }
39747                         if (state === 1 /* Instantiated */) {
39748                             return state;
39749                         }
39750                     }
39751                     return state;
39752                 }
39753                 break;
39754             // 5. other uninstantiated module declarations.
39755             case 257 /* ModuleBlock */: {
39756                 var state_1 = 0 /* NonInstantiated */;
39757                 ts.forEachChild(node, function (n) {
39758                     var childState = getModuleInstanceStateCached(n, visited);
39759                     switch (childState) {
39760                         case 0 /* NonInstantiated */:
39761                             // child is non-instantiated - continue searching
39762                             return;
39763                         case 2 /* ConstEnumOnly */:
39764                             // child is const enum only - record state and continue searching
39765                             state_1 = 2 /* ConstEnumOnly */;
39766                             return;
39767                         case 1 /* Instantiated */:
39768                             // child is instantiated - record state and stop
39769                             state_1 = 1 /* Instantiated */;
39770                             return true;
39771                         default:
39772                             ts.Debug.assertNever(childState);
39773                     }
39774                 });
39775                 return state_1;
39776             }
39777             case 256 /* ModuleDeclaration */:
39778                 return getModuleInstanceState(node, visited);
39779             case 78 /* Identifier */:
39780                 // Only jsdoc typedef definition can exist in jsdoc namespace, and it should
39781                 // be considered the same as type alias
39782                 if (node.isInJSDocNamespace) {
39783                     return 0 /* NonInstantiated */;
39784                 }
39785         }
39786         return 1 /* Instantiated */;
39787     }
39788     function getModuleInstanceStateForAliasTarget(specifier, visited) {
39789         var name = specifier.propertyName || specifier.name;
39790         var p = specifier.parent;
39791         while (p) {
39792             if (ts.isBlock(p) || ts.isModuleBlock(p) || ts.isSourceFile(p)) {
39793                 var statements = p.statements;
39794                 var found = void 0;
39795                 for (var _i = 0, statements_2 = statements; _i < statements_2.length; _i++) {
39796                     var statement = statements_2[_i];
39797                     if (ts.nodeHasName(statement, name)) {
39798                         if (!statement.parent) {
39799                             ts.setParent(statement, p);
39800                             ts.setParentRecursive(statement, /*incremental*/ false);
39801                         }
39802                         var state = getModuleInstanceStateCached(statement, visited);
39803                         if (found === undefined || state > found) {
39804                             found = state;
39805                         }
39806                         if (found === 1 /* Instantiated */) {
39807                             return found;
39808                         }
39809                     }
39810                 }
39811                 if (found !== undefined) {
39812                     return found;
39813                 }
39814             }
39815             p = p.parent;
39816         }
39817         return 1 /* Instantiated */; // Couldn't locate, assume could refer to a value
39818     }
39819     var ContainerFlags;
39820     (function (ContainerFlags) {
39821         // The current node is not a container, and no container manipulation should happen before
39822         // recursing into it.
39823         ContainerFlags[ContainerFlags["None"] = 0] = "None";
39824         // The current node is a container.  It should be set as the current container (and block-
39825         // container) before recursing into it.  The current node does not have locals.  Examples:
39826         //
39827         //      Classes, ObjectLiterals, TypeLiterals, Interfaces...
39828         ContainerFlags[ContainerFlags["IsContainer"] = 1] = "IsContainer";
39829         // The current node is a block-scoped-container.  It should be set as the current block-
39830         // container before recursing into it.  Examples:
39831         //
39832         //      Blocks (when not parented by functions), Catch clauses, For/For-in/For-of statements...
39833         ContainerFlags[ContainerFlags["IsBlockScopedContainer"] = 2] = "IsBlockScopedContainer";
39834         // The current node is the container of a control flow path. The current control flow should
39835         // be saved and restored, and a new control flow initialized within the container.
39836         ContainerFlags[ContainerFlags["IsControlFlowContainer"] = 4] = "IsControlFlowContainer";
39837         ContainerFlags[ContainerFlags["IsFunctionLike"] = 8] = "IsFunctionLike";
39838         ContainerFlags[ContainerFlags["IsFunctionExpression"] = 16] = "IsFunctionExpression";
39839         ContainerFlags[ContainerFlags["HasLocals"] = 32] = "HasLocals";
39840         ContainerFlags[ContainerFlags["IsInterface"] = 64] = "IsInterface";
39841         ContainerFlags[ContainerFlags["IsObjectLiteralOrClassExpressionMethod"] = 128] = "IsObjectLiteralOrClassExpressionMethod";
39842     })(ContainerFlags || (ContainerFlags = {}));
39843     function initFlowNode(node) {
39844         ts.Debug.attachFlowNodeDebugInfo(node);
39845         return node;
39846     }
39847     var binder = createBinder();
39848     function bindSourceFile(file, options) {
39849         var tracingData = ["bind" /* Bind */, "bindSourceFile", { path: file.path }];
39850         ts.tracing.begin.apply(ts.tracing, tracingData);
39851         ts.performance.mark("beforeBind");
39852         ts.perfLogger.logStartBindFile("" + file.fileName);
39853         binder(file, options);
39854         ts.perfLogger.logStopBindFile();
39855         ts.performance.mark("afterBind");
39856         ts.performance.measure("Bind", "beforeBind", "afterBind");
39857         ts.tracing.end.apply(ts.tracing, tracingData);
39858     }
39859     ts.bindSourceFile = bindSourceFile;
39860     function createBinder() {
39861         var file;
39862         var options;
39863         var languageVersion;
39864         var parent;
39865         var container;
39866         var thisParentContainer; // Container one level up
39867         var blockScopeContainer;
39868         var lastContainer;
39869         var delayedTypeAliases;
39870         var seenThisKeyword;
39871         // state used by control flow analysis
39872         var currentFlow;
39873         var currentBreakTarget;
39874         var currentContinueTarget;
39875         var currentReturnTarget;
39876         var currentTrueTarget;
39877         var currentFalseTarget;
39878         var currentExceptionTarget;
39879         var preSwitchCaseFlow;
39880         var activeLabelList;
39881         var hasExplicitReturn;
39882         // state used for emit helpers
39883         var emitFlags;
39884         // If this file is an external module, then it is automatically in strict-mode according to
39885         // ES6.  If it is not an external module, then we'll determine if it is in strict mode or
39886         // not depending on if we see "use strict" in certain places or if we hit a class/namespace
39887         // or if compiler options contain alwaysStrict.
39888         var inStrictMode;
39889         // If we are binding an assignment pattern, we will bind certain expressions differently.
39890         var inAssignmentPattern = false;
39891         var symbolCount = 0;
39892         var Symbol;
39893         var classifiableNames;
39894         var unreachableFlow = { flags: 1 /* Unreachable */ };
39895         var reportedUnreachableFlow = { flags: 1 /* Unreachable */ };
39896         /**
39897          * Inside the binder, we may create a diagnostic for an as-yet unbound node (with potentially no parent pointers, implying no accessible source file)
39898          * 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)
39899          * This version of `createDiagnosticForNode` uses the binder's context to account for this, and always yields correct diagnostics even in these situations.
39900          */
39901         function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
39902             return ts.createDiagnosticForNodeInSourceFile(ts.getSourceFileOfNode(node) || file, node, message, arg0, arg1, arg2);
39903         }
39904         function bindSourceFile(f, opts) {
39905             file = f;
39906             options = opts;
39907             languageVersion = ts.getEmitScriptTarget(options);
39908             inStrictMode = bindInStrictMode(file, opts);
39909             classifiableNames = new ts.Set();
39910             symbolCount = 0;
39911             Symbol = ts.objectAllocator.getSymbolConstructor();
39912             // Attach debugging information if necessary
39913             ts.Debug.attachFlowNodeDebugInfo(unreachableFlow);
39914             ts.Debug.attachFlowNodeDebugInfo(reportedUnreachableFlow);
39915             if (!file.locals) {
39916                 bind(file);
39917                 file.symbolCount = symbolCount;
39918                 file.classifiableNames = classifiableNames;
39919                 delayedBindJSDocTypedefTag();
39920             }
39921             file = undefined;
39922             options = undefined;
39923             languageVersion = undefined;
39924             parent = undefined;
39925             container = undefined;
39926             thisParentContainer = undefined;
39927             blockScopeContainer = undefined;
39928             lastContainer = undefined;
39929             delayedTypeAliases = undefined;
39930             seenThisKeyword = false;
39931             currentFlow = undefined;
39932             currentBreakTarget = undefined;
39933             currentContinueTarget = undefined;
39934             currentReturnTarget = undefined;
39935             currentTrueTarget = undefined;
39936             currentFalseTarget = undefined;
39937             currentExceptionTarget = undefined;
39938             activeLabelList = undefined;
39939             hasExplicitReturn = false;
39940             inAssignmentPattern = false;
39941             emitFlags = 0 /* None */;
39942         }
39943         return bindSourceFile;
39944         function bindInStrictMode(file, opts) {
39945             if (ts.getStrictOptionValue(opts, "alwaysStrict") && !file.isDeclarationFile) {
39946                 // bind in strict mode source files with alwaysStrict option
39947                 return true;
39948             }
39949             else {
39950                 return !!file.externalModuleIndicator;
39951             }
39952         }
39953         function createSymbol(flags, name) {
39954             symbolCount++;
39955             return new Symbol(flags, name);
39956         }
39957         function addDeclarationToSymbol(symbol, node, symbolFlags) {
39958             symbol.flags |= symbolFlags;
39959             node.symbol = symbol;
39960             symbol.declarations = ts.appendIfUnique(symbol.declarations, node);
39961             if (symbolFlags & (32 /* Class */ | 384 /* Enum */ | 1536 /* Module */ | 3 /* Variable */) && !symbol.exports) {
39962                 symbol.exports = ts.createSymbolTable();
39963             }
39964             if (symbolFlags & (32 /* Class */ | 64 /* Interface */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && !symbol.members) {
39965                 symbol.members = ts.createSymbolTable();
39966             }
39967             // On merge of const enum module with class or function, reset const enum only flag (namespaces will already recalculate)
39968             if (symbol.constEnumOnlyModule && (symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */))) {
39969                 symbol.constEnumOnlyModule = false;
39970             }
39971             if (symbolFlags & 111551 /* Value */) {
39972                 ts.setValueDeclaration(symbol, node);
39973             }
39974         }
39975         // Should not be called on a declaration with a computed property name,
39976         // unless it is a well known Symbol.
39977         function getDeclarationName(node) {
39978             if (node.kind === 266 /* ExportAssignment */) {
39979                 return node.isExportEquals ? "export=" /* ExportEquals */ : "default" /* Default */;
39980             }
39981             var name = ts.getNameOfDeclaration(node);
39982             if (name) {
39983                 if (ts.isAmbientModule(node)) {
39984                     var moduleName = ts.getTextOfIdentifierOrLiteral(name);
39985                     return (ts.isGlobalScopeAugmentation(node) ? "__global" : "\"" + moduleName + "\"");
39986                 }
39987                 if (name.kind === 158 /* ComputedPropertyName */) {
39988                     var nameExpression = name.expression;
39989                     // treat computed property names where expression is string/numeric literal as just string/numeric literal
39990                     if (ts.isStringOrNumericLiteralLike(nameExpression)) {
39991                         return ts.escapeLeadingUnderscores(nameExpression.text);
39992                     }
39993                     if (ts.isSignedNumericLiteral(nameExpression)) {
39994                         return ts.tokenToString(nameExpression.operator) + nameExpression.operand.text;
39995                     }
39996                     ts.Debug.assert(ts.isWellKnownSymbolSyntactically(nameExpression));
39997                     return ts.getPropertyNameForKnownSymbolName(ts.idText(nameExpression.name));
39998                 }
39999                 if (ts.isWellKnownSymbolSyntactically(name)) {
40000                     return ts.getPropertyNameForKnownSymbolName(ts.idText(name.name));
40001                 }
40002                 if (ts.isPrivateIdentifier(name)) {
40003                     // containingClass exists because private names only allowed inside classes
40004                     var containingClass = ts.getContainingClass(node);
40005                     if (!containingClass) {
40006                         // we can get here in cases where there is already a parse error.
40007                         return undefined;
40008                     }
40009                     var containingClassSymbol = containingClass.symbol;
40010                     return ts.getSymbolNameForPrivateIdentifier(containingClassSymbol, name.escapedText);
40011                 }
40012                 return ts.isPropertyNameLiteral(name) ? ts.getEscapedTextOfIdentifierOrLiteral(name) : undefined;
40013             }
40014             switch (node.kind) {
40015                 case 166 /* Constructor */:
40016                     return "__constructor" /* Constructor */;
40017                 case 174 /* FunctionType */:
40018                 case 169 /* CallSignature */:
40019                 case 313 /* JSDocSignature */:
40020                     return "__call" /* Call */;
40021                 case 175 /* ConstructorType */:
40022                 case 170 /* ConstructSignature */:
40023                     return "__new" /* New */;
40024                 case 171 /* IndexSignature */:
40025                     return "__index" /* Index */;
40026                 case 267 /* ExportDeclaration */:
40027                     return "__export" /* ExportStar */;
40028                 case 297 /* SourceFile */:
40029                     // json file should behave as
40030                     // module.exports = ...
40031                     return "export=" /* ExportEquals */;
40032                 case 216 /* BinaryExpression */:
40033                     if (ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */) {
40034                         // module.exports = ...
40035                         return "export=" /* ExportEquals */;
40036                     }
40037                     ts.Debug.fail("Unknown binary declaration kind");
40038                     break;
40039                 case 308 /* JSDocFunctionType */:
40040                     return (ts.isJSDocConstructSignature(node) ? "__new" /* New */ : "__call" /* Call */);
40041                 case 160 /* Parameter */:
40042                     // Parameters with names are handled at the top of this function.  Parameters
40043                     // without names can only come from JSDocFunctionTypes.
40044                     ts.Debug.assert(node.parent.kind === 308 /* JSDocFunctionType */, "Impossible parameter parent kind", function () { return "parent is: " + (ts.SyntaxKind ? ts.SyntaxKind[node.parent.kind] : node.parent.kind) + ", expected JSDocFunctionType"; });
40045                     var functionType = node.parent;
40046                     var index = functionType.parameters.indexOf(node);
40047                     return "arg" + index;
40048             }
40049         }
40050         function getDisplayName(node) {
40051             return ts.isNamedDeclaration(node) ? ts.declarationNameToString(node.name) : ts.unescapeLeadingUnderscores(ts.Debug.checkDefined(getDeclarationName(node)));
40052         }
40053         /**
40054          * Declares a Symbol for the node and adds it to symbols. Reports errors for conflicting identifier names.
40055          * @param symbolTable - The symbol table which node will be added to.
40056          * @param parent - node's parent declaration.
40057          * @param node - The declaration to be added to the symbol table
40058          * @param includes - The SymbolFlags that node has in addition to its declaration type (eg: export, ambient, etc.)
40059          * @param excludes - The flags which node cannot be declared alongside in a symbol table. Used to report forbidden declarations.
40060          */
40061         function declareSymbol(symbolTable, parent, node, includes, excludes, isReplaceableByMethod) {
40062             ts.Debug.assert(!ts.hasDynamicName(node));
40063             var isDefaultExport = ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node) && node.name.escapedText === "default";
40064             // The exported symbol for an export default function/class node is always named "default"
40065             var name = isDefaultExport && parent ? "default" /* Default */ : getDeclarationName(node);
40066             var symbol;
40067             if (name === undefined) {
40068                 symbol = createSymbol(0 /* None */, "__missing" /* Missing */);
40069             }
40070             else {
40071                 // Check and see if the symbol table already has a symbol with this name.  If not,
40072                 // create a new symbol with this name and add it to the table.  Note that we don't
40073                 // give the new symbol any flags *yet*.  This ensures that it will not conflict
40074                 // with the 'excludes' flags we pass in.
40075                 //
40076                 // If we do get an existing symbol, see if it conflicts with the new symbol we're
40077                 // creating.  For example, a 'var' symbol and a 'class' symbol will conflict within
40078                 // the same symbol table.  If we have a conflict, report the issue on each
40079                 // declaration we have for this symbol, and then create a new symbol for this
40080                 // declaration.
40081                 //
40082                 // Note that when properties declared in Javascript constructors
40083                 // (marked by isReplaceableByMethod) conflict with another symbol, the property loses.
40084                 // Always. This allows the common Javascript pattern of overwriting a prototype method
40085                 // with an bound instance method of the same type: `this.method = this.method.bind(this)`
40086                 //
40087                 // If we created a new symbol, either because we didn't have a symbol with this name
40088                 // in the symbol table, or we conflicted with an existing symbol, then just add this
40089                 // node as the sole declaration of the new symbol.
40090                 //
40091                 // Otherwise, we'll be merging into a compatible existing symbol (for example when
40092                 // you have multiple 'vars' with the same name in the same container).  In this case
40093                 // just add this node into the declarations list of the symbol.
40094                 symbol = symbolTable.get(name);
40095                 if (includes & 2885600 /* Classifiable */) {
40096                     classifiableNames.add(name);
40097                 }
40098                 if (!symbol) {
40099                     symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
40100                     if (isReplaceableByMethod)
40101                         symbol.isReplaceableByMethod = true;
40102                 }
40103                 else if (isReplaceableByMethod && !symbol.isReplaceableByMethod) {
40104                     // A symbol already exists, so don't add this as a declaration.
40105                     return symbol;
40106                 }
40107                 else if (symbol.flags & excludes) {
40108                     if (symbol.isReplaceableByMethod) {
40109                         // Javascript constructor-declared symbols can be discarded in favor of
40110                         // prototype symbols like methods.
40111                         symbolTable.set(name, symbol = createSymbol(0 /* None */, name));
40112                     }
40113                     else if (!(includes & 3 /* Variable */ && symbol.flags & 67108864 /* Assignment */)) {
40114                         // Assignment declarations are allowed to merge with variables, no matter what other flags they have.
40115                         if (ts.isNamedDeclaration(node)) {
40116                             ts.setParent(node.name, node);
40117                         }
40118                         // Report errors every position with duplicate declaration
40119                         // Report errors on previous encountered declarations
40120                         var message_1 = symbol.flags & 2 /* BlockScopedVariable */
40121                             ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
40122                             : ts.Diagnostics.Duplicate_identifier_0;
40123                         var messageNeedsName_1 = true;
40124                         if (symbol.flags & 384 /* Enum */ || includes & 384 /* Enum */) {
40125                             message_1 = ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations;
40126                             messageNeedsName_1 = false;
40127                         }
40128                         var multipleDefaultExports_1 = false;
40129                         if (ts.length(symbol.declarations)) {
40130                             // If the current node is a default export of some sort, then check if
40131                             // there are any other default exports that we need to error on.
40132                             // We'll know whether we have other default exports depending on if `symbol` already has a declaration list set.
40133                             if (isDefaultExport) {
40134                                 message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
40135                                 messageNeedsName_1 = false;
40136                                 multipleDefaultExports_1 = true;
40137                             }
40138                             else {
40139                                 // This is to properly report an error in the case "export default { }" is after export default of class declaration or function declaration.
40140                                 // Error on multiple export default in the following case:
40141                                 // 1. multiple export default of class declaration or function declaration by checking NodeFlags.Default
40142                                 // 2. multiple export default of export assignment. This one doesn't have NodeFlags.Default on (as export default doesn't considered as modifiers)
40143                                 if (symbol.declarations && symbol.declarations.length &&
40144                                     (node.kind === 266 /* ExportAssignment */ && !node.isExportEquals)) {
40145                                     message_1 = ts.Diagnostics.A_module_cannot_have_multiple_default_exports;
40146                                     messageNeedsName_1 = false;
40147                                     multipleDefaultExports_1 = true;
40148                                 }
40149                             }
40150                         }
40151                         var relatedInformation_1 = [];
40152                         if (ts.isTypeAliasDeclaration(node) && ts.nodeIsMissing(node.type) && ts.hasSyntacticModifier(node, 1 /* Export */) && symbol.flags & (2097152 /* Alias */ | 788968 /* Type */ | 1920 /* Namespace */)) {
40153                             // export type T; - may have meant export type { T }?
40154                             relatedInformation_1.push(createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_0, "export type { " + ts.unescapeLeadingUnderscores(node.name.escapedText) + " }"));
40155                         }
40156                         var declarationName_1 = ts.getNameOfDeclaration(node) || node;
40157                         ts.forEach(symbol.declarations, function (declaration, index) {
40158                             var decl = ts.getNameOfDeclaration(declaration) || declaration;
40159                             var diag = createDiagnosticForNode(decl, message_1, messageNeedsName_1 ? getDisplayName(declaration) : undefined);
40160                             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);
40161                             if (multipleDefaultExports_1) {
40162                                 relatedInformation_1.push(createDiagnosticForNode(decl, ts.Diagnostics.The_first_export_default_is_here));
40163                             }
40164                         });
40165                         var diag = createDiagnosticForNode(declarationName_1, message_1, messageNeedsName_1 ? getDisplayName(node) : undefined);
40166                         file.bindDiagnostics.push(ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInformation_1)));
40167                         symbol = createSymbol(0 /* None */, name);
40168                     }
40169                 }
40170             }
40171             addDeclarationToSymbol(symbol, node, includes);
40172             if (symbol.parent) {
40173                 ts.Debug.assert(symbol.parent === parent, "Existing symbol parent should match new one");
40174             }
40175             else {
40176                 symbol.parent = parent;
40177             }
40178             return symbol;
40179         }
40180         function declareModuleMember(node, symbolFlags, symbolExcludes) {
40181             var hasExportModifier = !!(ts.getCombinedModifierFlags(node) & 1 /* Export */) || jsdocTreatAsExported(node);
40182             if (symbolFlags & 2097152 /* Alias */) {
40183                 if (node.kind === 270 /* ExportSpecifier */ || (node.kind === 260 /* ImportEqualsDeclaration */ && hasExportModifier)) {
40184                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
40185                 }
40186                 else {
40187                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
40188                 }
40189             }
40190             else {
40191                 // Exported module members are given 2 symbols: A local symbol that is classified with an ExportValue flag,
40192                 // and an associated export symbol with all the correct flags set on it. There are 2 main reasons:
40193                 //
40194                 //   1. We treat locals and exports of the same name as mutually exclusive within a container.
40195                 //      That means the binder will issue a Duplicate Identifier error if you mix locals and exports
40196                 //      with the same name in the same container.
40197                 //      TODO: Make this a more specific error and decouple it from the exclusion logic.
40198                 //   2. When we checkIdentifier in the checker, we set its resolved symbol to the local symbol,
40199                 //      but return the export symbol (by calling getExportSymbolOfValueSymbolIfExported). That way
40200                 //      when the emitter comes back to it, it knows not to qualify the name if it was found in a containing scope.
40201                 // NOTE: Nested ambient modules always should go to to 'locals' table to prevent their automatic merge
40202                 //       during global merging in the checker. Why? The only case when ambient module is permitted inside another module is module augmentation
40203                 //       and this case is specially handled. Module augmentations should only be merged with original module definition
40204                 //       and should never be merged directly with other augmentation, and the latter case would be possible if automatic merge is allowed.
40205                 if (ts.isJSDocTypeAlias(node))
40206                     ts.Debug.assert(ts.isInJSFile(node)); // We shouldn't add symbols for JSDoc nodes if not in a JS file.
40207                 if (!ts.isAmbientModule(node) && (hasExportModifier || container.flags & 64 /* ExportContext */)) {
40208                     if (!container.locals || (ts.hasSyntacticModifier(node, 512 /* Default */) && !getDeclarationName(node))) {
40209                         return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes); // No local symbol for an unnamed default!
40210                     }
40211                     var exportKind = symbolFlags & 111551 /* Value */ ? 1048576 /* ExportValue */ : 0;
40212                     var local = declareSymbol(container.locals, /*parent*/ undefined, node, exportKind, symbolExcludes);
40213                     local.exportSymbol = declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
40214                     node.localSymbol = local;
40215                     return local;
40216                 }
40217                 else {
40218                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
40219                 }
40220             }
40221         }
40222         function jsdocTreatAsExported(node) {
40223             if (node.parent && ts.isModuleDeclaration(node)) {
40224                 node = node.parent;
40225             }
40226             if (!ts.isJSDocTypeAlias(node))
40227                 return false;
40228             // jsdoc typedef handling is a bit of a doozy, but to summarize, treat the typedef as exported if:
40229             // 1. It has an explicit name (since by default typedefs are always directly exported, either at the top level or in a container), or
40230             if (!ts.isJSDocEnumTag(node) && !!node.fullName)
40231                 return true;
40232             // 2. The thing a nameless typedef pulls its name from is implicitly a direct export (either by assignment or actual export flag).
40233             var declName = ts.getNameOfDeclaration(node);
40234             if (!declName)
40235                 return false;
40236             if (ts.isPropertyAccessEntityNameExpression(declName.parent) && isTopLevelNamespaceAssignment(declName.parent))
40237                 return true;
40238             if (ts.isDeclaration(declName.parent) && ts.getCombinedModifierFlags(declName.parent) & 1 /* Export */)
40239                 return true;
40240             // This could potentially be simplified by having `delayedBindJSDocTypedefTag` pass in an override for `hasExportModifier`, since it should
40241             // already have calculated and branched on most of this.
40242             return false;
40243         }
40244         // All container nodes are kept on a linked list in declaration order. This list is used by
40245         // the getLocalNameOfContainer function in the type checker to validate that the local name
40246         // used for a container is unique.
40247         function bindContainer(node, containerFlags) {
40248             // Before we recurse into a node's children, we first save the existing parent, container
40249             // and block-container.  Then after we pop out of processing the children, we restore
40250             // these saved values.
40251             var saveContainer = container;
40252             var saveThisParentContainer = thisParentContainer;
40253             var savedBlockScopeContainer = blockScopeContainer;
40254             // Depending on what kind of node this is, we may have to adjust the current container
40255             // and block-container.   If the current node is a container, then it is automatically
40256             // considered the current block-container as well.  Also, for containers that we know
40257             // may contain locals, we eagerly initialize the .locals field. We do this because
40258             // it's highly likely that the .locals will be needed to place some child in (for example,
40259             // a parameter, or variable declaration).
40260             //
40261             // However, we do not proactively create the .locals for block-containers because it's
40262             // totally normal and common for block-containers to never actually have a block-scoped
40263             // variable in them.  We don't want to end up allocating an object for every 'block' we
40264             // run into when most of them won't be necessary.
40265             //
40266             // Finally, if this is a block-container, then we clear out any existing .locals object
40267             // it may contain within it.  This happens in incremental scenarios.  Because we can be
40268             // reusing a node from a previous compilation, that node may have had 'locals' created
40269             // for it.  We must clear this so we don't accidentally move any stale data forward from
40270             // a previous compilation.
40271             if (containerFlags & 1 /* IsContainer */) {
40272                 if (node.kind !== 209 /* ArrowFunction */) {
40273                     thisParentContainer = container;
40274                 }
40275                 container = blockScopeContainer = node;
40276                 if (containerFlags & 32 /* HasLocals */) {
40277                     container.locals = ts.createSymbolTable();
40278                 }
40279                 addToContainerChain(container);
40280             }
40281             else if (containerFlags & 2 /* IsBlockScopedContainer */) {
40282                 blockScopeContainer = node;
40283                 blockScopeContainer.locals = undefined;
40284             }
40285             if (containerFlags & 4 /* IsControlFlowContainer */) {
40286                 var saveCurrentFlow = currentFlow;
40287                 var saveBreakTarget = currentBreakTarget;
40288                 var saveContinueTarget = currentContinueTarget;
40289                 var saveReturnTarget = currentReturnTarget;
40290                 var saveExceptionTarget = currentExceptionTarget;
40291                 var saveActiveLabelList = activeLabelList;
40292                 var saveHasExplicitReturn = hasExplicitReturn;
40293                 var isIIFE = containerFlags & 16 /* IsFunctionExpression */ && !ts.hasSyntacticModifier(node, 256 /* Async */) &&
40294                     !node.asteriskToken && !!ts.getImmediatelyInvokedFunctionExpression(node);
40295                 // A non-async, non-generator IIFE is considered part of the containing control flow. Return statements behave
40296                 // similarly to break statements that exit to a label just past the statement body.
40297                 if (!isIIFE) {
40298                     currentFlow = initFlowNode({ flags: 2 /* Start */ });
40299                     if (containerFlags & (16 /* IsFunctionExpression */ | 128 /* IsObjectLiteralOrClassExpressionMethod */)) {
40300                         currentFlow.node = node;
40301                     }
40302                 }
40303                 // We create a return control flow graph for IIFEs and constructors. For constructors
40304                 // we use the return control flow graph in strict property initialization checks.
40305                 currentReturnTarget = isIIFE || node.kind === 166 /* Constructor */ || (ts.isInJSFile && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) ? createBranchLabel() : undefined;
40306                 currentExceptionTarget = undefined;
40307                 currentBreakTarget = undefined;
40308                 currentContinueTarget = undefined;
40309                 activeLabelList = undefined;
40310                 hasExplicitReturn = false;
40311                 bindChildren(node);
40312                 // Reset all reachability check related flags on node (for incremental scenarios)
40313                 node.flags &= ~2816 /* ReachabilityAndEmitFlags */;
40314                 if (!(currentFlow.flags & 1 /* Unreachable */) && containerFlags & 8 /* IsFunctionLike */ && ts.nodeIsPresent(node.body)) {
40315                     node.flags |= 256 /* HasImplicitReturn */;
40316                     if (hasExplicitReturn)
40317                         node.flags |= 512 /* HasExplicitReturn */;
40318                     node.endFlowNode = currentFlow;
40319                 }
40320                 if (node.kind === 297 /* SourceFile */) {
40321                     node.flags |= emitFlags;
40322                 }
40323                 if (currentReturnTarget) {
40324                     addAntecedent(currentReturnTarget, currentFlow);
40325                     currentFlow = finishFlowLabel(currentReturnTarget);
40326                     if (node.kind === 166 /* Constructor */ || (ts.isInJSFile && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */))) {
40327                         node.returnFlowNode = currentFlow;
40328                     }
40329                 }
40330                 if (!isIIFE) {
40331                     currentFlow = saveCurrentFlow;
40332                 }
40333                 currentBreakTarget = saveBreakTarget;
40334                 currentContinueTarget = saveContinueTarget;
40335                 currentReturnTarget = saveReturnTarget;
40336                 currentExceptionTarget = saveExceptionTarget;
40337                 activeLabelList = saveActiveLabelList;
40338                 hasExplicitReturn = saveHasExplicitReturn;
40339             }
40340             else if (containerFlags & 64 /* IsInterface */) {
40341                 seenThisKeyword = false;
40342                 bindChildren(node);
40343                 node.flags = seenThisKeyword ? node.flags | 128 /* ContainsThis */ : node.flags & ~128 /* ContainsThis */;
40344             }
40345             else {
40346                 bindChildren(node);
40347             }
40348             container = saveContainer;
40349             thisParentContainer = saveThisParentContainer;
40350             blockScopeContainer = savedBlockScopeContainer;
40351         }
40352         function bindEachFunctionsFirst(nodes) {
40353             bindEach(nodes, function (n) { return n.kind === 251 /* FunctionDeclaration */ ? bind(n) : undefined; });
40354             bindEach(nodes, function (n) { return n.kind !== 251 /* FunctionDeclaration */ ? bind(n) : undefined; });
40355         }
40356         function bindEach(nodes, bindFunction) {
40357             if (bindFunction === void 0) { bindFunction = bind; }
40358             if (nodes === undefined) {
40359                 return;
40360             }
40361             ts.forEach(nodes, bindFunction);
40362         }
40363         function bindEachChild(node) {
40364             ts.forEachChild(node, bind, bindEach);
40365         }
40366         function bindChildren(node) {
40367             var saveInAssignmentPattern = inAssignmentPattern;
40368             // Most nodes aren't valid in an assignment pattern, so we clear the value here
40369             // and set it before we descend into nodes that could actually be part of an assignment pattern.
40370             inAssignmentPattern = false;
40371             if (checkUnreachable(node)) {
40372                 bindEachChild(node);
40373                 bindJSDoc(node);
40374                 inAssignmentPattern = saveInAssignmentPattern;
40375                 return;
40376             }
40377             if (node.kind >= 232 /* FirstStatement */ && node.kind <= 248 /* LastStatement */ && !options.allowUnreachableCode) {
40378                 node.flowNode = currentFlow;
40379             }
40380             switch (node.kind) {
40381                 case 236 /* WhileStatement */:
40382                     bindWhileStatement(node);
40383                     break;
40384                 case 235 /* DoStatement */:
40385                     bindDoStatement(node);
40386                     break;
40387                 case 237 /* ForStatement */:
40388                     bindForStatement(node);
40389                     break;
40390                 case 238 /* ForInStatement */:
40391                 case 239 /* ForOfStatement */:
40392                     bindForInOrForOfStatement(node);
40393                     break;
40394                 case 234 /* IfStatement */:
40395                     bindIfStatement(node);
40396                     break;
40397                 case 242 /* ReturnStatement */:
40398                 case 246 /* ThrowStatement */:
40399                     bindReturnOrThrow(node);
40400                     break;
40401                 case 241 /* BreakStatement */:
40402                 case 240 /* ContinueStatement */:
40403                     bindBreakOrContinueStatement(node);
40404                     break;
40405                 case 247 /* TryStatement */:
40406                     bindTryStatement(node);
40407                     break;
40408                 case 244 /* SwitchStatement */:
40409                     bindSwitchStatement(node);
40410                     break;
40411                 case 258 /* CaseBlock */:
40412                     bindCaseBlock(node);
40413                     break;
40414                 case 284 /* CaseClause */:
40415                     bindCaseClause(node);
40416                     break;
40417                 case 233 /* ExpressionStatement */:
40418                     bindExpressionStatement(node);
40419                     break;
40420                 case 245 /* LabeledStatement */:
40421                     bindLabeledStatement(node);
40422                     break;
40423                 case 214 /* PrefixUnaryExpression */:
40424                     bindPrefixUnaryExpressionFlow(node);
40425                     break;
40426                 case 215 /* PostfixUnaryExpression */:
40427                     bindPostfixUnaryExpressionFlow(node);
40428                     break;
40429                 case 216 /* BinaryExpression */:
40430                     if (ts.isDestructuringAssignment(node)) {
40431                         // Carry over whether we are in an assignment pattern to
40432                         // binary expressions that could actually be an initializer
40433                         inAssignmentPattern = saveInAssignmentPattern;
40434                         bindDestructuringAssignmentFlow(node);
40435                         return;
40436                     }
40437                     bindBinaryExpressionFlow(node);
40438                     break;
40439                 case 210 /* DeleteExpression */:
40440                     bindDeleteExpressionFlow(node);
40441                     break;
40442                 case 217 /* ConditionalExpression */:
40443                     bindConditionalExpressionFlow(node);
40444                     break;
40445                 case 249 /* VariableDeclaration */:
40446                     bindVariableDeclarationFlow(node);
40447                     break;
40448                 case 201 /* PropertyAccessExpression */:
40449                 case 202 /* ElementAccessExpression */:
40450                     bindAccessExpressionFlow(node);
40451                     break;
40452                 case 203 /* CallExpression */:
40453                     bindCallExpressionFlow(node);
40454                     break;
40455                 case 225 /* NonNullExpression */:
40456                     bindNonNullExpressionFlow(node);
40457                     break;
40458                 case 331 /* JSDocTypedefTag */:
40459                 case 324 /* JSDocCallbackTag */:
40460                 case 325 /* JSDocEnumTag */:
40461                     bindJSDocTypeAlias(node);
40462                     break;
40463                 // In source files and blocks, bind functions first to match hoisting that occurs at runtime
40464                 case 297 /* SourceFile */: {
40465                     bindEachFunctionsFirst(node.statements);
40466                     bind(node.endOfFileToken);
40467                     break;
40468                 }
40469                 case 230 /* Block */:
40470                 case 257 /* ModuleBlock */:
40471                     bindEachFunctionsFirst(node.statements);
40472                     break;
40473                 case 198 /* BindingElement */:
40474                     bindBindingElementFlow(node);
40475                     break;
40476                 case 200 /* ObjectLiteralExpression */:
40477                 case 199 /* ArrayLiteralExpression */:
40478                 case 288 /* PropertyAssignment */:
40479                 case 220 /* SpreadElement */:
40480                     // Carry over whether we are in an assignment pattern of Object and Array literals
40481                     // as well as their children that are valid assignment targets.
40482                     inAssignmentPattern = saveInAssignmentPattern;
40483                 // falls through
40484                 default:
40485                     bindEachChild(node);
40486                     break;
40487             }
40488             bindJSDoc(node);
40489             inAssignmentPattern = saveInAssignmentPattern;
40490         }
40491         function isNarrowingExpression(expr) {
40492             switch (expr.kind) {
40493                 case 78 /* Identifier */:
40494                 case 79 /* PrivateIdentifier */:
40495                 case 107 /* ThisKeyword */:
40496                 case 201 /* PropertyAccessExpression */:
40497                 case 202 /* ElementAccessExpression */:
40498                     return containsNarrowableReference(expr);
40499                 case 203 /* CallExpression */:
40500                     return hasNarrowableArgument(expr);
40501                 case 207 /* ParenthesizedExpression */:
40502                 case 225 /* NonNullExpression */:
40503                     return isNarrowingExpression(expr.expression);
40504                 case 216 /* BinaryExpression */:
40505                     return isNarrowingBinaryExpression(expr);
40506                 case 214 /* PrefixUnaryExpression */:
40507                     return expr.operator === 53 /* ExclamationToken */ && isNarrowingExpression(expr.operand);
40508                 case 211 /* TypeOfExpression */:
40509                     return isNarrowingExpression(expr.expression);
40510             }
40511             return false;
40512         }
40513         function isNarrowableReference(expr) {
40514             return expr.kind === 78 /* Identifier */ || expr.kind === 79 /* PrivateIdentifier */ || expr.kind === 107 /* ThisKeyword */ || expr.kind === 105 /* SuperKeyword */ ||
40515                 (ts.isPropertyAccessExpression(expr) || ts.isNonNullExpression(expr) || ts.isParenthesizedExpression(expr)) && isNarrowableReference(expr.expression) ||
40516                 ts.isBinaryExpression(expr) && expr.operatorToken.kind === 27 /* CommaToken */ && isNarrowableReference(expr.right) ||
40517                 ts.isElementAccessExpression(expr) && ts.isStringOrNumericLiteralLike(expr.argumentExpression) && isNarrowableReference(expr.expression) ||
40518                 ts.isAssignmentExpression(expr) && isNarrowableReference(expr.left);
40519         }
40520         function containsNarrowableReference(expr) {
40521             return isNarrowableReference(expr) || ts.isOptionalChain(expr) && containsNarrowableReference(expr.expression);
40522         }
40523         function hasNarrowableArgument(expr) {
40524             if (expr.arguments) {
40525                 for (var _i = 0, _a = expr.arguments; _i < _a.length; _i++) {
40526                     var argument = _a[_i];
40527                     if (containsNarrowableReference(argument)) {
40528                         return true;
40529                     }
40530                 }
40531             }
40532             if (expr.expression.kind === 201 /* PropertyAccessExpression */ &&
40533                 containsNarrowableReference(expr.expression.expression)) {
40534                 return true;
40535             }
40536             return false;
40537         }
40538         function isNarrowingTypeofOperands(expr1, expr2) {
40539             return ts.isTypeOfExpression(expr1) && isNarrowableOperand(expr1.expression) && ts.isStringLiteralLike(expr2);
40540         }
40541         function isNarrowableInOperands(left, right) {
40542             return ts.isStringLiteralLike(left) && isNarrowingExpression(right);
40543         }
40544         function isNarrowingBinaryExpression(expr) {
40545             switch (expr.operatorToken.kind) {
40546                 case 62 /* EqualsToken */:
40547                 case 74 /* BarBarEqualsToken */:
40548                 case 75 /* AmpersandAmpersandEqualsToken */:
40549                 case 76 /* QuestionQuestionEqualsToken */:
40550                     return containsNarrowableReference(expr.left);
40551                 case 34 /* EqualsEqualsToken */:
40552                 case 35 /* ExclamationEqualsToken */:
40553                 case 36 /* EqualsEqualsEqualsToken */:
40554                 case 37 /* ExclamationEqualsEqualsToken */:
40555                     return isNarrowableOperand(expr.left) || isNarrowableOperand(expr.right) ||
40556                         isNarrowingTypeofOperands(expr.right, expr.left) || isNarrowingTypeofOperands(expr.left, expr.right);
40557                 case 101 /* InstanceOfKeyword */:
40558                     return isNarrowableOperand(expr.left);
40559                 case 100 /* InKeyword */:
40560                     return isNarrowableInOperands(expr.left, expr.right);
40561                 case 27 /* CommaToken */:
40562                     return isNarrowingExpression(expr.right);
40563             }
40564             return false;
40565         }
40566         function isNarrowableOperand(expr) {
40567             switch (expr.kind) {
40568                 case 207 /* ParenthesizedExpression */:
40569                     return isNarrowableOperand(expr.expression);
40570                 case 216 /* BinaryExpression */:
40571                     switch (expr.operatorToken.kind) {
40572                         case 62 /* EqualsToken */:
40573                             return isNarrowableOperand(expr.left);
40574                         case 27 /* CommaToken */:
40575                             return isNarrowableOperand(expr.right);
40576                     }
40577             }
40578             return containsNarrowableReference(expr);
40579         }
40580         function createBranchLabel() {
40581             return initFlowNode({ flags: 4 /* BranchLabel */, antecedents: undefined });
40582         }
40583         function createLoopLabel() {
40584             return initFlowNode({ flags: 8 /* LoopLabel */, antecedents: undefined });
40585         }
40586         function createReduceLabel(target, antecedents, antecedent) {
40587             return initFlowNode({ flags: 1024 /* ReduceLabel */, target: target, antecedents: antecedents, antecedent: antecedent });
40588         }
40589         function setFlowNodeReferenced(flow) {
40590             // On first reference we set the Referenced flag, thereafter we set the Shared flag
40591             flow.flags |= flow.flags & 2048 /* Referenced */ ? 4096 /* Shared */ : 2048 /* Referenced */;
40592         }
40593         function addAntecedent(label, antecedent) {
40594             if (!(antecedent.flags & 1 /* Unreachable */) && !ts.contains(label.antecedents, antecedent)) {
40595                 (label.antecedents || (label.antecedents = [])).push(antecedent);
40596                 setFlowNodeReferenced(antecedent);
40597             }
40598         }
40599         function createFlowCondition(flags, antecedent, expression) {
40600             if (antecedent.flags & 1 /* Unreachable */) {
40601                 return antecedent;
40602             }
40603             if (!expression) {
40604                 return flags & 32 /* TrueCondition */ ? antecedent : unreachableFlow;
40605             }
40606             if ((expression.kind === 109 /* TrueKeyword */ && flags & 64 /* FalseCondition */ ||
40607                 expression.kind === 94 /* FalseKeyword */ && flags & 32 /* TrueCondition */) &&
40608                 !ts.isExpressionOfOptionalChainRoot(expression) && !ts.isNullishCoalesce(expression.parent)) {
40609                 return unreachableFlow;
40610             }
40611             if (!isNarrowingExpression(expression)) {
40612                 return antecedent;
40613             }
40614             setFlowNodeReferenced(antecedent);
40615             return initFlowNode({ flags: flags, antecedent: antecedent, node: expression });
40616         }
40617         function createFlowSwitchClause(antecedent, switchStatement, clauseStart, clauseEnd) {
40618             setFlowNodeReferenced(antecedent);
40619             return initFlowNode({ flags: 128 /* SwitchClause */, antecedent: antecedent, switchStatement: switchStatement, clauseStart: clauseStart, clauseEnd: clauseEnd });
40620         }
40621         function createFlowMutation(flags, antecedent, node) {
40622             setFlowNodeReferenced(antecedent);
40623             var result = initFlowNode({ flags: flags, antecedent: antecedent, node: node });
40624             if (currentExceptionTarget) {
40625                 addAntecedent(currentExceptionTarget, result);
40626             }
40627             return result;
40628         }
40629         function createFlowCall(antecedent, node) {
40630             setFlowNodeReferenced(antecedent);
40631             return initFlowNode({ flags: 512 /* Call */, antecedent: antecedent, node: node });
40632         }
40633         function finishFlowLabel(flow) {
40634             var antecedents = flow.antecedents;
40635             if (!antecedents) {
40636                 return unreachableFlow;
40637             }
40638             if (antecedents.length === 1) {
40639                 return antecedents[0];
40640             }
40641             return flow;
40642         }
40643         function isStatementCondition(node) {
40644             var parent = node.parent;
40645             switch (parent.kind) {
40646                 case 234 /* IfStatement */:
40647                 case 236 /* WhileStatement */:
40648                 case 235 /* DoStatement */:
40649                     return parent.expression === node;
40650                 case 237 /* ForStatement */:
40651                 case 217 /* ConditionalExpression */:
40652                     return parent.condition === node;
40653             }
40654             return false;
40655         }
40656         function isLogicalExpression(node) {
40657             while (true) {
40658                 if (node.kind === 207 /* ParenthesizedExpression */) {
40659                     node = node.expression;
40660                 }
40661                 else if (node.kind === 214 /* PrefixUnaryExpression */ && node.operator === 53 /* ExclamationToken */) {
40662                     node = node.operand;
40663                 }
40664                 else {
40665                     return node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ ||
40666                         node.operatorToken.kind === 56 /* BarBarToken */ ||
40667                         node.operatorToken.kind === 60 /* QuestionQuestionToken */);
40668                 }
40669             }
40670         }
40671         function isLogicalAssignmentExpression(node) {
40672             node = ts.skipParentheses(node);
40673             return ts.isBinaryExpression(node) && ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind);
40674         }
40675         function isTopLevelLogicalExpression(node) {
40676             while (ts.isParenthesizedExpression(node.parent) ||
40677                 ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 53 /* ExclamationToken */) {
40678                 node = node.parent;
40679             }
40680             return !isStatementCondition(node) &&
40681                 !isLogicalAssignmentExpression(node.parent) &&
40682                 !isLogicalExpression(node.parent) &&
40683                 !(ts.isOptionalChain(node.parent) && node.parent.expression === node);
40684         }
40685         function doWithConditionalBranches(action, value, trueTarget, falseTarget) {
40686             var savedTrueTarget = currentTrueTarget;
40687             var savedFalseTarget = currentFalseTarget;
40688             currentTrueTarget = trueTarget;
40689             currentFalseTarget = falseTarget;
40690             action(value);
40691             currentTrueTarget = savedTrueTarget;
40692             currentFalseTarget = savedFalseTarget;
40693         }
40694         function bindCondition(node, trueTarget, falseTarget) {
40695             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
40696             if (!node || !isLogicalAssignmentExpression(node) && !isLogicalExpression(node) && !(ts.isOptionalChain(node) && ts.isOutermostOptionalChain(node))) {
40697                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
40698                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
40699             }
40700         }
40701         function bindIterativeStatement(node, breakTarget, continueTarget) {
40702             var saveBreakTarget = currentBreakTarget;
40703             var saveContinueTarget = currentContinueTarget;
40704             currentBreakTarget = breakTarget;
40705             currentContinueTarget = continueTarget;
40706             bind(node);
40707             currentBreakTarget = saveBreakTarget;
40708             currentContinueTarget = saveContinueTarget;
40709         }
40710         function setContinueTarget(node, target) {
40711             var label = activeLabelList;
40712             while (label && node.parent.kind === 245 /* LabeledStatement */) {
40713                 label.continueTarget = target;
40714                 label = label.next;
40715                 node = node.parent;
40716             }
40717             return target;
40718         }
40719         function bindWhileStatement(node) {
40720             var preWhileLabel = setContinueTarget(node, createLoopLabel());
40721             var preBodyLabel = createBranchLabel();
40722             var postWhileLabel = createBranchLabel();
40723             addAntecedent(preWhileLabel, currentFlow);
40724             currentFlow = preWhileLabel;
40725             bindCondition(node.expression, preBodyLabel, postWhileLabel);
40726             currentFlow = finishFlowLabel(preBodyLabel);
40727             bindIterativeStatement(node.statement, postWhileLabel, preWhileLabel);
40728             addAntecedent(preWhileLabel, currentFlow);
40729             currentFlow = finishFlowLabel(postWhileLabel);
40730         }
40731         function bindDoStatement(node) {
40732             var preDoLabel = createLoopLabel();
40733             var preConditionLabel = setContinueTarget(node, createBranchLabel());
40734             var postDoLabel = createBranchLabel();
40735             addAntecedent(preDoLabel, currentFlow);
40736             currentFlow = preDoLabel;
40737             bindIterativeStatement(node.statement, postDoLabel, preConditionLabel);
40738             addAntecedent(preConditionLabel, currentFlow);
40739             currentFlow = finishFlowLabel(preConditionLabel);
40740             bindCondition(node.expression, preDoLabel, postDoLabel);
40741             currentFlow = finishFlowLabel(postDoLabel);
40742         }
40743         function bindForStatement(node) {
40744             var preLoopLabel = setContinueTarget(node, createLoopLabel());
40745             var preBodyLabel = createBranchLabel();
40746             var postLoopLabel = createBranchLabel();
40747             bind(node.initializer);
40748             addAntecedent(preLoopLabel, currentFlow);
40749             currentFlow = preLoopLabel;
40750             bindCondition(node.condition, preBodyLabel, postLoopLabel);
40751             currentFlow = finishFlowLabel(preBodyLabel);
40752             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
40753             bind(node.incrementor);
40754             addAntecedent(preLoopLabel, currentFlow);
40755             currentFlow = finishFlowLabel(postLoopLabel);
40756         }
40757         function bindForInOrForOfStatement(node) {
40758             var preLoopLabel = setContinueTarget(node, createLoopLabel());
40759             var postLoopLabel = createBranchLabel();
40760             bind(node.expression);
40761             addAntecedent(preLoopLabel, currentFlow);
40762             currentFlow = preLoopLabel;
40763             if (node.kind === 239 /* ForOfStatement */) {
40764                 bind(node.awaitModifier);
40765             }
40766             addAntecedent(postLoopLabel, currentFlow);
40767             bind(node.initializer);
40768             if (node.initializer.kind !== 250 /* VariableDeclarationList */) {
40769                 bindAssignmentTargetFlow(node.initializer);
40770             }
40771             bindIterativeStatement(node.statement, postLoopLabel, preLoopLabel);
40772             addAntecedent(preLoopLabel, currentFlow);
40773             currentFlow = finishFlowLabel(postLoopLabel);
40774         }
40775         function bindIfStatement(node) {
40776             var thenLabel = createBranchLabel();
40777             var elseLabel = createBranchLabel();
40778             var postIfLabel = createBranchLabel();
40779             bindCondition(node.expression, thenLabel, elseLabel);
40780             currentFlow = finishFlowLabel(thenLabel);
40781             bind(node.thenStatement);
40782             addAntecedent(postIfLabel, currentFlow);
40783             currentFlow = finishFlowLabel(elseLabel);
40784             bind(node.elseStatement);
40785             addAntecedent(postIfLabel, currentFlow);
40786             currentFlow = finishFlowLabel(postIfLabel);
40787         }
40788         function bindReturnOrThrow(node) {
40789             bind(node.expression);
40790             if (node.kind === 242 /* ReturnStatement */) {
40791                 hasExplicitReturn = true;
40792                 if (currentReturnTarget) {
40793                     addAntecedent(currentReturnTarget, currentFlow);
40794                 }
40795             }
40796             currentFlow = unreachableFlow;
40797         }
40798         function findActiveLabel(name) {
40799             for (var label = activeLabelList; label; label = label.next) {
40800                 if (label.name === name) {
40801                     return label;
40802                 }
40803             }
40804             return undefined;
40805         }
40806         function bindBreakOrContinueFlow(node, breakTarget, continueTarget) {
40807             var flowLabel = node.kind === 241 /* BreakStatement */ ? breakTarget : continueTarget;
40808             if (flowLabel) {
40809                 addAntecedent(flowLabel, currentFlow);
40810                 currentFlow = unreachableFlow;
40811             }
40812         }
40813         function bindBreakOrContinueStatement(node) {
40814             bind(node.label);
40815             if (node.label) {
40816                 var activeLabel = findActiveLabel(node.label.escapedText);
40817                 if (activeLabel) {
40818                     activeLabel.referenced = true;
40819                     bindBreakOrContinueFlow(node, activeLabel.breakTarget, activeLabel.continueTarget);
40820                 }
40821             }
40822             else {
40823                 bindBreakOrContinueFlow(node, currentBreakTarget, currentContinueTarget);
40824             }
40825         }
40826         function bindTryStatement(node) {
40827             // We conservatively assume that *any* code in the try block can cause an exception, but we only need
40828             // to track code that causes mutations (because only mutations widen the possible control flow type of
40829             // a variable). The exceptionLabel is the target label for control flows that result from exceptions.
40830             // We add all mutation flow nodes as antecedents of this label such that we can analyze them as possible
40831             // antecedents of the start of catch or finally blocks. Furthermore, we add the current control flow to
40832             // represent exceptions that occur before any mutations.
40833             var saveReturnTarget = currentReturnTarget;
40834             var saveExceptionTarget = currentExceptionTarget;
40835             var normalExitLabel = createBranchLabel();
40836             var returnLabel = createBranchLabel();
40837             var exceptionLabel = createBranchLabel();
40838             if (node.finallyBlock) {
40839                 currentReturnTarget = returnLabel;
40840             }
40841             addAntecedent(exceptionLabel, currentFlow);
40842             currentExceptionTarget = exceptionLabel;
40843             bind(node.tryBlock);
40844             addAntecedent(normalExitLabel, currentFlow);
40845             if (node.catchClause) {
40846                 // Start of catch clause is the target of exceptions from try block.
40847                 currentFlow = finishFlowLabel(exceptionLabel);
40848                 // The currentExceptionTarget now represents control flows from exceptions in the catch clause.
40849                 // Effectively, in a try-catch-finally, if an exception occurs in the try block, the catch block
40850                 // acts like a second try block.
40851                 exceptionLabel = createBranchLabel();
40852                 addAntecedent(exceptionLabel, currentFlow);
40853                 currentExceptionTarget = exceptionLabel;
40854                 bind(node.catchClause);
40855                 addAntecedent(normalExitLabel, currentFlow);
40856             }
40857             currentReturnTarget = saveReturnTarget;
40858             currentExceptionTarget = saveExceptionTarget;
40859             if (node.finallyBlock) {
40860                 // Possible ways control can reach the finally block:
40861                 // 1) Normal completion of try block of a try-finally or try-catch-finally
40862                 // 2) Normal completion of catch block (following exception in try block) of a try-catch-finally
40863                 // 3) Return in try or catch block of a try-finally or try-catch-finally
40864                 // 4) Exception in try block of a try-finally
40865                 // 5) Exception in catch block of a try-catch-finally
40866                 // When analyzing a control flow graph that starts inside a finally block we want to consider all
40867                 // five possibilities above. However, when analyzing a control flow graph that starts outside (past)
40868                 // the finally block, we only want to consider the first two (if we're past a finally block then it
40869                 // must have completed normally). Likewise, when analyzing a control flow graph from return statements
40870                 // in try or catch blocks in an IIFE, we only want to consider the third. To make this possible, we
40871                 // inject a ReduceLabel node into the control flow graph. This node contains an alternate reduced
40872                 // set of antecedents for the pre-finally label. As control flow analysis passes by a ReduceLabel
40873                 // node, the pre-finally label is temporarily switched to the reduced antecedent set.
40874                 var finallyLabel = createBranchLabel();
40875                 finallyLabel.antecedents = ts.concatenate(ts.concatenate(normalExitLabel.antecedents, exceptionLabel.antecedents), returnLabel.antecedents);
40876                 currentFlow = finallyLabel;
40877                 bind(node.finallyBlock);
40878                 if (currentFlow.flags & 1 /* Unreachable */) {
40879                     // If the end of the finally block is unreachable, the end of the entire try statement is unreachable.
40880                     currentFlow = unreachableFlow;
40881                 }
40882                 else {
40883                     // If we have an IIFE return target and return statements in the try or catch blocks, add a control
40884                     // flow that goes back through the finally block and back through only the return statements.
40885                     if (currentReturnTarget && returnLabel.antecedents) {
40886                         addAntecedent(currentReturnTarget, createReduceLabel(finallyLabel, returnLabel.antecedents, currentFlow));
40887                     }
40888                     // If we have an outer exception target (i.e. a containing try-finally or try-catch-finally), add a
40889                     // control flow that goes back through the finally blok and back through each possible exception source.
40890                     if (currentExceptionTarget && exceptionLabel.antecedents) {
40891                         addAntecedent(currentExceptionTarget, createReduceLabel(finallyLabel, exceptionLabel.antecedents, currentFlow));
40892                     }
40893                     // If the end of the finally block is reachable, but the end of the try and catch blocks are not,
40894                     // convert the current flow to unreachable. For example, 'try { return 1; } finally { ... }' should
40895                     // result in an unreachable current control flow.
40896                     currentFlow = normalExitLabel.antecedents ? createReduceLabel(finallyLabel, normalExitLabel.antecedents, currentFlow) : unreachableFlow;
40897                 }
40898             }
40899             else {
40900                 currentFlow = finishFlowLabel(normalExitLabel);
40901             }
40902         }
40903         function bindSwitchStatement(node) {
40904             var postSwitchLabel = createBranchLabel();
40905             bind(node.expression);
40906             var saveBreakTarget = currentBreakTarget;
40907             var savePreSwitchCaseFlow = preSwitchCaseFlow;
40908             currentBreakTarget = postSwitchLabel;
40909             preSwitchCaseFlow = currentFlow;
40910             bind(node.caseBlock);
40911             addAntecedent(postSwitchLabel, currentFlow);
40912             var hasDefault = ts.forEach(node.caseBlock.clauses, function (c) { return c.kind === 285 /* DefaultClause */; });
40913             // We mark a switch statement as possibly exhaustive if it has no default clause and if all
40914             // case clauses have unreachable end points (e.g. they all return). Note, we no longer need
40915             // this property in control flow analysis, it's there only for backwards compatibility.
40916             node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
40917             if (!hasDefault) {
40918                 addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
40919             }
40920             currentBreakTarget = saveBreakTarget;
40921             preSwitchCaseFlow = savePreSwitchCaseFlow;
40922             currentFlow = finishFlowLabel(postSwitchLabel);
40923         }
40924         function bindCaseBlock(node) {
40925             var clauses = node.clauses;
40926             var isNarrowingSwitch = isNarrowingExpression(node.parent.expression);
40927             var fallthroughFlow = unreachableFlow;
40928             for (var i = 0; i < clauses.length; i++) {
40929                 var clauseStart = i;
40930                 while (!clauses[i].statements.length && i + 1 < clauses.length) {
40931                     bind(clauses[i]);
40932                     i++;
40933                 }
40934                 var preCaseLabel = createBranchLabel();
40935                 addAntecedent(preCaseLabel, isNarrowingSwitch ? createFlowSwitchClause(preSwitchCaseFlow, node.parent, clauseStart, i + 1) : preSwitchCaseFlow);
40936                 addAntecedent(preCaseLabel, fallthroughFlow);
40937                 currentFlow = finishFlowLabel(preCaseLabel);
40938                 var clause = clauses[i];
40939                 bind(clause);
40940                 fallthroughFlow = currentFlow;
40941                 if (!(currentFlow.flags & 1 /* Unreachable */) && i !== clauses.length - 1 && options.noFallthroughCasesInSwitch) {
40942                     clause.fallthroughFlowNode = currentFlow;
40943                 }
40944             }
40945         }
40946         function bindCaseClause(node) {
40947             var saveCurrentFlow = currentFlow;
40948             currentFlow = preSwitchCaseFlow;
40949             bind(node.expression);
40950             currentFlow = saveCurrentFlow;
40951             bindEach(node.statements);
40952         }
40953         function bindExpressionStatement(node) {
40954             bind(node.expression);
40955             maybeBindExpressionFlowIfCall(node.expression);
40956         }
40957         function maybeBindExpressionFlowIfCall(node) {
40958             // A top level or LHS of comma expression call expression with a dotted function name and at least one argument
40959             // is potentially an assertion and is therefore included in the control flow.
40960             if (node.kind === 203 /* CallExpression */) {
40961                 var call = node;
40962                 if (ts.isDottedName(call.expression) && call.expression.kind !== 105 /* SuperKeyword */) {
40963                     currentFlow = createFlowCall(currentFlow, call);
40964                 }
40965             }
40966         }
40967         function bindLabeledStatement(node) {
40968             var postStatementLabel = createBranchLabel();
40969             activeLabelList = {
40970                 next: activeLabelList,
40971                 name: node.label.escapedText,
40972                 breakTarget: postStatementLabel,
40973                 continueTarget: undefined,
40974                 referenced: false
40975             };
40976             bind(node.label);
40977             bind(node.statement);
40978             if (!activeLabelList.referenced && !options.allowUnusedLabels) {
40979                 errorOrSuggestionOnNode(ts.unusedLabelIsError(options), node.label, ts.Diagnostics.Unused_label);
40980             }
40981             activeLabelList = activeLabelList.next;
40982             addAntecedent(postStatementLabel, currentFlow);
40983             currentFlow = finishFlowLabel(postStatementLabel);
40984         }
40985         function bindDestructuringTargetFlow(node) {
40986             if (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */) {
40987                 bindAssignmentTargetFlow(node.left);
40988             }
40989             else {
40990                 bindAssignmentTargetFlow(node);
40991             }
40992         }
40993         function bindAssignmentTargetFlow(node) {
40994             if (isNarrowableReference(node)) {
40995                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
40996             }
40997             else if (node.kind === 199 /* ArrayLiteralExpression */) {
40998                 for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
40999                     var e = _a[_i];
41000                     if (e.kind === 220 /* SpreadElement */) {
41001                         bindAssignmentTargetFlow(e.expression);
41002                     }
41003                     else {
41004                         bindDestructuringTargetFlow(e);
41005                     }
41006                 }
41007             }
41008             else if (node.kind === 200 /* ObjectLiteralExpression */) {
41009                 for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
41010                     var p = _c[_b];
41011                     if (p.kind === 288 /* PropertyAssignment */) {
41012                         bindDestructuringTargetFlow(p.initializer);
41013                     }
41014                     else if (p.kind === 289 /* ShorthandPropertyAssignment */) {
41015                         bindAssignmentTargetFlow(p.name);
41016                     }
41017                     else if (p.kind === 290 /* SpreadAssignment */) {
41018                         bindAssignmentTargetFlow(p.expression);
41019                     }
41020                 }
41021             }
41022         }
41023         function bindLogicalLikeExpression(node, trueTarget, falseTarget) {
41024             var preRightLabel = createBranchLabel();
41025             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ || node.operatorToken.kind === 75 /* AmpersandAmpersandEqualsToken */) {
41026                 bindCondition(node.left, preRightLabel, falseTarget);
41027             }
41028             else {
41029                 bindCondition(node.left, trueTarget, preRightLabel);
41030             }
41031             currentFlow = finishFlowLabel(preRightLabel);
41032             bind(node.operatorToken);
41033             if (ts.isLogicalOrCoalescingAssignmentOperator(node.operatorToken.kind)) {
41034                 doWithConditionalBranches(bind, node.right, trueTarget, falseTarget);
41035                 bindAssignmentTargetFlow(node.left);
41036                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41037                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41038             }
41039             else {
41040                 bindCondition(node.right, trueTarget, falseTarget);
41041             }
41042         }
41043         function bindPrefixUnaryExpressionFlow(node) {
41044             if (node.operator === 53 /* ExclamationToken */) {
41045                 var saveTrueTarget = currentTrueTarget;
41046                 currentTrueTarget = currentFalseTarget;
41047                 currentFalseTarget = saveTrueTarget;
41048                 bindEachChild(node);
41049                 currentFalseTarget = currentTrueTarget;
41050                 currentTrueTarget = saveTrueTarget;
41051             }
41052             else {
41053                 bindEachChild(node);
41054                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
41055                     bindAssignmentTargetFlow(node.operand);
41056                 }
41057             }
41058         }
41059         function bindPostfixUnaryExpressionFlow(node) {
41060             bindEachChild(node);
41061             if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
41062                 bindAssignmentTargetFlow(node.operand);
41063             }
41064         }
41065         function bindDestructuringAssignmentFlow(node) {
41066             if (inAssignmentPattern) {
41067                 inAssignmentPattern = false;
41068                 bind(node.operatorToken);
41069                 bind(node.right);
41070                 inAssignmentPattern = true;
41071                 bind(node.left);
41072             }
41073             else {
41074                 inAssignmentPattern = true;
41075                 bind(node.left);
41076                 inAssignmentPattern = false;
41077                 bind(node.operatorToken);
41078                 bind(node.right);
41079             }
41080             bindAssignmentTargetFlow(node.left);
41081         }
41082         var BindBinaryExpressionFlowState;
41083         (function (BindBinaryExpressionFlowState) {
41084             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindThenBindChildren"] = 0] = "BindThenBindChildren";
41085             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["MaybeBindLeft"] = 1] = "MaybeBindLeft";
41086             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindToken"] = 2] = "BindToken";
41087             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["BindRight"] = 3] = "BindRight";
41088             BindBinaryExpressionFlowState[BindBinaryExpressionFlowState["FinishBind"] = 4] = "FinishBind";
41089         })(BindBinaryExpressionFlowState || (BindBinaryExpressionFlowState = {}));
41090         function bindBinaryExpressionFlow(node) {
41091             var workStacks = {
41092                 expr: [node],
41093                 state: [1 /* MaybeBindLeft */],
41094                 inStrictMode: [undefined],
41095                 parent: [undefined],
41096             };
41097             var stackIndex = 0;
41098             while (stackIndex >= 0) {
41099                 node = workStacks.expr[stackIndex];
41100                 switch (workStacks.state[stackIndex]) {
41101                     case 0 /* BindThenBindChildren */: {
41102                         // This state is used only when recuring, to emulate the work that `bind` does before
41103                         // reaching `bindChildren`. A normal call to `bindBinaryExpressionFlow` will already have done this work.
41104                         ts.setParent(node, parent);
41105                         var saveInStrictMode = inStrictMode;
41106                         bindWorker(node);
41107                         var saveParent = parent;
41108                         parent = node;
41109                         advanceState(1 /* MaybeBindLeft */, saveInStrictMode, saveParent);
41110                         break;
41111                     }
41112                     case 1 /* MaybeBindLeft */: {
41113                         var operator = node.operatorToken.kind;
41114                         // TODO: bindLogicalExpression is recursive - if we want to handle deeply nested `&&` expressions
41115                         // we'll need to handle the `bindLogicalExpression` scenarios in this state machine, too
41116                         // For now, though, since the common cases are chained `+`, leaving it recursive is fine
41117                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */ ||
41118                             ts.isLogicalOrCoalescingAssignmentOperator(operator)) {
41119                             if (isTopLevelLogicalExpression(node)) {
41120                                 var postExpressionLabel = createBranchLabel();
41121                                 bindLogicalLikeExpression(node, postExpressionLabel, postExpressionLabel);
41122                                 currentFlow = finishFlowLabel(postExpressionLabel);
41123                             }
41124                             else {
41125                                 bindLogicalLikeExpression(node, currentTrueTarget, currentFalseTarget);
41126                             }
41127                             completeNode();
41128                         }
41129                         else {
41130                             advanceState(2 /* BindToken */);
41131                             maybeBind(node.left);
41132                         }
41133                         break;
41134                     }
41135                     case 2 /* BindToken */: {
41136                         if (node.operatorToken.kind === 27 /* CommaToken */) {
41137                             maybeBindExpressionFlowIfCall(node.left);
41138                         }
41139                         advanceState(3 /* BindRight */);
41140                         maybeBind(node.operatorToken);
41141                         break;
41142                     }
41143                     case 3 /* BindRight */: {
41144                         advanceState(4 /* FinishBind */);
41145                         maybeBind(node.right);
41146                         break;
41147                     }
41148                     case 4 /* FinishBind */: {
41149                         var operator = node.operatorToken.kind;
41150                         if (ts.isAssignmentOperator(operator) && !ts.isAssignmentTarget(node)) {
41151                             bindAssignmentTargetFlow(node.left);
41152                             if (operator === 62 /* EqualsToken */ && node.left.kind === 202 /* ElementAccessExpression */) {
41153                                 var elementAccess = node.left;
41154                                 if (isNarrowableOperand(elementAccess.expression)) {
41155                                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
41156                                 }
41157                             }
41158                         }
41159                         completeNode();
41160                         break;
41161                     }
41162                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for bindBinaryExpressionFlow");
41163                 }
41164             }
41165             /**
41166              * Note that `advanceState` sets the _current_ head state, and that `maybeBind` potentially pushes on a new
41167              * head state; so `advanceState` must be called before any `maybeBind` during a state's execution.
41168              */
41169             function advanceState(state, isInStrictMode, parent) {
41170                 workStacks.state[stackIndex] = state;
41171                 if (isInStrictMode !== undefined) {
41172                     workStacks.inStrictMode[stackIndex] = isInStrictMode;
41173                 }
41174                 if (parent !== undefined) {
41175                     workStacks.parent[stackIndex] = parent;
41176                 }
41177             }
41178             function completeNode() {
41179                 if (workStacks.inStrictMode[stackIndex] !== undefined) {
41180                     inStrictMode = workStacks.inStrictMode[stackIndex];
41181                     parent = workStacks.parent[stackIndex];
41182                 }
41183                 stackIndex--;
41184             }
41185             /**
41186              * If `node` is a BinaryExpression, adds it to the local work stack, otherwise recursively binds it
41187              */
41188             function maybeBind(node) {
41189                 if (node && ts.isBinaryExpression(node) && !ts.isDestructuringAssignment(node)) {
41190                     stackIndex++;
41191                     workStacks.expr[stackIndex] = node;
41192                     workStacks.state[stackIndex] = 0 /* BindThenBindChildren */;
41193                     workStacks.inStrictMode[stackIndex] = undefined;
41194                     workStacks.parent[stackIndex] = undefined;
41195                 }
41196                 else {
41197                     bind(node);
41198                 }
41199             }
41200         }
41201         function bindDeleteExpressionFlow(node) {
41202             bindEachChild(node);
41203             if (node.expression.kind === 201 /* PropertyAccessExpression */) {
41204                 bindAssignmentTargetFlow(node.expression);
41205             }
41206         }
41207         function bindConditionalExpressionFlow(node) {
41208             var trueLabel = createBranchLabel();
41209             var falseLabel = createBranchLabel();
41210             var postExpressionLabel = createBranchLabel();
41211             bindCondition(node.condition, trueLabel, falseLabel);
41212             currentFlow = finishFlowLabel(trueLabel);
41213             bind(node.questionToken);
41214             bind(node.whenTrue);
41215             addAntecedent(postExpressionLabel, currentFlow);
41216             currentFlow = finishFlowLabel(falseLabel);
41217             bind(node.colonToken);
41218             bind(node.whenFalse);
41219             addAntecedent(postExpressionLabel, currentFlow);
41220             currentFlow = finishFlowLabel(postExpressionLabel);
41221         }
41222         function bindInitializedVariableFlow(node) {
41223             var name = !ts.isOmittedExpression(node) ? node.name : undefined;
41224             if (ts.isBindingPattern(name)) {
41225                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
41226                     var child = _a[_i];
41227                     bindInitializedVariableFlow(child);
41228                 }
41229             }
41230             else {
41231                 currentFlow = createFlowMutation(16 /* Assignment */, currentFlow, node);
41232             }
41233         }
41234         function bindVariableDeclarationFlow(node) {
41235             bindEachChild(node);
41236             if (node.initializer || ts.isForInOrOfStatement(node.parent.parent)) {
41237                 bindInitializedVariableFlow(node);
41238             }
41239         }
41240         function bindBindingElementFlow(node) {
41241             if (ts.isBindingPattern(node.name)) {
41242                 // When evaluating a binding pattern, the initializer is evaluated before the binding pattern, per:
41243                 // - https://tc39.es/ecma262/#sec-destructuring-binding-patterns-runtime-semantics-iteratorbindinginitialization
41244                 //   - `BindingElement: BindingPattern Initializer?`
41245                 // - https://tc39.es/ecma262/#sec-runtime-semantics-keyedbindinginitialization
41246                 //   - `BindingElement: BindingPattern Initializer?`
41247                 bindEach(node.decorators);
41248                 bindEach(node.modifiers);
41249                 bind(node.dotDotDotToken);
41250                 bind(node.propertyName);
41251                 bind(node.initializer);
41252                 bind(node.name);
41253             }
41254             else {
41255                 bindEachChild(node);
41256             }
41257         }
41258         function bindJSDocTypeAlias(node) {
41259             ts.setParent(node.tagName, node);
41260             if (node.kind !== 325 /* JSDocEnumTag */ && node.fullName) {
41261                 ts.setParent(node.fullName, node);
41262                 ts.setParentRecursive(node.fullName, /*incremental*/ false);
41263             }
41264         }
41265         function bindJSDocClassTag(node) {
41266             bindEachChild(node);
41267             var host = ts.getHostSignatureFromJSDoc(node);
41268             if (host && host.kind !== 165 /* MethodDeclaration */) {
41269                 addDeclarationToSymbol(host.symbol, host, 32 /* Class */);
41270             }
41271         }
41272         function bindOptionalExpression(node, trueTarget, falseTarget) {
41273             doWithConditionalBranches(bind, node, trueTarget, falseTarget);
41274             if (!ts.isOptionalChain(node) || ts.isOutermostOptionalChain(node)) {
41275                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41276                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41277             }
41278         }
41279         function bindOptionalChainRest(node) {
41280             switch (node.kind) {
41281                 case 201 /* PropertyAccessExpression */:
41282                     bind(node.questionDotToken);
41283                     bind(node.name);
41284                     break;
41285                 case 202 /* ElementAccessExpression */:
41286                     bind(node.questionDotToken);
41287                     bind(node.argumentExpression);
41288                     break;
41289                 case 203 /* CallExpression */:
41290                     bind(node.questionDotToken);
41291                     bindEach(node.typeArguments);
41292                     bindEach(node.arguments);
41293                     break;
41294             }
41295         }
41296         function bindOptionalChain(node, trueTarget, falseTarget) {
41297             // For an optional chain, we emulate the behavior of a logical expression:
41298             //
41299             // a?.b         -> a && a.b
41300             // a?.b.c       -> a && a.b.c
41301             // a?.b?.c      -> a && a.b && a.b.c
41302             // a?.[x = 1]   -> a && a[x = 1]
41303             //
41304             // To do this we descend through the chain until we reach the root of a chain (the expression with a `?.`)
41305             // and build it's CFA graph as if it were the first condition (`a && ...`). Then we bind the rest
41306             // of the node as part of the "true" branch, and continue to do so as we ascend back up to the outermost
41307             // chain node. We then treat the entire node as the right side of the expression.
41308             var preChainLabel = ts.isOptionalChainRoot(node) ? createBranchLabel() : undefined;
41309             bindOptionalExpression(node.expression, preChainLabel || trueTarget, falseTarget);
41310             if (preChainLabel) {
41311                 currentFlow = finishFlowLabel(preChainLabel);
41312             }
41313             doWithConditionalBranches(bindOptionalChainRest, node, trueTarget, falseTarget);
41314             if (ts.isOutermostOptionalChain(node)) {
41315                 addAntecedent(trueTarget, createFlowCondition(32 /* TrueCondition */, currentFlow, node));
41316                 addAntecedent(falseTarget, createFlowCondition(64 /* FalseCondition */, currentFlow, node));
41317             }
41318         }
41319         function bindOptionalChainFlow(node) {
41320             if (isTopLevelLogicalExpression(node)) {
41321                 var postExpressionLabel = createBranchLabel();
41322                 bindOptionalChain(node, postExpressionLabel, postExpressionLabel);
41323                 currentFlow = finishFlowLabel(postExpressionLabel);
41324             }
41325             else {
41326                 bindOptionalChain(node, currentTrueTarget, currentFalseTarget);
41327             }
41328         }
41329         function bindNonNullExpressionFlow(node) {
41330             if (ts.isOptionalChain(node)) {
41331                 bindOptionalChainFlow(node);
41332             }
41333             else {
41334                 bindEachChild(node);
41335             }
41336         }
41337         function bindAccessExpressionFlow(node) {
41338             if (ts.isOptionalChain(node)) {
41339                 bindOptionalChainFlow(node);
41340             }
41341             else {
41342                 bindEachChild(node);
41343             }
41344         }
41345         function bindCallExpressionFlow(node) {
41346             if (ts.isOptionalChain(node)) {
41347                 bindOptionalChainFlow(node);
41348             }
41349             else {
41350                 // If the target of the call expression is a function expression or arrow function we have
41351                 // an immediately invoked function expression (IIFE). Initialize the flowNode property to
41352                 // the current control flow (which includes evaluation of the IIFE arguments).
41353                 var expr = ts.skipParentheses(node.expression);
41354                 if (expr.kind === 208 /* FunctionExpression */ || expr.kind === 209 /* ArrowFunction */) {
41355                     bindEach(node.typeArguments);
41356                     bindEach(node.arguments);
41357                     bind(node.expression);
41358                 }
41359                 else {
41360                     bindEachChild(node);
41361                     if (node.expression.kind === 105 /* SuperKeyword */) {
41362                         currentFlow = createFlowCall(currentFlow, node);
41363                     }
41364                 }
41365             }
41366             if (node.expression.kind === 201 /* PropertyAccessExpression */) {
41367                 var propertyAccess = node.expression;
41368                 if (ts.isIdentifier(propertyAccess.name) && isNarrowableOperand(propertyAccess.expression) && ts.isPushOrUnshiftIdentifier(propertyAccess.name)) {
41369                     currentFlow = createFlowMutation(256 /* ArrayMutation */, currentFlow, node);
41370                 }
41371             }
41372         }
41373         function getContainerFlags(node) {
41374             switch (node.kind) {
41375                 case 221 /* ClassExpression */:
41376                 case 252 /* ClassDeclaration */:
41377                 case 255 /* EnumDeclaration */:
41378                 case 200 /* ObjectLiteralExpression */:
41379                 case 177 /* TypeLiteral */:
41380                 case 312 /* JSDocTypeLiteral */:
41381                 case 281 /* JsxAttributes */:
41382                     return 1 /* IsContainer */;
41383                 case 253 /* InterfaceDeclaration */:
41384                     return 1 /* IsContainer */ | 64 /* IsInterface */;
41385                 case 256 /* ModuleDeclaration */:
41386                 case 254 /* TypeAliasDeclaration */:
41387                 case 190 /* MappedType */:
41388                     return 1 /* IsContainer */ | 32 /* HasLocals */;
41389                 case 297 /* SourceFile */:
41390                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */;
41391                 case 165 /* MethodDeclaration */:
41392                     if (ts.isObjectLiteralOrClassExpressionMethod(node)) {
41393                         return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 128 /* IsObjectLiteralOrClassExpressionMethod */;
41394                     }
41395                 // falls through
41396                 case 166 /* Constructor */:
41397                 case 251 /* FunctionDeclaration */:
41398                 case 164 /* MethodSignature */:
41399                 case 167 /* GetAccessor */:
41400                 case 168 /* SetAccessor */:
41401                 case 169 /* CallSignature */:
41402                 case 313 /* JSDocSignature */:
41403                 case 308 /* JSDocFunctionType */:
41404                 case 174 /* FunctionType */:
41405                 case 170 /* ConstructSignature */:
41406                 case 171 /* IndexSignature */:
41407                 case 175 /* ConstructorType */:
41408                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */;
41409                 case 208 /* FunctionExpression */:
41410                 case 209 /* ArrowFunction */:
41411                     return 1 /* IsContainer */ | 4 /* IsControlFlowContainer */ | 32 /* HasLocals */ | 8 /* IsFunctionLike */ | 16 /* IsFunctionExpression */;
41412                 case 257 /* ModuleBlock */:
41413                     return 4 /* IsControlFlowContainer */;
41414                 case 163 /* PropertyDeclaration */:
41415                     return node.initializer ? 4 /* IsControlFlowContainer */ : 0;
41416                 case 287 /* CatchClause */:
41417                 case 237 /* ForStatement */:
41418                 case 238 /* ForInStatement */:
41419                 case 239 /* ForOfStatement */:
41420                 case 258 /* CaseBlock */:
41421                     return 2 /* IsBlockScopedContainer */;
41422                 case 230 /* Block */:
41423                     // do not treat blocks directly inside a function as a block-scoped-container.
41424                     // Locals that reside in this block should go to the function locals. Otherwise 'x'
41425                     // would not appear to be a redeclaration of a block scoped local in the following
41426                     // example:
41427                     //
41428                     //      function foo() {
41429                     //          var x;
41430                     //          let x;
41431                     //      }
41432                     //
41433                     // If we placed 'var x' into the function locals and 'let x' into the locals of
41434                     // the block, then there would be no collision.
41435                     //
41436                     // By not creating a new block-scoped-container here, we ensure that both 'var x'
41437                     // and 'let x' go into the Function-container's locals, and we do get a collision
41438                     // conflict.
41439                     return ts.isFunctionLike(node.parent) ? 0 /* None */ : 2 /* IsBlockScopedContainer */;
41440             }
41441             return 0 /* None */;
41442         }
41443         function addToContainerChain(next) {
41444             if (lastContainer) {
41445                 lastContainer.nextContainer = next;
41446             }
41447             lastContainer = next;
41448         }
41449         function declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes) {
41450             switch (container.kind) {
41451                 // Modules, source files, and classes need specialized handling for how their
41452                 // members are declared (for example, a member of a class will go into a specific
41453                 // symbol table depending on if it is static or not). We defer to specialized
41454                 // handlers to take care of declaring these child members.
41455                 case 256 /* ModuleDeclaration */:
41456                     return declareModuleMember(node, symbolFlags, symbolExcludes);
41457                 case 297 /* SourceFile */:
41458                     return declareSourceFileMember(node, symbolFlags, symbolExcludes);
41459                 case 221 /* ClassExpression */:
41460                 case 252 /* ClassDeclaration */:
41461                     return declareClassMember(node, symbolFlags, symbolExcludes);
41462                 case 255 /* EnumDeclaration */:
41463                     return declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes);
41464                 case 177 /* TypeLiteral */:
41465                 case 312 /* JSDocTypeLiteral */:
41466                 case 200 /* ObjectLiteralExpression */:
41467                 case 253 /* InterfaceDeclaration */:
41468                 case 281 /* JsxAttributes */:
41469                     // Interface/Object-types always have their children added to the 'members' of
41470                     // their container. They are only accessible through an instance of their
41471                     // container, and are never in scope otherwise (even inside the body of the
41472                     // object / type / interface declaring them). An exception is type parameters,
41473                     // which are in scope without qualification (similar to 'locals').
41474                     return declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
41475                 case 174 /* FunctionType */:
41476                 case 175 /* ConstructorType */:
41477                 case 169 /* CallSignature */:
41478                 case 170 /* ConstructSignature */:
41479                 case 313 /* JSDocSignature */:
41480                 case 171 /* IndexSignature */:
41481                 case 165 /* MethodDeclaration */:
41482                 case 164 /* MethodSignature */:
41483                 case 166 /* Constructor */:
41484                 case 167 /* GetAccessor */:
41485                 case 168 /* SetAccessor */:
41486                 case 251 /* FunctionDeclaration */:
41487                 case 208 /* FunctionExpression */:
41488                 case 209 /* ArrowFunction */:
41489                 case 308 /* JSDocFunctionType */:
41490                 case 331 /* JSDocTypedefTag */:
41491                 case 324 /* JSDocCallbackTag */:
41492                 case 254 /* TypeAliasDeclaration */:
41493                 case 190 /* MappedType */:
41494                     // All the children of these container types are never visible through another
41495                     // symbol (i.e. through another symbol's 'exports' or 'members').  Instead,
41496                     // they're only accessed 'lexically' (i.e. from code that exists underneath
41497                     // their container in the tree). To accomplish this, we simply add their declared
41498                     // symbol to the 'locals' of the container.  These symbols can then be found as
41499                     // the type checker walks up the containers, checking them for matching names.
41500                     return declareSymbol(container.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
41501             }
41502         }
41503         function declareClassMember(node, symbolFlags, symbolExcludes) {
41504             return ts.hasSyntacticModifier(node, 32 /* Static */)
41505                 ? declareSymbol(container.symbol.exports, container.symbol, node, symbolFlags, symbolExcludes)
41506                 : declareSymbol(container.symbol.members, container.symbol, node, symbolFlags, symbolExcludes);
41507         }
41508         function declareSourceFileMember(node, symbolFlags, symbolExcludes) {
41509             return ts.isExternalModule(file)
41510                 ? declareModuleMember(node, symbolFlags, symbolExcludes)
41511                 : declareSymbol(file.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
41512         }
41513         function hasExportDeclarations(node) {
41514             var body = ts.isSourceFile(node) ? node : ts.tryCast(node.body, ts.isModuleBlock);
41515             return !!body && body.statements.some(function (s) { return ts.isExportDeclaration(s) || ts.isExportAssignment(s); });
41516         }
41517         function setExportContextFlag(node) {
41518             // A declaration source file or ambient module declaration that contains no export declarations (but possibly regular
41519             // declarations with export modifiers) is an export context in which declarations are implicitly exported.
41520             if (node.flags & 8388608 /* Ambient */ && !hasExportDeclarations(node)) {
41521                 node.flags |= 64 /* ExportContext */;
41522             }
41523             else {
41524                 node.flags &= ~64 /* ExportContext */;
41525             }
41526         }
41527         function bindModuleDeclaration(node) {
41528             setExportContextFlag(node);
41529             if (ts.isAmbientModule(node)) {
41530                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
41531                     errorOnFirstToken(node, ts.Diagnostics.export_modifier_cannot_be_applied_to_ambient_modules_and_module_augmentations_since_they_are_always_visible);
41532                 }
41533                 if (ts.isModuleAugmentationExternal(node)) {
41534                     declareModuleSymbol(node);
41535                 }
41536                 else {
41537                     var pattern = void 0;
41538                     if (node.name.kind === 10 /* StringLiteral */) {
41539                         var text = node.name.text;
41540                         if (ts.hasZeroOrOneAsteriskCharacter(text)) {
41541                             pattern = ts.tryParsePattern(text);
41542                         }
41543                         else {
41544                             errorOnFirstToken(node.name, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, text);
41545                         }
41546                     }
41547                     var symbol = declareSymbolAndAddToSymbolTable(node, 512 /* ValueModule */, 110735 /* ValueModuleExcludes */);
41548                     file.patternAmbientModules = ts.append(file.patternAmbientModules, pattern && { pattern: pattern, symbol: symbol });
41549                 }
41550             }
41551             else {
41552                 var state = declareModuleSymbol(node);
41553                 if (state !== 0 /* NonInstantiated */) {
41554                     var symbol = node.symbol;
41555                     // if module was already merged with some function, class or non-const enum, treat it as non-const-enum-only
41556                     symbol.constEnumOnlyModule = (!(symbol.flags & (16 /* Function */ | 32 /* Class */ | 256 /* RegularEnum */)))
41557                         // Current must be `const enum` only
41558                         && state === 2 /* ConstEnumOnly */
41559                         // Can't have been set to 'false' in a previous merged symbol. ('undefined' OK)
41560                         && symbol.constEnumOnlyModule !== false;
41561                 }
41562             }
41563         }
41564         function declareModuleSymbol(node) {
41565             var state = getModuleInstanceState(node);
41566             var instantiated = state !== 0 /* NonInstantiated */;
41567             declareSymbolAndAddToSymbolTable(node, instantiated ? 512 /* ValueModule */ : 1024 /* NamespaceModule */, instantiated ? 110735 /* ValueModuleExcludes */ : 0 /* NamespaceModuleExcludes */);
41568             return state;
41569         }
41570         function bindFunctionOrConstructorType(node) {
41571             // For a given function symbol "<...>(...) => T" we want to generate a symbol identical
41572             // to the one we would get for: { <...>(...): T }
41573             //
41574             // We do that by making an anonymous type literal symbol, and then setting the function
41575             // symbol as its sole member. To the rest of the system, this symbol will be indistinguishable
41576             // from an actual type literal symbol you would have gotten had you used the long form.
41577             var symbol = createSymbol(131072 /* Signature */, getDeclarationName(node)); // TODO: GH#18217
41578             addDeclarationToSymbol(symbol, node, 131072 /* Signature */);
41579             var typeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
41580             addDeclarationToSymbol(typeLiteralSymbol, node, 2048 /* TypeLiteral */);
41581             typeLiteralSymbol.members = ts.createSymbolTable();
41582             typeLiteralSymbol.members.set(symbol.escapedName, symbol);
41583         }
41584         function bindObjectLiteralExpression(node) {
41585             var ElementKind;
41586             (function (ElementKind) {
41587                 ElementKind[ElementKind["Property"] = 1] = "Property";
41588                 ElementKind[ElementKind["Accessor"] = 2] = "Accessor";
41589             })(ElementKind || (ElementKind = {}));
41590             if (inStrictMode && !ts.isAssignmentTarget(node)) {
41591                 var seen = new ts.Map();
41592                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
41593                     var prop = _a[_i];
41594                     if (prop.kind === 290 /* SpreadAssignment */ || prop.name.kind !== 78 /* Identifier */) {
41595                         continue;
41596                     }
41597                     var identifier = prop.name;
41598                     // ECMA-262 11.1.5 Object Initializer
41599                     // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
41600                     // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
41601                     // IsDataDescriptor(propId.descriptor) is true.
41602                     //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
41603                     //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
41604                     //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
41605                     // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
41606                     var currentKind = prop.kind === 288 /* PropertyAssignment */ || prop.kind === 289 /* ShorthandPropertyAssignment */ || prop.kind === 165 /* MethodDeclaration */
41607                         ? 1 /* Property */
41608                         : 2 /* Accessor */;
41609                     var existingKind = seen.get(identifier.escapedText);
41610                     if (!existingKind) {
41611                         seen.set(identifier.escapedText, currentKind);
41612                         continue;
41613                     }
41614                     if (currentKind === 1 /* Property */ && existingKind === 1 /* Property */) {
41615                         var span = ts.getErrorSpanForNode(file, identifier);
41616                         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));
41617                     }
41618                 }
41619             }
41620             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__object" /* Object */);
41621         }
41622         function bindJsxAttributes(node) {
41623             return bindAnonymousDeclaration(node, 4096 /* ObjectLiteral */, "__jsxAttributes" /* JSXAttributes */);
41624         }
41625         function bindJsxAttribute(node, symbolFlags, symbolExcludes) {
41626             return declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
41627         }
41628         function bindAnonymousDeclaration(node, symbolFlags, name) {
41629             var symbol = createSymbol(symbolFlags, name);
41630             if (symbolFlags & (8 /* EnumMember */ | 106500 /* ClassMember */)) {
41631                 symbol.parent = container.symbol;
41632             }
41633             addDeclarationToSymbol(symbol, node, symbolFlags);
41634             return symbol;
41635         }
41636         function bindBlockScopedDeclaration(node, symbolFlags, symbolExcludes) {
41637             switch (blockScopeContainer.kind) {
41638                 case 256 /* ModuleDeclaration */:
41639                     declareModuleMember(node, symbolFlags, symbolExcludes);
41640                     break;
41641                 case 297 /* SourceFile */:
41642                     if (ts.isExternalOrCommonJsModule(container)) {
41643                         declareModuleMember(node, symbolFlags, symbolExcludes);
41644                         break;
41645                     }
41646                 // falls through
41647                 default:
41648                     if (!blockScopeContainer.locals) {
41649                         blockScopeContainer.locals = ts.createSymbolTable();
41650                         addToContainerChain(blockScopeContainer);
41651                     }
41652                     declareSymbol(blockScopeContainer.locals, /*parent*/ undefined, node, symbolFlags, symbolExcludes);
41653             }
41654         }
41655         function delayedBindJSDocTypedefTag() {
41656             if (!delayedTypeAliases) {
41657                 return;
41658             }
41659             var saveContainer = container;
41660             var saveLastContainer = lastContainer;
41661             var saveBlockScopeContainer = blockScopeContainer;
41662             var saveParent = parent;
41663             var saveCurrentFlow = currentFlow;
41664             for (var _i = 0, delayedTypeAliases_1 = delayedTypeAliases; _i < delayedTypeAliases_1.length; _i++) {
41665                 var typeAlias = delayedTypeAliases_1[_i];
41666                 var host = ts.getJSDocHost(typeAlias);
41667                 container = ts.findAncestor(host.parent, function (n) { return !!(getContainerFlags(n) & 1 /* IsContainer */); }) || file;
41668                 blockScopeContainer = ts.getEnclosingBlockScopeContainer(host) || file;
41669                 currentFlow = initFlowNode({ flags: 2 /* Start */ });
41670                 parent = typeAlias;
41671                 bind(typeAlias.typeExpression);
41672                 var declName = ts.getNameOfDeclaration(typeAlias);
41673                 if ((ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName) && declName && ts.isPropertyAccessEntityNameExpression(declName.parent)) {
41674                     // typedef anchored to an A.B.C assignment - we need to bind into B's namespace under name C
41675                     var isTopLevel = isTopLevelNamespaceAssignment(declName.parent);
41676                     if (isTopLevel) {
41677                         bindPotentiallyMissingNamespaces(file.symbol, declName.parent, isTopLevel, !!ts.findAncestor(declName, function (d) { return ts.isPropertyAccessExpression(d) && d.name.escapedText === "prototype"; }), /*containerIsClass*/ false);
41678                         var oldContainer = container;
41679                         switch (ts.getAssignmentDeclarationPropertyAccessKind(declName.parent)) {
41680                             case 1 /* ExportsProperty */:
41681                             case 2 /* ModuleExports */:
41682                                 if (!ts.isExternalOrCommonJsModule(file)) {
41683                                     container = undefined;
41684                                 }
41685                                 else {
41686                                     container = file;
41687                                 }
41688                                 break;
41689                             case 4 /* ThisProperty */:
41690                                 container = declName.parent.expression;
41691                                 break;
41692                             case 3 /* PrototypeProperty */:
41693                                 container = declName.parent.expression.name;
41694                                 break;
41695                             case 5 /* Property */:
41696                                 container = isExportsOrModuleExportsOrAlias(file, declName.parent.expression) ? file
41697                                     : ts.isPropertyAccessExpression(declName.parent.expression) ? declName.parent.expression.name
41698                                         : declName.parent.expression;
41699                                 break;
41700                             case 0 /* None */:
41701                                 return ts.Debug.fail("Shouldn't have detected typedef or enum on non-assignment declaration");
41702                         }
41703                         if (container) {
41704                             declareModuleMember(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
41705                         }
41706                         container = oldContainer;
41707                     }
41708                 }
41709                 else if (ts.isJSDocEnumTag(typeAlias) || !typeAlias.fullName || typeAlias.fullName.kind === 78 /* Identifier */) {
41710                     parent = typeAlias.parent;
41711                     bindBlockScopedDeclaration(typeAlias, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
41712                 }
41713                 else {
41714                     bind(typeAlias.fullName);
41715                 }
41716             }
41717             container = saveContainer;
41718             lastContainer = saveLastContainer;
41719             blockScopeContainer = saveBlockScopeContainer;
41720             parent = saveParent;
41721             currentFlow = saveCurrentFlow;
41722         }
41723         // The binder visits every node in the syntax tree so it is a convenient place to perform a single localized
41724         // check for reserved words used as identifiers in strict mode code, as well as `yield` or `await` in
41725         // [Yield] or [Await] contexts, respectively.
41726         function checkContextualIdentifier(node) {
41727             // Report error only if there are no parse errors in file
41728             if (!file.parseDiagnostics.length &&
41729                 !(node.flags & 8388608 /* Ambient */) &&
41730                 !(node.flags & 4194304 /* JSDoc */) &&
41731                 !ts.isIdentifierName(node)) {
41732                 // strict mode identifiers
41733                 if (inStrictMode &&
41734                     node.originalKeywordKind >= 116 /* FirstFutureReservedWord */ &&
41735                     node.originalKeywordKind <= 124 /* LastFutureReservedWord */) {
41736                     file.bindDiagnostics.push(createDiagnosticForNode(node, getStrictModeIdentifierMessage(node), ts.declarationNameToString(node)));
41737                 }
41738                 else if (node.originalKeywordKind === 130 /* AwaitKeyword */) {
41739                     if (ts.isExternalModule(file) && ts.isInTopLevelContext(node)) {
41740                         file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_at_the_top_level_of_a_module, ts.declarationNameToString(node)));
41741                     }
41742                     else if (node.flags & 32768 /* AwaitContext */) {
41743                         file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
41744                     }
41745                 }
41746                 else if (node.originalKeywordKind === 124 /* YieldKeyword */ && node.flags & 8192 /* YieldContext */) {
41747                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_that_cannot_be_used_here, ts.declarationNameToString(node)));
41748                 }
41749             }
41750         }
41751         function getStrictModeIdentifierMessage(node) {
41752             // Provide specialized messages to help the user understand why we think they're in
41753             // strict mode.
41754             if (ts.getContainingClass(node)) {
41755                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Class_definitions_are_automatically_in_strict_mode;
41756             }
41757             if (file.externalModuleIndicator) {
41758                 return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode_Modules_are_automatically_in_strict_mode;
41759             }
41760             return ts.Diagnostics.Identifier_expected_0_is_a_reserved_word_in_strict_mode;
41761         }
41762         // The binder visits every node, so this is a good place to check for
41763         // the reserved private name (there is only one)
41764         function checkPrivateIdentifier(node) {
41765             if (node.escapedText === "#constructor") {
41766                 // Report error only if there are no parse errors in file
41767                 if (!file.parseDiagnostics.length) {
41768                     file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.constructor_is_a_reserved_word, ts.declarationNameToString(node)));
41769                 }
41770             }
41771         }
41772         function checkStrictModeBinaryExpression(node) {
41773             if (inStrictMode && ts.isLeftHandSideExpression(node.left) && ts.isAssignmentOperator(node.operatorToken.kind)) {
41774                 // ECMA 262 (Annex C) The identifier eval or arguments may not appear as the LeftHandSideExpression of an
41775                 // Assignment operator(11.13) or of a PostfixExpression(11.3)
41776                 checkStrictModeEvalOrArguments(node, node.left);
41777             }
41778         }
41779         function checkStrictModeCatchClause(node) {
41780             // It is a SyntaxError if a TryStatement with a Catch occurs within strict code and the Identifier of the
41781             // Catch production is eval or arguments
41782             if (inStrictMode && node.variableDeclaration) {
41783                 checkStrictModeEvalOrArguments(node, node.variableDeclaration.name);
41784             }
41785         }
41786         function checkStrictModeDeleteExpression(node) {
41787             // Grammar checking
41788             if (inStrictMode && node.expression.kind === 78 /* Identifier */) {
41789                 // When a delete operator occurs within strict mode code, a SyntaxError is thrown if its
41790                 // UnaryExpression is a direct reference to a variable, function argument, or function name
41791                 var span = ts.getErrorSpanForNode(file, node.expression);
41792                 file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, ts.Diagnostics.delete_cannot_be_called_on_an_identifier_in_strict_mode));
41793             }
41794         }
41795         function isEvalOrArgumentsIdentifier(node) {
41796             return ts.isIdentifier(node) && (node.escapedText === "eval" || node.escapedText === "arguments");
41797         }
41798         function checkStrictModeEvalOrArguments(contextNode, name) {
41799             if (name && name.kind === 78 /* Identifier */) {
41800                 var identifier = name;
41801                 if (isEvalOrArgumentsIdentifier(identifier)) {
41802                     // We check first if the name is inside class declaration or class expression; if so give explicit message
41803                     // otherwise report generic error message.
41804                     var span = ts.getErrorSpanForNode(file, name);
41805                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, getStrictModeEvalOrArgumentsMessage(contextNode), ts.idText(identifier)));
41806                 }
41807             }
41808         }
41809         function getStrictModeEvalOrArgumentsMessage(node) {
41810             // Provide specialized messages to help the user understand why we think they're in
41811             // strict mode.
41812             if (ts.getContainingClass(node)) {
41813                 return ts.Diagnostics.Invalid_use_of_0_Class_definitions_are_automatically_in_strict_mode;
41814             }
41815             if (file.externalModuleIndicator) {
41816                 return ts.Diagnostics.Invalid_use_of_0_Modules_are_automatically_in_strict_mode;
41817             }
41818             return ts.Diagnostics.Invalid_use_of_0_in_strict_mode;
41819         }
41820         function checkStrictModeFunctionName(node) {
41821             if (inStrictMode) {
41822                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a strict mode FunctionDeclaration or FunctionExpression (13.1))
41823                 checkStrictModeEvalOrArguments(node, node.name);
41824             }
41825         }
41826         function getStrictModeBlockScopeFunctionDeclarationMessage(node) {
41827             // Provide specialized messages to help the user understand why we think they're in
41828             // strict mode.
41829             if (ts.getContainingClass(node)) {
41830                 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;
41831             }
41832             if (file.externalModuleIndicator) {
41833                 return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5_Modules_are_automatically_in_strict_mode;
41834             }
41835             return ts.Diagnostics.Function_declarations_are_not_allowed_inside_blocks_in_strict_mode_when_targeting_ES3_or_ES5;
41836         }
41837         function checkStrictModeFunctionDeclaration(node) {
41838             if (languageVersion < 2 /* ES2015 */) {
41839                 // Report error if function is not top level function declaration
41840                 if (blockScopeContainer.kind !== 297 /* SourceFile */ &&
41841                     blockScopeContainer.kind !== 256 /* ModuleDeclaration */ &&
41842                     !ts.isFunctionLike(blockScopeContainer)) {
41843                     // We check first if the name is inside class declaration or class expression; if so give explicit message
41844                     // otherwise report generic error message.
41845                     var errorSpan = ts.getErrorSpanForNode(file, node);
41846                     file.bindDiagnostics.push(ts.createFileDiagnostic(file, errorSpan.start, errorSpan.length, getStrictModeBlockScopeFunctionDeclarationMessage(node)));
41847                 }
41848             }
41849         }
41850         function checkStrictModeNumericLiteral(node) {
41851             if (inStrictMode && node.numericLiteralFlags & 32 /* Octal */) {
41852                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Octal_literals_are_not_allowed_in_strict_mode));
41853             }
41854         }
41855         function checkStrictModePostfixUnaryExpression(node) {
41856             // Grammar checking
41857             // The identifier eval or arguments may not appear as the LeftHandSideExpression of an
41858             // Assignment operator(11.13) or of a PostfixExpression(11.3) or as the UnaryExpression
41859             // operated upon by a Prefix Increment(11.4.4) or a Prefix Decrement(11.4.5) operator.
41860             if (inStrictMode) {
41861                 checkStrictModeEvalOrArguments(node, node.operand);
41862             }
41863         }
41864         function checkStrictModePrefixUnaryExpression(node) {
41865             // Grammar checking
41866             if (inStrictMode) {
41867                 if (node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */) {
41868                     checkStrictModeEvalOrArguments(node, node.operand);
41869                 }
41870             }
41871         }
41872         function checkStrictModeWithStatement(node) {
41873             // Grammar checking for withStatement
41874             if (inStrictMode) {
41875                 errorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_strict_mode);
41876             }
41877         }
41878         function checkStrictModeLabeledStatement(node) {
41879             // Grammar checking for labeledStatement
41880             if (inStrictMode && options.target >= 2 /* ES2015 */) {
41881                 if (ts.isDeclarationStatement(node.statement) || ts.isVariableStatement(node.statement)) {
41882                     errorOnFirstToken(node.label, ts.Diagnostics.A_label_is_not_allowed_here);
41883                 }
41884             }
41885         }
41886         function errorOnFirstToken(node, message, arg0, arg1, arg2) {
41887             var span = ts.getSpanOfTokenAtPosition(file, node.pos);
41888             file.bindDiagnostics.push(ts.createFileDiagnostic(file, span.start, span.length, message, arg0, arg1, arg2));
41889         }
41890         function errorOrSuggestionOnNode(isError, node, message) {
41891             errorOrSuggestionOnRange(isError, node, node, message);
41892         }
41893         function errorOrSuggestionOnRange(isError, startNode, endNode, message) {
41894             addErrorOrSuggestionDiagnostic(isError, { pos: ts.getTokenPosOfNode(startNode, file), end: endNode.end }, message);
41895         }
41896         function addErrorOrSuggestionDiagnostic(isError, range, message) {
41897             var diag = ts.createFileDiagnostic(file, range.pos, range.end - range.pos, message);
41898             if (isError) {
41899                 file.bindDiagnostics.push(diag);
41900             }
41901             else {
41902                 file.bindSuggestionDiagnostics = ts.append(file.bindSuggestionDiagnostics, __assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
41903             }
41904         }
41905         function bind(node) {
41906             if (!node) {
41907                 return;
41908             }
41909             ts.setParent(node, parent);
41910             var saveInStrictMode = inStrictMode;
41911             // Even though in the AST the jsdoc @typedef node belongs to the current node,
41912             // its symbol might be in the same scope with the current node's symbol. Consider:
41913             //
41914             //     /** @typedef {string | number} MyType */
41915             //     function foo();
41916             //
41917             // Here the current node is "foo", which is a container, but the scope of "MyType" should
41918             // not be inside "foo". Therefore we always bind @typedef before bind the parent node,
41919             // and skip binding this tag later when binding all the other jsdoc tags.
41920             // First we bind declaration nodes to a symbol if possible. We'll both create a symbol
41921             // and then potentially add the symbol to an appropriate symbol table. Possible
41922             // destination symbol tables are:
41923             //
41924             //  1) The 'exports' table of the current container's symbol.
41925             //  2) The 'members' table of the current container's symbol.
41926             //  3) The 'locals' table of the current container.
41927             //
41928             // However, not all symbols will end up in any of these tables. 'Anonymous' symbols
41929             // (like TypeLiterals for example) will not be put in any table.
41930             bindWorker(node);
41931             // Then we recurse into the children of the node to bind them as well. For certain
41932             // symbols we do specialized work when we recurse. For example, we'll keep track of
41933             // the current 'container' node when it changes. This helps us know which symbol table
41934             // a local should go into for example. Since terminal nodes are known not to have
41935             // children, as an optimization we don't process those.
41936             if (node.kind > 156 /* LastToken */) {
41937                 var saveParent = parent;
41938                 parent = node;
41939                 var containerFlags = getContainerFlags(node);
41940                 if (containerFlags === 0 /* None */) {
41941                     bindChildren(node);
41942                 }
41943                 else {
41944                     bindContainer(node, containerFlags);
41945                 }
41946                 parent = saveParent;
41947             }
41948             else {
41949                 var saveParent = parent;
41950                 if (node.kind === 1 /* EndOfFileToken */)
41951                     parent = node;
41952                 bindJSDoc(node);
41953                 parent = saveParent;
41954             }
41955             inStrictMode = saveInStrictMode;
41956         }
41957         function bindJSDoc(node) {
41958             if (ts.hasJSDocNodes(node)) {
41959                 if (ts.isInJSFile(node)) {
41960                     for (var _i = 0, _a = node.jsDoc; _i < _a.length; _i++) {
41961                         var j = _a[_i];
41962                         bind(j);
41963                     }
41964                 }
41965                 else {
41966                     for (var _b = 0, _c = node.jsDoc; _b < _c.length; _b++) {
41967                         var j = _c[_b];
41968                         ts.setParent(j, node);
41969                         ts.setParentRecursive(j, /*incremental*/ false);
41970                     }
41971                 }
41972             }
41973         }
41974         function updateStrictModeStatementList(statements) {
41975             if (!inStrictMode) {
41976                 for (var _i = 0, statements_3 = statements; _i < statements_3.length; _i++) {
41977                     var statement = statements_3[_i];
41978                     if (!ts.isPrologueDirective(statement)) {
41979                         return;
41980                     }
41981                     if (isUseStrictPrologueDirective(statement)) {
41982                         inStrictMode = true;
41983                         return;
41984                     }
41985                 }
41986             }
41987         }
41988         /// Should be called only on prologue directives (isPrologueDirective(node) should be true)
41989         function isUseStrictPrologueDirective(node) {
41990             var nodeText = ts.getSourceTextOfNodeFromSourceFile(file, node.expression);
41991             // Note: the node text must be exactly "use strict" or 'use strict'.  It is not ok for the
41992             // string to contain unicode escapes (as per ES5).
41993             return nodeText === '"use strict"' || nodeText === "'use strict'";
41994         }
41995         function bindWorker(node) {
41996             switch (node.kind) {
41997                 /* Strict mode checks */
41998                 case 78 /* Identifier */:
41999                     // for typedef type names with namespaces, bind the new jsdoc type symbol here
42000                     // because it requires all containing namespaces to be in effect, namely the
42001                     // current "blockScopeContainer" needs to be set to its immediate namespace parent.
42002                     if (node.isInJSDocNamespace) {
42003                         var parentNode = node.parent;
42004                         while (parentNode && !ts.isJSDocTypeAlias(parentNode)) {
42005                             parentNode = parentNode.parent;
42006                         }
42007                         bindBlockScopedDeclaration(parentNode, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
42008                         break;
42009                     }
42010                 // falls through
42011                 case 107 /* ThisKeyword */:
42012                     if (currentFlow && (ts.isExpression(node) || parent.kind === 289 /* ShorthandPropertyAssignment */)) {
42013                         node.flowNode = currentFlow;
42014                     }
42015                     return checkContextualIdentifier(node);
42016                 case 105 /* SuperKeyword */:
42017                     node.flowNode = currentFlow;
42018                     break;
42019                 case 79 /* PrivateIdentifier */:
42020                     return checkPrivateIdentifier(node);
42021                 case 201 /* PropertyAccessExpression */:
42022                 case 202 /* ElementAccessExpression */:
42023                     var expr = node;
42024                     if (currentFlow && isNarrowableReference(expr)) {
42025                         expr.flowNode = currentFlow;
42026                     }
42027                     if (ts.isSpecialPropertyDeclaration(expr)) {
42028                         bindSpecialPropertyDeclaration(expr);
42029                     }
42030                     if (ts.isInJSFile(expr) &&
42031                         file.commonJsModuleIndicator &&
42032                         ts.isModuleExportsAccessExpression(expr) &&
42033                         !lookupSymbolForName(blockScopeContainer, "module")) {
42034                         declareSymbol(file.locals, /*parent*/ undefined, expr.expression, 1 /* FunctionScopedVariable */ | 134217728 /* ModuleExports */, 111550 /* FunctionScopedVariableExcludes */);
42035                     }
42036                     break;
42037                 case 216 /* BinaryExpression */:
42038                     var specialKind = ts.getAssignmentDeclarationKind(node);
42039                     switch (specialKind) {
42040                         case 1 /* ExportsProperty */:
42041                             bindExportsPropertyAssignment(node);
42042                             break;
42043                         case 2 /* ModuleExports */:
42044                             bindModuleExportsAssignment(node);
42045                             break;
42046                         case 3 /* PrototypeProperty */:
42047                             bindPrototypePropertyAssignment(node.left, node);
42048                             break;
42049                         case 6 /* Prototype */:
42050                             bindPrototypeAssignment(node);
42051                             break;
42052                         case 4 /* ThisProperty */:
42053                             bindThisPropertyAssignment(node);
42054                             break;
42055                         case 5 /* Property */:
42056                             var expression = node.left.expression;
42057                             if (ts.isInJSFile(node) && ts.isIdentifier(expression)) {
42058                                 var symbol = lookupSymbolForName(blockScopeContainer, expression.escapedText);
42059                                 if (ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration)) {
42060                                     bindThisPropertyAssignment(node);
42061                                     break;
42062                                 }
42063                             }
42064                             bindSpecialPropertyAssignment(node);
42065                             break;
42066                         case 0 /* None */:
42067                             // Nothing to do
42068                             break;
42069                         default:
42070                             ts.Debug.fail("Unknown binary expression special property assignment kind");
42071                     }
42072                     return checkStrictModeBinaryExpression(node);
42073                 case 287 /* CatchClause */:
42074                     return checkStrictModeCatchClause(node);
42075                 case 210 /* DeleteExpression */:
42076                     return checkStrictModeDeleteExpression(node);
42077                 case 8 /* NumericLiteral */:
42078                     return checkStrictModeNumericLiteral(node);
42079                 case 215 /* PostfixUnaryExpression */:
42080                     return checkStrictModePostfixUnaryExpression(node);
42081                 case 214 /* PrefixUnaryExpression */:
42082                     return checkStrictModePrefixUnaryExpression(node);
42083                 case 243 /* WithStatement */:
42084                     return checkStrictModeWithStatement(node);
42085                 case 245 /* LabeledStatement */:
42086                     return checkStrictModeLabeledStatement(node);
42087                 case 187 /* ThisType */:
42088                     seenThisKeyword = true;
42089                     return;
42090                 case 172 /* TypePredicate */:
42091                     break; // Binding the children will handle everything
42092                 case 159 /* TypeParameter */:
42093                     return bindTypeParameter(node);
42094                 case 160 /* Parameter */:
42095                     return bindParameter(node);
42096                 case 249 /* VariableDeclaration */:
42097                     return bindVariableDeclarationOrBindingElement(node);
42098                 case 198 /* BindingElement */:
42099                     node.flowNode = currentFlow;
42100                     return bindVariableDeclarationOrBindingElement(node);
42101                 case 163 /* PropertyDeclaration */:
42102                 case 162 /* PropertySignature */:
42103                     return bindPropertyWorker(node);
42104                 case 288 /* PropertyAssignment */:
42105                 case 289 /* ShorthandPropertyAssignment */:
42106                     return bindPropertyOrMethodOrAccessor(node, 4 /* Property */, 0 /* PropertyExcludes */);
42107                 case 291 /* EnumMember */:
42108                     return bindPropertyOrMethodOrAccessor(node, 8 /* EnumMember */, 900095 /* EnumMemberExcludes */);
42109                 case 169 /* CallSignature */:
42110                 case 170 /* ConstructSignature */:
42111                 case 171 /* IndexSignature */:
42112                     return declareSymbolAndAddToSymbolTable(node, 131072 /* Signature */, 0 /* None */);
42113                 case 165 /* MethodDeclaration */:
42114                 case 164 /* MethodSignature */:
42115                     // If this is an ObjectLiteralExpression method, then it sits in the same space
42116                     // as other properties in the object literal.  So we use SymbolFlags.PropertyExcludes
42117                     // so that it will conflict with any other object literal members with the same
42118                     // name.
42119                     return bindPropertyOrMethodOrAccessor(node, 8192 /* Method */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), ts.isObjectLiteralMethod(node) ? 0 /* PropertyExcludes */ : 103359 /* MethodExcludes */);
42120                 case 251 /* FunctionDeclaration */:
42121                     return bindFunctionDeclaration(node);
42122                 case 166 /* Constructor */:
42123                     return declareSymbolAndAddToSymbolTable(node, 16384 /* Constructor */, /*symbolExcludes:*/ 0 /* None */);
42124                 case 167 /* GetAccessor */:
42125                     return bindPropertyOrMethodOrAccessor(node, 32768 /* GetAccessor */, 46015 /* GetAccessorExcludes */);
42126                 case 168 /* SetAccessor */:
42127                     return bindPropertyOrMethodOrAccessor(node, 65536 /* SetAccessor */, 78783 /* SetAccessorExcludes */);
42128                 case 174 /* FunctionType */:
42129                 case 308 /* JSDocFunctionType */:
42130                 case 313 /* JSDocSignature */:
42131                 case 175 /* ConstructorType */:
42132                     return bindFunctionOrConstructorType(node);
42133                 case 177 /* TypeLiteral */:
42134                 case 312 /* JSDocTypeLiteral */:
42135                 case 190 /* MappedType */:
42136                     return bindAnonymousTypeWorker(node);
42137                 case 319 /* JSDocClassTag */:
42138                     return bindJSDocClassTag(node);
42139                 case 200 /* ObjectLiteralExpression */:
42140                     return bindObjectLiteralExpression(node);
42141                 case 208 /* FunctionExpression */:
42142                 case 209 /* ArrowFunction */:
42143                     return bindFunctionExpression(node);
42144                 case 203 /* CallExpression */:
42145                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
42146                     switch (assignmentKind) {
42147                         case 7 /* ObjectDefinePropertyValue */:
42148                             return bindObjectDefinePropertyAssignment(node);
42149                         case 8 /* ObjectDefinePropertyExports */:
42150                             return bindObjectDefinePropertyExport(node);
42151                         case 9 /* ObjectDefinePrototypeProperty */:
42152                             return bindObjectDefinePrototypeProperty(node);
42153                         case 0 /* None */:
42154                             break; // Nothing to do
42155                         default:
42156                             return ts.Debug.fail("Unknown call expression assignment declaration kind");
42157                     }
42158                     if (ts.isInJSFile(node)) {
42159                         bindCallExpression(node);
42160                     }
42161                     break;
42162                 // Members of classes, interfaces, and modules
42163                 case 221 /* ClassExpression */:
42164                 case 252 /* ClassDeclaration */:
42165                     // All classes are automatically in strict mode in ES6.
42166                     inStrictMode = true;
42167                     return bindClassLikeDeclaration(node);
42168                 case 253 /* InterfaceDeclaration */:
42169                     return bindBlockScopedDeclaration(node, 64 /* Interface */, 788872 /* InterfaceExcludes */);
42170                 case 254 /* TypeAliasDeclaration */:
42171                     return bindBlockScopedDeclaration(node, 524288 /* TypeAlias */, 788968 /* TypeAliasExcludes */);
42172                 case 255 /* EnumDeclaration */:
42173                     return bindEnumDeclaration(node);
42174                 case 256 /* ModuleDeclaration */:
42175                     return bindModuleDeclaration(node);
42176                 // Jsx-attributes
42177                 case 281 /* JsxAttributes */:
42178                     return bindJsxAttributes(node);
42179                 case 280 /* JsxAttribute */:
42180                     return bindJsxAttribute(node, 4 /* Property */, 0 /* PropertyExcludes */);
42181                 // Imports and exports
42182                 case 260 /* ImportEqualsDeclaration */:
42183                 case 263 /* NamespaceImport */:
42184                 case 265 /* ImportSpecifier */:
42185                 case 270 /* ExportSpecifier */:
42186                     return declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42187                 case 259 /* NamespaceExportDeclaration */:
42188                     return bindNamespaceExportDeclaration(node);
42189                 case 262 /* ImportClause */:
42190                     return bindImportClause(node);
42191                 case 267 /* ExportDeclaration */:
42192                     return bindExportDeclaration(node);
42193                 case 266 /* ExportAssignment */:
42194                     return bindExportAssignment(node);
42195                 case 297 /* SourceFile */:
42196                     updateStrictModeStatementList(node.statements);
42197                     return bindSourceFileIfExternalModule();
42198                 case 230 /* Block */:
42199                     if (!ts.isFunctionLike(node.parent)) {
42200                         return;
42201                     }
42202                 // falls through
42203                 case 257 /* ModuleBlock */:
42204                     return updateStrictModeStatementList(node.statements);
42205                 case 326 /* JSDocParameterTag */:
42206                     if (node.parent.kind === 313 /* JSDocSignature */) {
42207                         return bindParameter(node);
42208                     }
42209                     if (node.parent.kind !== 312 /* JSDocTypeLiteral */) {
42210                         break;
42211                     }
42212                 // falls through
42213                 case 333 /* JSDocPropertyTag */:
42214                     var propTag = node;
42215                     var flags = propTag.isBracketed || propTag.typeExpression && propTag.typeExpression.type.kind === 307 /* JSDocOptionalType */ ?
42216                         4 /* Property */ | 16777216 /* Optional */ :
42217                         4 /* Property */;
42218                     return declareSymbolAndAddToSymbolTable(propTag, flags, 0 /* PropertyExcludes */);
42219                 case 331 /* JSDocTypedefTag */:
42220                 case 324 /* JSDocCallbackTag */:
42221                 case 325 /* JSDocEnumTag */:
42222                     return (delayedTypeAliases || (delayedTypeAliases = [])).push(node);
42223             }
42224         }
42225         function bindPropertyWorker(node) {
42226             return bindPropertyOrMethodOrAccessor(node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
42227         }
42228         function bindAnonymousTypeWorker(node) {
42229             return bindAnonymousDeclaration(node, 2048 /* TypeLiteral */, "__type" /* Type */);
42230         }
42231         function bindSourceFileIfExternalModule() {
42232             setExportContextFlag(file);
42233             if (ts.isExternalModule(file)) {
42234                 bindSourceFileAsExternalModule();
42235             }
42236             else if (ts.isJsonSourceFile(file)) {
42237                 bindSourceFileAsExternalModule();
42238                 // Create symbol equivalent for the module.exports = {}
42239                 var originalSymbol = file.symbol;
42240                 declareSymbol(file.symbol.exports, file.symbol, file, 4 /* Property */, 67108863 /* All */);
42241                 file.symbol = originalSymbol;
42242             }
42243         }
42244         function bindSourceFileAsExternalModule() {
42245             bindAnonymousDeclaration(file, 512 /* ValueModule */, "\"" + ts.removeFileExtension(file.fileName) + "\"");
42246         }
42247         function bindExportAssignment(node) {
42248             if (!container.symbol || !container.symbol.exports) {
42249                 // Export assignment in some sort of block construct
42250                 bindAnonymousDeclaration(node, 2097152 /* Alias */, getDeclarationName(node));
42251             }
42252             else {
42253                 var flags = ts.exportAssignmentIsAlias(node)
42254                     // An export default clause with an EntityNameExpression or a class expression exports all meanings of that identifier or expression;
42255                     ? 2097152 /* Alias */
42256                     // An export default clause with any other expression exports a value
42257                     : 4 /* Property */;
42258                 // If there is an `export default x;` alias declaration, can't `export default` anything else.
42259                 // (In contrast, you can still have `export default function f() {}` and `export default interface I {}`.)
42260                 var symbol = declareSymbol(container.symbol.exports, container.symbol, node, flags, 67108863 /* All */);
42261                 if (node.isExportEquals) {
42262                     // Will be an error later, since the module already has other exports. Just make sure this has a valueDeclaration set.
42263                     ts.setValueDeclaration(symbol, node);
42264                 }
42265             }
42266         }
42267         function bindNamespaceExportDeclaration(node) {
42268             if (node.modifiers && node.modifiers.length) {
42269                 file.bindDiagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Modifiers_cannot_appear_here));
42270             }
42271             var diag = !ts.isSourceFile(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_at_top_level
42272                 : !ts.isExternalModule(node.parent) ? ts.Diagnostics.Global_module_exports_may_only_appear_in_module_files
42273                     : !node.parent.isDeclarationFile ? ts.Diagnostics.Global_module_exports_may_only_appear_in_declaration_files
42274                         : undefined;
42275             if (diag) {
42276                 file.bindDiagnostics.push(createDiagnosticForNode(node, diag));
42277             }
42278             else {
42279                 file.symbol.globalExports = file.symbol.globalExports || ts.createSymbolTable();
42280                 declareSymbol(file.symbol.globalExports, file.symbol, node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42281             }
42282         }
42283         function bindExportDeclaration(node) {
42284             if (!container.symbol || !container.symbol.exports) {
42285                 // Export * in some sort of block construct
42286                 bindAnonymousDeclaration(node, 8388608 /* ExportStar */, getDeclarationName(node));
42287             }
42288             else if (!node.exportClause) {
42289                 // All export * declarations are collected in an __export symbol
42290                 declareSymbol(container.symbol.exports, container.symbol, node, 8388608 /* ExportStar */, 0 /* None */);
42291             }
42292             else if (ts.isNamespaceExport(node.exportClause)) {
42293                 // declareSymbol walks up parents to find name text, parent _must_ be set
42294                 // but won't be set by the normal binder walk until `bindChildren` later on.
42295                 ts.setParent(node.exportClause, node);
42296                 declareSymbol(container.symbol.exports, container.symbol, node.exportClause, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42297             }
42298         }
42299         function bindImportClause(node) {
42300             if (node.name) {
42301                 declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42302             }
42303         }
42304         function setCommonJsModuleIndicator(node) {
42305             if (file.externalModuleIndicator) {
42306                 return false;
42307             }
42308             if (!file.commonJsModuleIndicator) {
42309                 file.commonJsModuleIndicator = node;
42310                 bindSourceFileAsExternalModule();
42311             }
42312             return true;
42313         }
42314         function bindObjectDefinePropertyExport(node) {
42315             if (!setCommonJsModuleIndicator(node)) {
42316                 return;
42317             }
42318             var symbol = forEachIdentifierInEntityName(node.arguments[0], /*parent*/ undefined, function (id, symbol) {
42319                 if (symbol) {
42320                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
42321                 }
42322                 return symbol;
42323             });
42324             if (symbol) {
42325                 var flags = 4 /* Property */ | 1048576 /* ExportValue */;
42326                 declareSymbol(symbol.exports, symbol, node, flags, 0 /* None */);
42327             }
42328         }
42329         function bindExportsPropertyAssignment(node) {
42330             // When we create a property via 'exports.foo = bar', the 'exports.foo' property access
42331             // expression is the declaration
42332             if (!setCommonJsModuleIndicator(node)) {
42333                 return;
42334             }
42335             var symbol = forEachIdentifierInEntityName(node.left.expression, /*parent*/ undefined, function (id, symbol) {
42336                 if (symbol) {
42337                     addDeclarationToSymbol(symbol, id, 1536 /* Module */ | 67108864 /* Assignment */);
42338                 }
42339                 return symbol;
42340             });
42341             if (symbol) {
42342                 var isAlias = ts.isAliasableExpression(node.right) && (ts.isExportsIdentifier(node.left.expression) || ts.isModuleExportsAccessExpression(node.left.expression));
42343                 var flags = isAlias ? 2097152 /* Alias */ : 4 /* Property */ | 1048576 /* ExportValue */;
42344                 ts.setParent(node.left, node);
42345                 declareSymbol(symbol.exports, symbol, node.left, flags, 0 /* None */);
42346             }
42347         }
42348         function bindModuleExportsAssignment(node) {
42349             // A common practice in node modules is to set 'export = module.exports = {}', this ensures that 'exports'
42350             // is still pointing to 'module.exports'.
42351             // We do not want to consider this as 'export=' since a module can have only one of these.
42352             // Similarly we do not want to treat 'module.exports = exports' as an 'export='.
42353             if (!setCommonJsModuleIndicator(node)) {
42354                 return;
42355             }
42356             var assignedExpression = ts.getRightMostAssignedExpression(node.right);
42357             if (ts.isEmptyObjectLiteral(assignedExpression) || container === file && isExportsOrModuleExportsOrAlias(file, assignedExpression)) {
42358                 return;
42359             }
42360             if (ts.isObjectLiteralExpression(assignedExpression) && ts.every(assignedExpression.properties, ts.isShorthandPropertyAssignment)) {
42361                 ts.forEach(assignedExpression.properties, bindExportAssignedObjectMemberAlias);
42362                 return;
42363             }
42364             // 'module.exports = expr' assignment
42365             var flags = ts.exportAssignmentIsAlias(node)
42366                 ? 2097152 /* Alias */
42367                 : 4 /* Property */ | 1048576 /* ExportValue */ | 512 /* ValueModule */;
42368             var symbol = declareSymbol(file.symbol.exports, file.symbol, node, flags | 67108864 /* Assignment */, 0 /* None */);
42369             ts.setValueDeclaration(symbol, node);
42370         }
42371         function bindExportAssignedObjectMemberAlias(node) {
42372             declareSymbol(file.symbol.exports, file.symbol, node, 2097152 /* Alias */ | 67108864 /* Assignment */, 0 /* None */);
42373         }
42374         function bindThisPropertyAssignment(node) {
42375             ts.Debug.assert(ts.isInJSFile(node));
42376             // private identifiers *must* be declared (even in JS files)
42377             var hasPrivateIdentifier = (ts.isBinaryExpression(node) && ts.isPropertyAccessExpression(node.left) && ts.isPrivateIdentifier(node.left.name))
42378                 || (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name));
42379             if (hasPrivateIdentifier) {
42380                 return;
42381             }
42382             var thisContainer = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
42383             switch (thisContainer.kind) {
42384                 case 251 /* FunctionDeclaration */:
42385                 case 208 /* FunctionExpression */:
42386                     var constructorSymbol = thisContainer.symbol;
42387                     // For `f.prototype.m = function() { this.x = 0; }`, `this.x = 0` should modify `f`'s members, not the function expression.
42388                     if (ts.isBinaryExpression(thisContainer.parent) && thisContainer.parent.operatorToken.kind === 62 /* EqualsToken */) {
42389                         var l = thisContainer.parent.left;
42390                         if (ts.isBindableStaticAccessExpression(l) && ts.isPrototypeAccess(l.expression)) {
42391                             constructorSymbol = lookupSymbolForPropertyAccess(l.expression.expression, thisParentContainer);
42392                         }
42393                     }
42394                     if (constructorSymbol && constructorSymbol.valueDeclaration) {
42395                         // Declare a 'member' if the container is an ES5 class or ES6 constructor
42396                         constructorSymbol.members = constructorSymbol.members || ts.createSymbolTable();
42397                         // It's acceptable for multiple 'this' assignments of the same identifier to occur
42398                         if (ts.hasDynamicName(node)) {
42399                             bindDynamicallyNamedThisPropertyAssignment(node, constructorSymbol);
42400                         }
42401                         else {
42402                             declareSymbol(constructorSymbol.members, constructorSymbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* PropertyExcludes */ & ~4 /* Property */);
42403                         }
42404                         addDeclarationToSymbol(constructorSymbol, constructorSymbol.valueDeclaration, 32 /* Class */);
42405                     }
42406                     break;
42407                 case 166 /* Constructor */:
42408                 case 163 /* PropertyDeclaration */:
42409                 case 165 /* MethodDeclaration */:
42410                 case 167 /* GetAccessor */:
42411                 case 168 /* SetAccessor */:
42412                     // this.foo assignment in a JavaScript class
42413                     // Bind this property to the containing class
42414                     var containingClass = thisContainer.parent;
42415                     var symbolTable = ts.hasSyntacticModifier(thisContainer, 32 /* Static */) ? containingClass.symbol.exports : containingClass.symbol.members;
42416                     if (ts.hasDynamicName(node)) {
42417                         bindDynamicallyNamedThisPropertyAssignment(node, containingClass.symbol);
42418                     }
42419                     else {
42420                         declareSymbol(symbolTable, containingClass.symbol, node, 4 /* Property */ | 67108864 /* Assignment */, 0 /* None */, /*isReplaceableByMethod*/ true);
42421                     }
42422                     break;
42423                 case 297 /* SourceFile */:
42424                     // this.property = assignment in a source file -- declare symbol in exports for a module, in locals for a script
42425                     if (ts.hasDynamicName(node)) {
42426                         break;
42427                     }
42428                     else if (thisContainer.commonJsModuleIndicator) {
42429                         declareSymbol(thisContainer.symbol.exports, thisContainer.symbol, node, 4 /* Property */ | 1048576 /* ExportValue */, 0 /* None */);
42430                     }
42431                     else {
42432                         declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
42433                     }
42434                     break;
42435                 default:
42436                     ts.Debug.failBadSyntaxKind(thisContainer);
42437             }
42438         }
42439         function bindDynamicallyNamedThisPropertyAssignment(node, symbol) {
42440             bindAnonymousDeclaration(node, 4 /* Property */, "__computed" /* Computed */);
42441             addLateBoundAssignmentDeclarationToSymbol(node, symbol);
42442         }
42443         function addLateBoundAssignmentDeclarationToSymbol(node, symbol) {
42444             if (symbol) {
42445                 (symbol.assignmentDeclarationMembers || (symbol.assignmentDeclarationMembers = new ts.Map())).set(ts.getNodeId(node), node);
42446             }
42447         }
42448         function bindSpecialPropertyDeclaration(node) {
42449             if (node.expression.kind === 107 /* ThisKeyword */) {
42450                 bindThisPropertyAssignment(node);
42451             }
42452             else if (ts.isBindableStaticAccessExpression(node) && node.parent.parent.kind === 297 /* SourceFile */) {
42453                 if (ts.isPrototypeAccess(node.expression)) {
42454                     bindPrototypePropertyAssignment(node, node.parent);
42455                 }
42456                 else {
42457                     bindStaticPropertyAssignment(node);
42458                 }
42459             }
42460         }
42461         /** For `x.prototype = { p, ... }`, declare members p,... if `x` is function/class/{}, or not declared. */
42462         function bindPrototypeAssignment(node) {
42463             ts.setParent(node.left, node);
42464             ts.setParent(node.right, node);
42465             bindPropertyAssignment(node.left.expression, node.left, /*isPrototypeProperty*/ false, /*containerIsClass*/ true);
42466         }
42467         function bindObjectDefinePrototypeProperty(node) {
42468             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0].expression);
42469             if (namespaceSymbol && namespaceSymbol.valueDeclaration) {
42470                 // Ensure the namespace symbol becomes class-like
42471                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
42472             }
42473             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ true);
42474         }
42475         /**
42476          * For `x.prototype.y = z`, declare a member `y` on `x` if `x` is a function or class, or not declared.
42477          * Note that jsdoc preceding an ExpressionStatement like `x.prototype.y;` is also treated as a declaration.
42478          */
42479         function bindPrototypePropertyAssignment(lhs, parent) {
42480             // Look up the function in the local scope, since prototype assignments should
42481             // follow the function declaration
42482             var classPrototype = lhs.expression;
42483             var constructorFunction = classPrototype.expression;
42484             // Fix up parent pointers since we're going to use these nodes before we bind into them
42485             ts.setParent(constructorFunction, classPrototype);
42486             ts.setParent(classPrototype, lhs);
42487             ts.setParent(lhs, parent);
42488             bindPropertyAssignment(constructorFunction, lhs, /*isPrototypeProperty*/ true, /*containerIsClass*/ true);
42489         }
42490         function bindObjectDefinePropertyAssignment(node) {
42491             var namespaceSymbol = lookupSymbolForPropertyAccess(node.arguments[0]);
42492             var isToplevel = node.parent.parent.kind === 297 /* SourceFile */;
42493             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, node.arguments[0], isToplevel, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
42494             bindPotentiallyNewExpandoMemberToNamespace(node, namespaceSymbol, /*isPrototypeProperty*/ false);
42495         }
42496         function bindSpecialPropertyAssignment(node) {
42497             var _a;
42498             // Class declarations in Typescript do not allow property declarations
42499             var parentSymbol = lookupSymbolForPropertyAccess(node.left.expression, container) || lookupSymbolForPropertyAccess(node.left.expression, blockScopeContainer);
42500             if (!ts.isInJSFile(node) && !ts.isFunctionSymbol(parentSymbol)) {
42501                 return;
42502             }
42503             var rootExpr = ts.getLeftmostAccessExpression(node.left);
42504             if (ts.isIdentifier(rootExpr) && ((_a = lookupSymbolForName(container, rootExpr.escapedText)) === null || _a === void 0 ? void 0 : _a.flags) & 2097152 /* Alias */) {
42505                 return;
42506             }
42507             // Fix up parent pointers since we're going to use these nodes before we bind into them
42508             ts.setParent(node.left, node);
42509             ts.setParent(node.right, node);
42510             if (ts.isIdentifier(node.left.expression) && container === file && isExportsOrModuleExportsOrAlias(file, node.left.expression)) {
42511                 // This can be an alias for the 'exports' or 'module.exports' names, e.g.
42512                 //    var util = module.exports;
42513                 //    util.property = function ...
42514                 bindExportsPropertyAssignment(node);
42515             }
42516             else if (ts.hasDynamicName(node)) {
42517                 bindAnonymousDeclaration(node, 4 /* Property */ | 67108864 /* Assignment */, "__computed" /* Computed */);
42518                 var sym = bindPotentiallyMissingNamespaces(parentSymbol, node.left.expression, isTopLevelNamespaceAssignment(node.left), /*isPrototype*/ false, /*containerIsClass*/ false);
42519                 addLateBoundAssignmentDeclarationToSymbol(node, sym);
42520             }
42521             else {
42522                 bindStaticPropertyAssignment(ts.cast(node.left, ts.isBindableStaticNameExpression));
42523             }
42524         }
42525         /**
42526          * 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.
42527          * Also works for expression statements preceded by JSDoc, like / ** @type number * / x.y;
42528          */
42529         function bindStaticPropertyAssignment(node) {
42530             ts.Debug.assert(!ts.isIdentifier(node));
42531             ts.setParent(node.expression, node);
42532             bindPropertyAssignment(node.expression, node, /*isPrototypeProperty*/ false, /*containerIsClass*/ false);
42533         }
42534         function bindPotentiallyMissingNamespaces(namespaceSymbol, entityName, isToplevel, isPrototypeProperty, containerIsClass) {
42535             if ((namespaceSymbol === null || namespaceSymbol === void 0 ? void 0 : namespaceSymbol.flags) & 2097152 /* Alias */) {
42536                 return namespaceSymbol;
42537             }
42538             if (isToplevel && !isPrototypeProperty) {
42539                 // make symbols or add declarations for intermediate containers
42540                 var flags_2 = 1536 /* Module */ | 67108864 /* Assignment */;
42541                 var excludeFlags_1 = 110735 /* ValueModuleExcludes */ & ~67108864 /* Assignment */;
42542                 namespaceSymbol = forEachIdentifierInEntityName(entityName, namespaceSymbol, function (id, symbol, parent) {
42543                     if (symbol) {
42544                         addDeclarationToSymbol(symbol, id, flags_2);
42545                         return symbol;
42546                     }
42547                     else {
42548                         var table = parent ? parent.exports :
42549                             file.jsGlobalAugmentations || (file.jsGlobalAugmentations = ts.createSymbolTable());
42550                         return declareSymbol(table, parent, id, flags_2, excludeFlags_1);
42551                     }
42552                 });
42553             }
42554             if (containerIsClass && namespaceSymbol && namespaceSymbol.valueDeclaration) {
42555                 addDeclarationToSymbol(namespaceSymbol, namespaceSymbol.valueDeclaration, 32 /* Class */);
42556             }
42557             return namespaceSymbol;
42558         }
42559         function bindPotentiallyNewExpandoMemberToNamespace(declaration, namespaceSymbol, isPrototypeProperty) {
42560             if (!namespaceSymbol || !isExpandoSymbol(namespaceSymbol)) {
42561                 return;
42562             }
42563             // Set up the members collection if it doesn't exist already
42564             var symbolTable = isPrototypeProperty ?
42565                 (namespaceSymbol.members || (namespaceSymbol.members = ts.createSymbolTable())) :
42566                 (namespaceSymbol.exports || (namespaceSymbol.exports = ts.createSymbolTable()));
42567             var includes = 0 /* None */;
42568             var excludes = 0 /* None */;
42569             // Method-like
42570             if (ts.isFunctionLikeDeclaration(ts.getAssignedExpandoInitializer(declaration))) {
42571                 includes = 8192 /* Method */;
42572                 excludes = 103359 /* MethodExcludes */;
42573             }
42574             // Maybe accessor-like
42575             else if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
42576                 if (ts.some(declaration.arguments[2].properties, function (p) {
42577                     var id = ts.getNameOfDeclaration(p);
42578                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "set";
42579                 })) {
42580                     // We mix in `SymbolFLags.Property` so in the checker `getTypeOfVariableParameterOrProperty` is used for this
42581                     // symbol, instead of `getTypeOfAccessor` (which will assert as there is no real accessor declaration)
42582                     includes |= 65536 /* SetAccessor */ | 4 /* Property */;
42583                     excludes |= 78783 /* SetAccessorExcludes */;
42584                 }
42585                 if (ts.some(declaration.arguments[2].properties, function (p) {
42586                     var id = ts.getNameOfDeclaration(p);
42587                     return !!id && ts.isIdentifier(id) && ts.idText(id) === "get";
42588                 })) {
42589                     includes |= 32768 /* GetAccessor */ | 4 /* Property */;
42590                     excludes |= 46015 /* GetAccessorExcludes */;
42591                 }
42592             }
42593             if (includes === 0 /* None */) {
42594                 includes = 4 /* Property */;
42595                 excludes = 0 /* PropertyExcludes */;
42596             }
42597             declareSymbol(symbolTable, namespaceSymbol, declaration, includes | 67108864 /* Assignment */, excludes & ~67108864 /* Assignment */);
42598         }
42599         function isTopLevelNamespaceAssignment(propertyAccess) {
42600             return ts.isBinaryExpression(propertyAccess.parent)
42601                 ? getParentOfBinaryExpression(propertyAccess.parent).parent.kind === 297 /* SourceFile */
42602                 : propertyAccess.parent.parent.kind === 297 /* SourceFile */;
42603         }
42604         function bindPropertyAssignment(name, propertyAccess, isPrototypeProperty, containerIsClass) {
42605             var namespaceSymbol = lookupSymbolForPropertyAccess(name, container) || lookupSymbolForPropertyAccess(name, blockScopeContainer);
42606             var isToplevel = isTopLevelNamespaceAssignment(propertyAccess);
42607             namespaceSymbol = bindPotentiallyMissingNamespaces(namespaceSymbol, propertyAccess.expression, isToplevel, isPrototypeProperty, containerIsClass);
42608             bindPotentiallyNewExpandoMemberToNamespace(propertyAccess, namespaceSymbol, isPrototypeProperty);
42609         }
42610         /**
42611          * Javascript expando values are:
42612          * - Functions
42613          * - classes
42614          * - namespaces
42615          * - variables initialized with function expressions
42616          * -                       with class expressions
42617          * -                       with empty object literals
42618          * -                       with non-empty object literals if assigned to the prototype property
42619          */
42620         function isExpandoSymbol(symbol) {
42621             if (symbol.flags & (16 /* Function */ | 32 /* Class */ | 1024 /* NamespaceModule */)) {
42622                 return true;
42623             }
42624             var node = symbol.valueDeclaration;
42625             if (node && ts.isCallExpression(node)) {
42626                 return !!ts.getAssignedExpandoInitializer(node);
42627             }
42628             var init = !node ? undefined :
42629                 ts.isVariableDeclaration(node) ? node.initializer :
42630                     ts.isBinaryExpression(node) ? node.right :
42631                         ts.isPropertyAccessExpression(node) && ts.isBinaryExpression(node.parent) ? node.parent.right :
42632                             undefined;
42633             init = init && ts.getRightMostAssignedExpression(init);
42634             if (init) {
42635                 var isPrototypeAssignment = ts.isPrototypeAccess(ts.isVariableDeclaration(node) ? node.name : ts.isBinaryExpression(node) ? node.left : node);
42636                 return !!ts.getExpandoInitializer(ts.isBinaryExpression(init) && (init.operatorToken.kind === 56 /* BarBarToken */ || init.operatorToken.kind === 60 /* QuestionQuestionToken */) ? init.right : init, isPrototypeAssignment);
42637             }
42638             return false;
42639         }
42640         function getParentOfBinaryExpression(expr) {
42641             while (ts.isBinaryExpression(expr.parent)) {
42642                 expr = expr.parent;
42643             }
42644             return expr.parent;
42645         }
42646         function lookupSymbolForPropertyAccess(node, lookupContainer) {
42647             if (lookupContainer === void 0) { lookupContainer = container; }
42648             if (ts.isIdentifier(node)) {
42649                 return lookupSymbolForName(lookupContainer, node.escapedText);
42650             }
42651             else {
42652                 var symbol = lookupSymbolForPropertyAccess(node.expression);
42653                 return symbol && symbol.exports && symbol.exports.get(ts.getElementOrPropertyAccessName(node));
42654             }
42655         }
42656         function forEachIdentifierInEntityName(e, parent, action) {
42657             if (isExportsOrModuleExportsOrAlias(file, e)) {
42658                 return file.symbol;
42659             }
42660             else if (ts.isIdentifier(e)) {
42661                 return action(e, lookupSymbolForPropertyAccess(e), parent);
42662             }
42663             else {
42664                 var s = forEachIdentifierInEntityName(e.expression, parent, action);
42665                 var name = ts.getNameOrArgument(e);
42666                 // unreachable
42667                 if (ts.isPrivateIdentifier(name)) {
42668                     ts.Debug.fail("unexpected PrivateIdentifier");
42669                 }
42670                 return action(name, s && s.exports && s.exports.get(ts.getElementOrPropertyAccessName(e)), s);
42671             }
42672         }
42673         function bindCallExpression(node) {
42674             // We're only inspecting call expressions to detect CommonJS modules, so we can skip
42675             // this check if we've already seen the module indicator
42676             if (!file.commonJsModuleIndicator && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ false)) {
42677                 setCommonJsModuleIndicator(node);
42678             }
42679         }
42680         function bindClassLikeDeclaration(node) {
42681             if (node.kind === 252 /* ClassDeclaration */) {
42682                 bindBlockScopedDeclaration(node, 32 /* Class */, 899503 /* ClassExcludes */);
42683             }
42684             else {
42685                 var bindingName = node.name ? node.name.escapedText : "__class" /* Class */;
42686                 bindAnonymousDeclaration(node, 32 /* Class */, bindingName);
42687                 // Add name of class expression into the map for semantic classifier
42688                 if (node.name) {
42689                     classifiableNames.add(node.name.escapedText);
42690                 }
42691             }
42692             var symbol = node.symbol;
42693             // TypeScript 1.0 spec (April 2014): 8.4
42694             // Every class automatically contains a static property member named 'prototype', the
42695             // type of which is an instantiation of the class type with type Any supplied as a type
42696             // argument for each type parameter. It is an error to explicitly declare a static
42697             // property member with the name 'prototype'.
42698             //
42699             // Note: we check for this here because this class may be merging into a module.  The
42700             // module might have an exported variable called 'prototype'.  We can't allow that as
42701             // that would clash with the built-in 'prototype' for the class.
42702             var prototypeSymbol = createSymbol(4 /* Property */ | 4194304 /* Prototype */, "prototype");
42703             var symbolExport = symbol.exports.get(prototypeSymbol.escapedName);
42704             if (symbolExport) {
42705                 if (node.name) {
42706                     ts.setParent(node.name, node);
42707                 }
42708                 file.bindDiagnostics.push(createDiagnosticForNode(symbolExport.declarations[0], ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(prototypeSymbol)));
42709             }
42710             symbol.exports.set(prototypeSymbol.escapedName, prototypeSymbol);
42711             prototypeSymbol.parent = symbol;
42712         }
42713         function bindEnumDeclaration(node) {
42714             return ts.isEnumConst(node)
42715                 ? bindBlockScopedDeclaration(node, 128 /* ConstEnum */, 899967 /* ConstEnumExcludes */)
42716                 : bindBlockScopedDeclaration(node, 256 /* RegularEnum */, 899327 /* RegularEnumExcludes */);
42717         }
42718         function bindVariableDeclarationOrBindingElement(node) {
42719             if (inStrictMode) {
42720                 checkStrictModeEvalOrArguments(node, node.name);
42721             }
42722             if (!ts.isBindingPattern(node.name)) {
42723                 if (ts.isInJSFile(node) && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true) && !ts.getJSDocTypeTag(node)) {
42724                     declareSymbolAndAddToSymbolTable(node, 2097152 /* Alias */, 2097152 /* AliasExcludes */);
42725                 }
42726                 else if (ts.isBlockOrCatchScoped(node)) {
42727                     bindBlockScopedDeclaration(node, 2 /* BlockScopedVariable */, 111551 /* BlockScopedVariableExcludes */);
42728                 }
42729                 else if (ts.isParameterDeclaration(node)) {
42730                     // It is safe to walk up parent chain to find whether the node is a destructuring parameter declaration
42731                     // because its parent chain has already been set up, since parents are set before descending into children.
42732                     //
42733                     // If node is a binding element in parameter declaration, we need to use ParameterExcludes.
42734                     // Using ParameterExcludes flag allows the compiler to report an error on duplicate identifiers in Parameter Declaration
42735                     // For example:
42736                     //      function foo([a,a]) {} // Duplicate Identifier error
42737                     //      function bar(a,a) {}   // Duplicate Identifier error, parameter declaration in this case is handled in bindParameter
42738                     //                             // which correctly set excluded symbols
42739                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
42740                 }
42741                 else {
42742                     declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111550 /* FunctionScopedVariableExcludes */);
42743                 }
42744             }
42745         }
42746         function bindParameter(node) {
42747             if (node.kind === 326 /* JSDocParameterTag */ && container.kind !== 313 /* JSDocSignature */) {
42748                 return;
42749             }
42750             if (inStrictMode && !(node.flags & 8388608 /* Ambient */)) {
42751                 // It is a SyntaxError if the identifier eval or arguments appears within a FormalParameterList of a
42752                 // strict mode FunctionLikeDeclaration or FunctionExpression(13.1)
42753                 checkStrictModeEvalOrArguments(node, node.name);
42754             }
42755             if (ts.isBindingPattern(node.name)) {
42756                 bindAnonymousDeclaration(node, 1 /* FunctionScopedVariable */, "__" + node.parent.parameters.indexOf(node));
42757             }
42758             else {
42759                 declareSymbolAndAddToSymbolTable(node, 1 /* FunctionScopedVariable */, 111551 /* ParameterExcludes */);
42760             }
42761             // If this is a property-parameter, then also declare the property symbol into the
42762             // containing class.
42763             if (ts.isParameterPropertyDeclaration(node, node.parent)) {
42764                 var classDeclaration = node.parent.parent;
42765                 declareSymbol(classDeclaration.symbol.members, classDeclaration.symbol, node, 4 /* Property */ | (node.questionToken ? 16777216 /* Optional */ : 0 /* None */), 0 /* PropertyExcludes */);
42766             }
42767         }
42768         function bindFunctionDeclaration(node) {
42769             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
42770                 if (ts.isAsyncFunction(node)) {
42771                     emitFlags |= 2048 /* HasAsyncFunctions */;
42772                 }
42773             }
42774             checkStrictModeFunctionName(node);
42775             if (inStrictMode) {
42776                 checkStrictModeFunctionDeclaration(node);
42777                 bindBlockScopedDeclaration(node, 16 /* Function */, 110991 /* FunctionExcludes */);
42778             }
42779             else {
42780                 declareSymbolAndAddToSymbolTable(node, 16 /* Function */, 110991 /* FunctionExcludes */);
42781             }
42782         }
42783         function bindFunctionExpression(node) {
42784             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */)) {
42785                 if (ts.isAsyncFunction(node)) {
42786                     emitFlags |= 2048 /* HasAsyncFunctions */;
42787                 }
42788             }
42789             if (currentFlow) {
42790                 node.flowNode = currentFlow;
42791             }
42792             checkStrictModeFunctionName(node);
42793             var bindingName = node.name ? node.name.escapedText : "__function" /* Function */;
42794             return bindAnonymousDeclaration(node, 16 /* Function */, bindingName);
42795         }
42796         function bindPropertyOrMethodOrAccessor(node, symbolFlags, symbolExcludes) {
42797             if (!file.isDeclarationFile && !(node.flags & 8388608 /* Ambient */) && ts.isAsyncFunction(node)) {
42798                 emitFlags |= 2048 /* HasAsyncFunctions */;
42799             }
42800             if (currentFlow && ts.isObjectLiteralOrClassExpressionMethod(node)) {
42801                 node.flowNode = currentFlow;
42802             }
42803             return ts.hasDynamicName(node)
42804                 ? bindAnonymousDeclaration(node, symbolFlags, "__computed" /* Computed */)
42805                 : declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
42806         }
42807         function getInferTypeContainer(node) {
42808             var extendsType = ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && n.parent.extendsType === n; });
42809             return extendsType && extendsType.parent;
42810         }
42811         function bindTypeParameter(node) {
42812             if (ts.isJSDocTemplateTag(node.parent)) {
42813                 var container_1 = ts.find(node.parent.parent.tags, ts.isJSDocTypeAlias) || ts.getHostSignatureFromJSDoc(node.parent); // TODO: GH#18217
42814                 if (container_1) {
42815                     if (!container_1.locals) {
42816                         container_1.locals = ts.createSymbolTable();
42817                     }
42818                     declareSymbol(container_1.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
42819                 }
42820                 else {
42821                     declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
42822                 }
42823             }
42824             else if (node.parent.kind === 185 /* InferType */) {
42825                 var container_2 = getInferTypeContainer(node.parent);
42826                 if (container_2) {
42827                     if (!container_2.locals) {
42828                         container_2.locals = ts.createSymbolTable();
42829                     }
42830                     declareSymbol(container_2.locals, /*parent*/ undefined, node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
42831                 }
42832                 else {
42833                     bindAnonymousDeclaration(node, 262144 /* TypeParameter */, getDeclarationName(node)); // TODO: GH#18217
42834                 }
42835             }
42836             else {
42837                 declareSymbolAndAddToSymbolTable(node, 262144 /* TypeParameter */, 526824 /* TypeParameterExcludes */);
42838             }
42839         }
42840         // reachability checks
42841         function shouldReportErrorOnModuleDeclaration(node) {
42842             var instanceState = getModuleInstanceState(node);
42843             return instanceState === 1 /* Instantiated */ || (instanceState === 2 /* ConstEnumOnly */ && !!options.preserveConstEnums);
42844         }
42845         function checkUnreachable(node) {
42846             if (!(currentFlow.flags & 1 /* Unreachable */)) {
42847                 return false;
42848             }
42849             if (currentFlow === unreachableFlow) {
42850                 var reportError = 
42851                 // report error on all statements except empty ones
42852                 (ts.isStatementButNotDeclaration(node) && node.kind !== 231 /* EmptyStatement */) ||
42853                     // report error on class declarations
42854                     node.kind === 252 /* ClassDeclaration */ ||
42855                     // report error on instantiated modules or const-enums only modules if preserveConstEnums is set
42856                     (node.kind === 256 /* ModuleDeclaration */ && shouldReportErrorOnModuleDeclaration(node));
42857                 if (reportError) {
42858                     currentFlow = reportedUnreachableFlow;
42859                     if (!options.allowUnreachableCode) {
42860                         // unreachable code is reported if
42861                         // - user has explicitly asked about it AND
42862                         // - statement is in not ambient context (statements in ambient context is already an error
42863                         //   so we should not report extras) AND
42864                         //   - node is not variable statement OR
42865                         //   - node is block scoped variable statement OR
42866                         //   - node is not block scoped variable statement and at least one variable declaration has initializer
42867                         //   Rationale: we don't want to report errors on non-initialized var's since they are hoisted
42868                         //   On the other side we do want to report errors on non-initialized 'lets' because of TDZ
42869                         var isError_1 = ts.unreachableCodeIsError(options) &&
42870                             !(node.flags & 8388608 /* Ambient */) &&
42871                             (!ts.isVariableStatement(node) ||
42872                                 !!(ts.getCombinedNodeFlags(node.declarationList) & 3 /* BlockScoped */) ||
42873                                 node.declarationList.declarations.some(function (d) { return !!d.initializer; }));
42874                         eachUnreachableRange(node, function (start, end) { return errorOrSuggestionOnRange(isError_1, start, end, ts.Diagnostics.Unreachable_code_detected); });
42875                     }
42876                 }
42877             }
42878             return true;
42879         }
42880     }
42881     function eachUnreachableRange(node, cb) {
42882         if (ts.isStatement(node) && isExecutableStatement(node) && ts.isBlock(node.parent)) {
42883             var statements = node.parent.statements;
42884             var slice_1 = ts.sliceAfter(statements, node);
42885             ts.getRangesWhere(slice_1, isExecutableStatement, function (start, afterEnd) { return cb(slice_1[start], slice_1[afterEnd - 1]); });
42886         }
42887         else {
42888             cb(node, node);
42889         }
42890     }
42891     // As opposed to a pure declaration like an `interface`
42892     function isExecutableStatement(s) {
42893         // Don't remove statements that can validly be used before they appear.
42894         return !ts.isFunctionDeclaration(s) && !isPurelyTypeDeclaration(s) && !ts.isEnumDeclaration(s) &&
42895             // `var x;` may declare a variable used above
42896             !(ts.isVariableStatement(s) && !(ts.getCombinedNodeFlags(s) & (1 /* Let */ | 2 /* Const */)) && s.declarationList.declarations.some(function (d) { return !d.initializer; }));
42897     }
42898     function isPurelyTypeDeclaration(s) {
42899         switch (s.kind) {
42900             case 253 /* InterfaceDeclaration */:
42901             case 254 /* TypeAliasDeclaration */:
42902                 return true;
42903             case 256 /* ModuleDeclaration */:
42904                 return getModuleInstanceState(s) !== 1 /* Instantiated */;
42905             case 255 /* EnumDeclaration */:
42906                 return ts.hasSyntacticModifier(s, 2048 /* Const */);
42907             default:
42908                 return false;
42909         }
42910     }
42911     function isExportsOrModuleExportsOrAlias(sourceFile, node) {
42912         var i = 0;
42913         var q = [node];
42914         while (q.length && i < 100) {
42915             i++;
42916             node = q.shift();
42917             if (ts.isExportsIdentifier(node) || ts.isModuleExportsAccessExpression(node)) {
42918                 return true;
42919             }
42920             else if (ts.isIdentifier(node)) {
42921                 var symbol = lookupSymbolForName(sourceFile, node.escapedText);
42922                 if (!!symbol && !!symbol.valueDeclaration && ts.isVariableDeclaration(symbol.valueDeclaration) && !!symbol.valueDeclaration.initializer) {
42923                     var init = symbol.valueDeclaration.initializer;
42924                     q.push(init);
42925                     if (ts.isAssignmentExpression(init, /*excludeCompoundAssignment*/ true)) {
42926                         q.push(init.left);
42927                         q.push(init.right);
42928                     }
42929                 }
42930             }
42931         }
42932         return false;
42933     }
42934     ts.isExportsOrModuleExportsOrAlias = isExportsOrModuleExportsOrAlias;
42935     function lookupSymbolForName(container, name) {
42936         var local = container.locals && container.locals.get(name);
42937         if (local) {
42938             return local.exportSymbol || local;
42939         }
42940         if (ts.isSourceFile(container) && container.jsGlobalAugmentations && container.jsGlobalAugmentations.has(name)) {
42941             return container.jsGlobalAugmentations.get(name);
42942         }
42943         return container.symbol && container.symbol.exports && container.symbol.exports.get(name);
42944     }
42945 })(ts || (ts = {}));
42946 /** @internal */
42947 var ts;
42948 (function (ts) {
42949     function createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, getFirstIdentifier, getTypeArguments) {
42950         return getSymbolWalker;
42951         function getSymbolWalker(accept) {
42952             if (accept === void 0) { accept = function () { return true; }; }
42953             var visitedTypes = []; // Sparse array from id to type
42954             var visitedSymbols = []; // Sparse array from id to symbol
42955             return {
42956                 walkType: function (type) {
42957                     try {
42958                         visitType(type);
42959                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
42960                     }
42961                     finally {
42962                         ts.clear(visitedTypes);
42963                         ts.clear(visitedSymbols);
42964                     }
42965                 },
42966                 walkSymbol: function (symbol) {
42967                     try {
42968                         visitSymbol(symbol);
42969                         return { visitedTypes: ts.getOwnValues(visitedTypes), visitedSymbols: ts.getOwnValues(visitedSymbols) };
42970                     }
42971                     finally {
42972                         ts.clear(visitedTypes);
42973                         ts.clear(visitedSymbols);
42974                     }
42975                 },
42976             };
42977             function visitType(type) {
42978                 if (!type) {
42979                     return;
42980                 }
42981                 if (visitedTypes[type.id]) {
42982                     return;
42983                 }
42984                 visitedTypes[type.id] = type;
42985                 // Reuse visitSymbol to visit the type's symbol,
42986                 //  but be sure to bail on recuring into the type if accept declines the symbol.
42987                 var shouldBail = visitSymbol(type.symbol);
42988                 if (shouldBail)
42989                     return;
42990                 // Visit the type's related types, if any
42991                 if (type.flags & 524288 /* Object */) {
42992                     var objectType = type;
42993                     var objectFlags = objectType.objectFlags;
42994                     if (objectFlags & 4 /* Reference */) {
42995                         visitTypeReference(type);
42996                     }
42997                     if (objectFlags & 32 /* Mapped */) {
42998                         visitMappedType(type);
42999                     }
43000                     if (objectFlags & (1 /* Class */ | 2 /* Interface */)) {
43001                         visitInterfaceType(type);
43002                     }
43003                     if (objectFlags & (8 /* Tuple */ | 16 /* Anonymous */)) {
43004                         visitObjectType(objectType);
43005                     }
43006                 }
43007                 if (type.flags & 262144 /* TypeParameter */) {
43008                     visitTypeParameter(type);
43009                 }
43010                 if (type.flags & 3145728 /* UnionOrIntersection */) {
43011                     visitUnionOrIntersectionType(type);
43012                 }
43013                 if (type.flags & 4194304 /* Index */) {
43014                     visitIndexType(type);
43015                 }
43016                 if (type.flags & 8388608 /* IndexedAccess */) {
43017                     visitIndexedAccessType(type);
43018                 }
43019             }
43020             function visitTypeReference(type) {
43021                 visitType(type.target);
43022                 ts.forEach(getTypeArguments(type), visitType);
43023             }
43024             function visitTypeParameter(type) {
43025                 visitType(getConstraintOfTypeParameter(type));
43026             }
43027             function visitUnionOrIntersectionType(type) {
43028                 ts.forEach(type.types, visitType);
43029             }
43030             function visitIndexType(type) {
43031                 visitType(type.type);
43032             }
43033             function visitIndexedAccessType(type) {
43034                 visitType(type.objectType);
43035                 visitType(type.indexType);
43036                 visitType(type.constraint);
43037             }
43038             function visitMappedType(type) {
43039                 visitType(type.typeParameter);
43040                 visitType(type.constraintType);
43041                 visitType(type.templateType);
43042                 visitType(type.modifiersType);
43043             }
43044             function visitSignature(signature) {
43045                 var typePredicate = getTypePredicateOfSignature(signature);
43046                 if (typePredicate) {
43047                     visitType(typePredicate.type);
43048                 }
43049                 ts.forEach(signature.typeParameters, visitType);
43050                 for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
43051                     var parameter = _a[_i];
43052                     visitSymbol(parameter);
43053                 }
43054                 visitType(getRestTypeOfSignature(signature));
43055                 visitType(getReturnTypeOfSignature(signature));
43056             }
43057             function visitInterfaceType(interfaceT) {
43058                 visitObjectType(interfaceT);
43059                 ts.forEach(interfaceT.typeParameters, visitType);
43060                 ts.forEach(getBaseTypes(interfaceT), visitType);
43061                 visitType(interfaceT.thisType);
43062             }
43063             function visitObjectType(type) {
43064                 var stringIndexType = getIndexTypeOfStructuredType(type, 0 /* String */);
43065                 visitType(stringIndexType);
43066                 var numberIndexType = getIndexTypeOfStructuredType(type, 1 /* Number */);
43067                 visitType(numberIndexType);
43068                 // The two checks above *should* have already resolved the type (if needed), so this should be cached
43069                 var resolved = resolveStructuredTypeMembers(type);
43070                 for (var _i = 0, _a = resolved.callSignatures; _i < _a.length; _i++) {
43071                     var signature = _a[_i];
43072                     visitSignature(signature);
43073                 }
43074                 for (var _b = 0, _c = resolved.constructSignatures; _b < _c.length; _b++) {
43075                     var signature = _c[_b];
43076                     visitSignature(signature);
43077                 }
43078                 for (var _d = 0, _e = resolved.properties; _d < _e.length; _d++) {
43079                     var p = _e[_d];
43080                     visitSymbol(p);
43081                 }
43082             }
43083             function visitSymbol(symbol) {
43084                 if (!symbol) {
43085                     return false;
43086                 }
43087                 var symbolId = ts.getSymbolId(symbol);
43088                 if (visitedSymbols[symbolId]) {
43089                     return false;
43090                 }
43091                 visitedSymbols[symbolId] = symbol;
43092                 if (!accept(symbol)) {
43093                     return true;
43094                 }
43095                 var t = getTypeOfSymbol(symbol);
43096                 visitType(t); // Should handle members on classes and such
43097                 if (symbol.exports) {
43098                     symbol.exports.forEach(visitSymbol);
43099                 }
43100                 ts.forEach(symbol.declarations, function (d) {
43101                     // Type queries are too far resolved when we just visit the symbol's type
43102                     //  (their type resolved directly to the member deeply referenced)
43103                     // So to get the intervening symbols, we need to check if there's a type
43104                     // query node on any of the symbol's declarations and get symbols there
43105                     if (d.type && d.type.kind === 176 /* TypeQuery */) {
43106                         var query = d.type;
43107                         var entity = getResolvedSymbol(getFirstIdentifier(query.exprName));
43108                         visitSymbol(entity);
43109                     }
43110                 });
43111                 return false;
43112             }
43113         }
43114     }
43115     ts.createGetSymbolWalker = createGetSymbolWalker;
43116 })(ts || (ts = {}));
43117 /* @internal */
43118 var ts;
43119 (function (ts) {
43120     var ambientModuleSymbolRegex = /^".+"$/;
43121     var anon = "(anonymous)";
43122     var nextSymbolId = 1;
43123     var nextNodeId = 1;
43124     var nextMergeId = 1;
43125     var nextFlowId = 1;
43126     var IterationUse;
43127     (function (IterationUse) {
43128         IterationUse[IterationUse["AllowsSyncIterablesFlag"] = 1] = "AllowsSyncIterablesFlag";
43129         IterationUse[IterationUse["AllowsAsyncIterablesFlag"] = 2] = "AllowsAsyncIterablesFlag";
43130         IterationUse[IterationUse["AllowsStringInputFlag"] = 4] = "AllowsStringInputFlag";
43131         IterationUse[IterationUse["ForOfFlag"] = 8] = "ForOfFlag";
43132         IterationUse[IterationUse["YieldStarFlag"] = 16] = "YieldStarFlag";
43133         IterationUse[IterationUse["SpreadFlag"] = 32] = "SpreadFlag";
43134         IterationUse[IterationUse["DestructuringFlag"] = 64] = "DestructuringFlag";
43135         IterationUse[IterationUse["PossiblyOutOfBounds"] = 128] = "PossiblyOutOfBounds";
43136         // Spread, Destructuring, Array element assignment
43137         IterationUse[IterationUse["Element"] = 1] = "Element";
43138         IterationUse[IterationUse["Spread"] = 33] = "Spread";
43139         IterationUse[IterationUse["Destructuring"] = 65] = "Destructuring";
43140         IterationUse[IterationUse["ForOf"] = 13] = "ForOf";
43141         IterationUse[IterationUse["ForAwaitOf"] = 15] = "ForAwaitOf";
43142         IterationUse[IterationUse["YieldStar"] = 17] = "YieldStar";
43143         IterationUse[IterationUse["AsyncYieldStar"] = 19] = "AsyncYieldStar";
43144         IterationUse[IterationUse["GeneratorReturnType"] = 1] = "GeneratorReturnType";
43145         IterationUse[IterationUse["AsyncGeneratorReturnType"] = 2] = "AsyncGeneratorReturnType";
43146     })(IterationUse || (IterationUse = {}));
43147     var IterationTypeKind;
43148     (function (IterationTypeKind) {
43149         IterationTypeKind[IterationTypeKind["Yield"] = 0] = "Yield";
43150         IterationTypeKind[IterationTypeKind["Return"] = 1] = "Return";
43151         IterationTypeKind[IterationTypeKind["Next"] = 2] = "Next";
43152     })(IterationTypeKind || (IterationTypeKind = {}));
43153     var WideningKind;
43154     (function (WideningKind) {
43155         WideningKind[WideningKind["Normal"] = 0] = "Normal";
43156         WideningKind[WideningKind["FunctionReturn"] = 1] = "FunctionReturn";
43157         WideningKind[WideningKind["GeneratorNext"] = 2] = "GeneratorNext";
43158         WideningKind[WideningKind["GeneratorYield"] = 3] = "GeneratorYield";
43159     })(WideningKind || (WideningKind = {}));
43160     var TypeFacts;
43161     (function (TypeFacts) {
43162         TypeFacts[TypeFacts["None"] = 0] = "None";
43163         TypeFacts[TypeFacts["TypeofEQString"] = 1] = "TypeofEQString";
43164         TypeFacts[TypeFacts["TypeofEQNumber"] = 2] = "TypeofEQNumber";
43165         TypeFacts[TypeFacts["TypeofEQBigInt"] = 4] = "TypeofEQBigInt";
43166         TypeFacts[TypeFacts["TypeofEQBoolean"] = 8] = "TypeofEQBoolean";
43167         TypeFacts[TypeFacts["TypeofEQSymbol"] = 16] = "TypeofEQSymbol";
43168         TypeFacts[TypeFacts["TypeofEQObject"] = 32] = "TypeofEQObject";
43169         TypeFacts[TypeFacts["TypeofEQFunction"] = 64] = "TypeofEQFunction";
43170         TypeFacts[TypeFacts["TypeofEQHostObject"] = 128] = "TypeofEQHostObject";
43171         TypeFacts[TypeFacts["TypeofNEString"] = 256] = "TypeofNEString";
43172         TypeFacts[TypeFacts["TypeofNENumber"] = 512] = "TypeofNENumber";
43173         TypeFacts[TypeFacts["TypeofNEBigInt"] = 1024] = "TypeofNEBigInt";
43174         TypeFacts[TypeFacts["TypeofNEBoolean"] = 2048] = "TypeofNEBoolean";
43175         TypeFacts[TypeFacts["TypeofNESymbol"] = 4096] = "TypeofNESymbol";
43176         TypeFacts[TypeFacts["TypeofNEObject"] = 8192] = "TypeofNEObject";
43177         TypeFacts[TypeFacts["TypeofNEFunction"] = 16384] = "TypeofNEFunction";
43178         TypeFacts[TypeFacts["TypeofNEHostObject"] = 32768] = "TypeofNEHostObject";
43179         TypeFacts[TypeFacts["EQUndefined"] = 65536] = "EQUndefined";
43180         TypeFacts[TypeFacts["EQNull"] = 131072] = "EQNull";
43181         TypeFacts[TypeFacts["EQUndefinedOrNull"] = 262144] = "EQUndefinedOrNull";
43182         TypeFacts[TypeFacts["NEUndefined"] = 524288] = "NEUndefined";
43183         TypeFacts[TypeFacts["NENull"] = 1048576] = "NENull";
43184         TypeFacts[TypeFacts["NEUndefinedOrNull"] = 2097152] = "NEUndefinedOrNull";
43185         TypeFacts[TypeFacts["Truthy"] = 4194304] = "Truthy";
43186         TypeFacts[TypeFacts["Falsy"] = 8388608] = "Falsy";
43187         TypeFacts[TypeFacts["All"] = 16777215] = "All";
43188         // The following members encode facts about particular kinds of types for use in the getTypeFacts function.
43189         // The presence of a particular fact means that the given test is true for some (and possibly all) values
43190         // of that kind of type.
43191         TypeFacts[TypeFacts["BaseStringStrictFacts"] = 3735041] = "BaseStringStrictFacts";
43192         TypeFacts[TypeFacts["BaseStringFacts"] = 12582401] = "BaseStringFacts";
43193         TypeFacts[TypeFacts["StringStrictFacts"] = 16317953] = "StringStrictFacts";
43194         TypeFacts[TypeFacts["StringFacts"] = 16776705] = "StringFacts";
43195         TypeFacts[TypeFacts["EmptyStringStrictFacts"] = 12123649] = "EmptyStringStrictFacts";
43196         TypeFacts[TypeFacts["EmptyStringFacts"] = 12582401] = "EmptyStringFacts";
43197         TypeFacts[TypeFacts["NonEmptyStringStrictFacts"] = 7929345] = "NonEmptyStringStrictFacts";
43198         TypeFacts[TypeFacts["NonEmptyStringFacts"] = 16776705] = "NonEmptyStringFacts";
43199         TypeFacts[TypeFacts["BaseNumberStrictFacts"] = 3734786] = "BaseNumberStrictFacts";
43200         TypeFacts[TypeFacts["BaseNumberFacts"] = 12582146] = "BaseNumberFacts";
43201         TypeFacts[TypeFacts["NumberStrictFacts"] = 16317698] = "NumberStrictFacts";
43202         TypeFacts[TypeFacts["NumberFacts"] = 16776450] = "NumberFacts";
43203         TypeFacts[TypeFacts["ZeroNumberStrictFacts"] = 12123394] = "ZeroNumberStrictFacts";
43204         TypeFacts[TypeFacts["ZeroNumberFacts"] = 12582146] = "ZeroNumberFacts";
43205         TypeFacts[TypeFacts["NonZeroNumberStrictFacts"] = 7929090] = "NonZeroNumberStrictFacts";
43206         TypeFacts[TypeFacts["NonZeroNumberFacts"] = 16776450] = "NonZeroNumberFacts";
43207         TypeFacts[TypeFacts["BaseBigIntStrictFacts"] = 3734276] = "BaseBigIntStrictFacts";
43208         TypeFacts[TypeFacts["BaseBigIntFacts"] = 12581636] = "BaseBigIntFacts";
43209         TypeFacts[TypeFacts["BigIntStrictFacts"] = 16317188] = "BigIntStrictFacts";
43210         TypeFacts[TypeFacts["BigIntFacts"] = 16775940] = "BigIntFacts";
43211         TypeFacts[TypeFacts["ZeroBigIntStrictFacts"] = 12122884] = "ZeroBigIntStrictFacts";
43212         TypeFacts[TypeFacts["ZeroBigIntFacts"] = 12581636] = "ZeroBigIntFacts";
43213         TypeFacts[TypeFacts["NonZeroBigIntStrictFacts"] = 7928580] = "NonZeroBigIntStrictFacts";
43214         TypeFacts[TypeFacts["NonZeroBigIntFacts"] = 16775940] = "NonZeroBigIntFacts";
43215         TypeFacts[TypeFacts["BaseBooleanStrictFacts"] = 3733256] = "BaseBooleanStrictFacts";
43216         TypeFacts[TypeFacts["BaseBooleanFacts"] = 12580616] = "BaseBooleanFacts";
43217         TypeFacts[TypeFacts["BooleanStrictFacts"] = 16316168] = "BooleanStrictFacts";
43218         TypeFacts[TypeFacts["BooleanFacts"] = 16774920] = "BooleanFacts";
43219         TypeFacts[TypeFacts["FalseStrictFacts"] = 12121864] = "FalseStrictFacts";
43220         TypeFacts[TypeFacts["FalseFacts"] = 12580616] = "FalseFacts";
43221         TypeFacts[TypeFacts["TrueStrictFacts"] = 7927560] = "TrueStrictFacts";
43222         TypeFacts[TypeFacts["TrueFacts"] = 16774920] = "TrueFacts";
43223         TypeFacts[TypeFacts["SymbolStrictFacts"] = 7925520] = "SymbolStrictFacts";
43224         TypeFacts[TypeFacts["SymbolFacts"] = 16772880] = "SymbolFacts";
43225         TypeFacts[TypeFacts["ObjectStrictFacts"] = 7888800] = "ObjectStrictFacts";
43226         TypeFacts[TypeFacts["ObjectFacts"] = 16736160] = "ObjectFacts";
43227         TypeFacts[TypeFacts["FunctionStrictFacts"] = 7880640] = "FunctionStrictFacts";
43228         TypeFacts[TypeFacts["FunctionFacts"] = 16728000] = "FunctionFacts";
43229         TypeFacts[TypeFacts["UndefinedFacts"] = 9830144] = "UndefinedFacts";
43230         TypeFacts[TypeFacts["NullFacts"] = 9363232] = "NullFacts";
43231         TypeFacts[TypeFacts["EmptyObjectStrictFacts"] = 16318463] = "EmptyObjectStrictFacts";
43232         TypeFacts[TypeFacts["AllTypeofNE"] = 556800] = "AllTypeofNE";
43233         TypeFacts[TypeFacts["EmptyObjectFacts"] = 16777215] = "EmptyObjectFacts";
43234     })(TypeFacts || (TypeFacts = {}));
43235     var typeofEQFacts = new ts.Map(ts.getEntries({
43236         string: 1 /* TypeofEQString */,
43237         number: 2 /* TypeofEQNumber */,
43238         bigint: 4 /* TypeofEQBigInt */,
43239         boolean: 8 /* TypeofEQBoolean */,
43240         symbol: 16 /* TypeofEQSymbol */,
43241         undefined: 65536 /* EQUndefined */,
43242         object: 32 /* TypeofEQObject */,
43243         function: 64 /* TypeofEQFunction */
43244     }));
43245     var typeofNEFacts = new ts.Map(ts.getEntries({
43246         string: 256 /* TypeofNEString */,
43247         number: 512 /* TypeofNENumber */,
43248         bigint: 1024 /* TypeofNEBigInt */,
43249         boolean: 2048 /* TypeofNEBoolean */,
43250         symbol: 4096 /* TypeofNESymbol */,
43251         undefined: 524288 /* NEUndefined */,
43252         object: 8192 /* TypeofNEObject */,
43253         function: 16384 /* TypeofNEFunction */
43254     }));
43255     var TypeSystemPropertyName;
43256     (function (TypeSystemPropertyName) {
43257         TypeSystemPropertyName[TypeSystemPropertyName["Type"] = 0] = "Type";
43258         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseConstructorType"] = 1] = "ResolvedBaseConstructorType";
43259         TypeSystemPropertyName[TypeSystemPropertyName["DeclaredType"] = 2] = "DeclaredType";
43260         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedReturnType"] = 3] = "ResolvedReturnType";
43261         TypeSystemPropertyName[TypeSystemPropertyName["ImmediateBaseConstraint"] = 4] = "ImmediateBaseConstraint";
43262         TypeSystemPropertyName[TypeSystemPropertyName["EnumTagType"] = 5] = "EnumTagType";
43263         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedTypeArguments"] = 6] = "ResolvedTypeArguments";
43264         TypeSystemPropertyName[TypeSystemPropertyName["ResolvedBaseTypes"] = 7] = "ResolvedBaseTypes";
43265     })(TypeSystemPropertyName || (TypeSystemPropertyName = {}));
43266     var CheckMode;
43267     (function (CheckMode) {
43268         CheckMode[CheckMode["Normal"] = 0] = "Normal";
43269         CheckMode[CheckMode["Contextual"] = 1] = "Contextual";
43270         CheckMode[CheckMode["Inferential"] = 2] = "Inferential";
43271         CheckMode[CheckMode["SkipContextSensitive"] = 4] = "SkipContextSensitive";
43272         CheckMode[CheckMode["SkipGenericFunctions"] = 8] = "SkipGenericFunctions";
43273         CheckMode[CheckMode["IsForSignatureHelp"] = 16] = "IsForSignatureHelp";
43274     })(CheckMode || (CheckMode = {}));
43275     var AccessFlags;
43276     (function (AccessFlags) {
43277         AccessFlags[AccessFlags["None"] = 0] = "None";
43278         AccessFlags[AccessFlags["NoIndexSignatures"] = 1] = "NoIndexSignatures";
43279         AccessFlags[AccessFlags["Writing"] = 2] = "Writing";
43280         AccessFlags[AccessFlags["CacheSymbol"] = 4] = "CacheSymbol";
43281         AccessFlags[AccessFlags["NoTupleBoundsCheck"] = 8] = "NoTupleBoundsCheck";
43282         AccessFlags[AccessFlags["ExpressionPosition"] = 16] = "ExpressionPosition";
43283     })(AccessFlags || (AccessFlags = {}));
43284     var SignatureCheckMode;
43285     (function (SignatureCheckMode) {
43286         SignatureCheckMode[SignatureCheckMode["BivariantCallback"] = 1] = "BivariantCallback";
43287         SignatureCheckMode[SignatureCheckMode["StrictCallback"] = 2] = "StrictCallback";
43288         SignatureCheckMode[SignatureCheckMode["IgnoreReturnTypes"] = 4] = "IgnoreReturnTypes";
43289         SignatureCheckMode[SignatureCheckMode["StrictArity"] = 8] = "StrictArity";
43290         SignatureCheckMode[SignatureCheckMode["Callback"] = 3] = "Callback";
43291     })(SignatureCheckMode || (SignatureCheckMode = {}));
43292     var IntersectionState;
43293     (function (IntersectionState) {
43294         IntersectionState[IntersectionState["None"] = 0] = "None";
43295         IntersectionState[IntersectionState["Source"] = 1] = "Source";
43296         IntersectionState[IntersectionState["Target"] = 2] = "Target";
43297         IntersectionState[IntersectionState["PropertyCheck"] = 4] = "PropertyCheck";
43298         IntersectionState[IntersectionState["InPropertyCheck"] = 8] = "InPropertyCheck";
43299     })(IntersectionState || (IntersectionState = {}));
43300     var MappedTypeModifiers;
43301     (function (MappedTypeModifiers) {
43302         MappedTypeModifiers[MappedTypeModifiers["IncludeReadonly"] = 1] = "IncludeReadonly";
43303         MappedTypeModifiers[MappedTypeModifiers["ExcludeReadonly"] = 2] = "ExcludeReadonly";
43304         MappedTypeModifiers[MappedTypeModifiers["IncludeOptional"] = 4] = "IncludeOptional";
43305         MappedTypeModifiers[MappedTypeModifiers["ExcludeOptional"] = 8] = "ExcludeOptional";
43306     })(MappedTypeModifiers || (MappedTypeModifiers = {}));
43307     var ExpandingFlags;
43308     (function (ExpandingFlags) {
43309         ExpandingFlags[ExpandingFlags["None"] = 0] = "None";
43310         ExpandingFlags[ExpandingFlags["Source"] = 1] = "Source";
43311         ExpandingFlags[ExpandingFlags["Target"] = 2] = "Target";
43312         ExpandingFlags[ExpandingFlags["Both"] = 3] = "Both";
43313     })(ExpandingFlags || (ExpandingFlags = {}));
43314     var MembersOrExportsResolutionKind;
43315     (function (MembersOrExportsResolutionKind) {
43316         MembersOrExportsResolutionKind["resolvedExports"] = "resolvedExports";
43317         MembersOrExportsResolutionKind["resolvedMembers"] = "resolvedMembers";
43318     })(MembersOrExportsResolutionKind || (MembersOrExportsResolutionKind = {}));
43319     var UnusedKind;
43320     (function (UnusedKind) {
43321         UnusedKind[UnusedKind["Local"] = 0] = "Local";
43322         UnusedKind[UnusedKind["Parameter"] = 1] = "Parameter";
43323     })(UnusedKind || (UnusedKind = {}));
43324     var isNotOverloadAndNotAccessor = ts.and(isNotOverload, isNotAccessor);
43325     var DeclarationMeaning;
43326     (function (DeclarationMeaning) {
43327         DeclarationMeaning[DeclarationMeaning["GetAccessor"] = 1] = "GetAccessor";
43328         DeclarationMeaning[DeclarationMeaning["SetAccessor"] = 2] = "SetAccessor";
43329         DeclarationMeaning[DeclarationMeaning["PropertyAssignment"] = 4] = "PropertyAssignment";
43330         DeclarationMeaning[DeclarationMeaning["Method"] = 8] = "Method";
43331         DeclarationMeaning[DeclarationMeaning["GetOrSetAccessor"] = 3] = "GetOrSetAccessor";
43332         DeclarationMeaning[DeclarationMeaning["PropertyAssignmentOrMethod"] = 12] = "PropertyAssignmentOrMethod";
43333     })(DeclarationMeaning || (DeclarationMeaning = {}));
43334     var DeclarationSpaces;
43335     (function (DeclarationSpaces) {
43336         DeclarationSpaces[DeclarationSpaces["None"] = 0] = "None";
43337         DeclarationSpaces[DeclarationSpaces["ExportValue"] = 1] = "ExportValue";
43338         DeclarationSpaces[DeclarationSpaces["ExportType"] = 2] = "ExportType";
43339         DeclarationSpaces[DeclarationSpaces["ExportNamespace"] = 4] = "ExportNamespace";
43340     })(DeclarationSpaces || (DeclarationSpaces = {}));
43341     var MinArgumentCountFlags;
43342     (function (MinArgumentCountFlags) {
43343         MinArgumentCountFlags[MinArgumentCountFlags["None"] = 0] = "None";
43344         MinArgumentCountFlags[MinArgumentCountFlags["StrongArityForUntypedJS"] = 1] = "StrongArityForUntypedJS";
43345         MinArgumentCountFlags[MinArgumentCountFlags["VoidIsNonOptional"] = 2] = "VoidIsNonOptional";
43346     })(MinArgumentCountFlags || (MinArgumentCountFlags = {}));
43347     var IntrinsicTypeKind;
43348     (function (IntrinsicTypeKind) {
43349         IntrinsicTypeKind[IntrinsicTypeKind["Uppercase"] = 0] = "Uppercase";
43350         IntrinsicTypeKind[IntrinsicTypeKind["Lowercase"] = 1] = "Lowercase";
43351         IntrinsicTypeKind[IntrinsicTypeKind["Capitalize"] = 2] = "Capitalize";
43352         IntrinsicTypeKind[IntrinsicTypeKind["Uncapitalize"] = 3] = "Uncapitalize";
43353     })(IntrinsicTypeKind || (IntrinsicTypeKind = {}));
43354     var intrinsicTypeKinds = new ts.Map(ts.getEntries({
43355         Uppercase: 0 /* Uppercase */,
43356         Lowercase: 1 /* Lowercase */,
43357         Capitalize: 2 /* Capitalize */,
43358         Uncapitalize: 3 /* Uncapitalize */
43359     }));
43360     function SymbolLinks() {
43361     }
43362     function NodeLinks() {
43363         this.flags = 0;
43364     }
43365     function getNodeId(node) {
43366         if (!node.id) {
43367             node.id = nextNodeId;
43368             nextNodeId++;
43369         }
43370         return node.id;
43371     }
43372     ts.getNodeId = getNodeId;
43373     function getSymbolId(symbol) {
43374         if (!symbol.id) {
43375             symbol.id = nextSymbolId;
43376             nextSymbolId++;
43377         }
43378         return symbol.id;
43379     }
43380     ts.getSymbolId = getSymbolId;
43381     function isInstantiatedModule(node, preserveConstEnums) {
43382         var moduleState = ts.getModuleInstanceState(node);
43383         return moduleState === 1 /* Instantiated */ ||
43384             (preserveConstEnums && moduleState === 2 /* ConstEnumOnly */);
43385     }
43386     ts.isInstantiatedModule = isInstantiatedModule;
43387     function createTypeChecker(host, produceDiagnostics) {
43388         var getPackagesSet = ts.memoize(function () {
43389             var set = new ts.Set();
43390             host.getSourceFiles().forEach(function (sf) {
43391                 if (!sf.resolvedModules)
43392                     return;
43393                 ts.forEachEntry(sf.resolvedModules, function (r) {
43394                     if (r && r.packageId)
43395                         set.add(r.packageId.name);
43396                 });
43397             });
43398             return set;
43399         });
43400         // Cancellation that controls whether or not we can cancel in the middle of type checking.
43401         // In general cancelling is *not* safe for the type checker.  We might be in the middle of
43402         // computing something, and we will leave our internals in an inconsistent state.  Callers
43403         // who set the cancellation token should catch if a cancellation exception occurs, and
43404         // should throw away and create a new TypeChecker.
43405         //
43406         // Currently we only support setting the cancellation token when getting diagnostics.  This
43407         // is because diagnostics can be quite expensive, and we want to allow hosts to bail out if
43408         // they no longer need the information (for example, if the user started editing again).
43409         var cancellationToken;
43410         var requestedExternalEmitHelpers;
43411         var externalHelpersModule;
43412         var Symbol = ts.objectAllocator.getSymbolConstructor();
43413         var Type = ts.objectAllocator.getTypeConstructor();
43414         var Signature = ts.objectAllocator.getSignatureConstructor();
43415         var typeCount = 0;
43416         var symbolCount = 0;
43417         var enumCount = 0;
43418         var totalInstantiationCount = 0;
43419         var instantiationCount = 0;
43420         var instantiationDepth = 0;
43421         var constraintDepth = 0;
43422         var currentNode;
43423         var typeCatalog = []; // NB: id is index + 1
43424         var emptySymbols = ts.createSymbolTable();
43425         var arrayVariances = [1 /* Covariant */];
43426         var compilerOptions = host.getCompilerOptions();
43427         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
43428         var moduleKind = ts.getEmitModuleKind(compilerOptions);
43429         var allowSyntheticDefaultImports = ts.getAllowSyntheticDefaultImports(compilerOptions);
43430         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
43431         var strictFunctionTypes = ts.getStrictOptionValue(compilerOptions, "strictFunctionTypes");
43432         var strictBindCallApply = ts.getStrictOptionValue(compilerOptions, "strictBindCallApply");
43433         var strictPropertyInitialization = ts.getStrictOptionValue(compilerOptions, "strictPropertyInitialization");
43434         var noImplicitAny = ts.getStrictOptionValue(compilerOptions, "noImplicitAny");
43435         var noImplicitThis = ts.getStrictOptionValue(compilerOptions, "noImplicitThis");
43436         var keyofStringsOnly = !!compilerOptions.keyofStringsOnly;
43437         var freshObjectLiteralFlag = compilerOptions.suppressExcessPropertyErrors ? 0 : 32768 /* FreshLiteral */;
43438         var emitResolver = createResolver();
43439         var nodeBuilder = createNodeBuilder();
43440         var globals = ts.createSymbolTable();
43441         var undefinedSymbol = createSymbol(4 /* Property */, "undefined");
43442         undefinedSymbol.declarations = [];
43443         var globalThisSymbol = createSymbol(1536 /* Module */, "globalThis", 8 /* Readonly */);
43444         globalThisSymbol.exports = globals;
43445         globalThisSymbol.declarations = [];
43446         globals.set(globalThisSymbol.escapedName, globalThisSymbol);
43447         var argumentsSymbol = createSymbol(4 /* Property */, "arguments");
43448         var requireSymbol = createSymbol(4 /* Property */, "require");
43449         /** This will be set during calls to `getResolvedSignature` where services determines an apparent number of arguments greater than what is actually provided. */
43450         var apparentArgumentCount;
43451         // for public members that accept a Node or one of its subtypes, we must guard against
43452         // synthetic nodes created during transformations by calling `getParseTreeNode`.
43453         // for most of these, we perform the guard only on `checker` to avoid any possible
43454         // extra cost of calling `getParseTreeNode` when calling these functions from inside the
43455         // checker.
43456         var checker = {
43457             getNodeCount: function () { return ts.sum(host.getSourceFiles(), "nodeCount"); },
43458             getIdentifierCount: function () { return ts.sum(host.getSourceFiles(), "identifierCount"); },
43459             getSymbolCount: function () { return ts.sum(host.getSourceFiles(), "symbolCount") + symbolCount; },
43460             getTypeCatalog: function () { return typeCatalog; },
43461             getTypeCount: function () { return typeCount; },
43462             getInstantiationCount: function () { return totalInstantiationCount; },
43463             getRelationCacheSizes: function () { return ({
43464                 assignable: assignableRelation.size,
43465                 identity: identityRelation.size,
43466                 subtype: subtypeRelation.size,
43467                 strictSubtype: strictSubtypeRelation.size,
43468             }); },
43469             isUndefinedSymbol: function (symbol) { return symbol === undefinedSymbol; },
43470             isArgumentsSymbol: function (symbol) { return symbol === argumentsSymbol; },
43471             isUnknownSymbol: function (symbol) { return symbol === unknownSymbol; },
43472             getMergedSymbol: getMergedSymbol,
43473             getDiagnostics: getDiagnostics,
43474             getGlobalDiagnostics: getGlobalDiagnostics,
43475             getRecursionIdentity: getRecursionIdentity,
43476             getTypeOfSymbolAtLocation: function (symbol, locationIn) {
43477                 var location = ts.getParseTreeNode(locationIn);
43478                 return location ? getTypeOfSymbolAtLocation(symbol, location) : errorType;
43479             },
43480             getSymbolsOfParameterPropertyDeclaration: function (parameterIn, parameterName) {
43481                 var parameter = ts.getParseTreeNode(parameterIn, ts.isParameter);
43482                 if (parameter === undefined)
43483                     return ts.Debug.fail("Cannot get symbols of a synthetic parameter that cannot be resolved to a parse-tree node.");
43484                 return getSymbolsOfParameterPropertyDeclaration(parameter, ts.escapeLeadingUnderscores(parameterName));
43485             },
43486             getDeclaredTypeOfSymbol: getDeclaredTypeOfSymbol,
43487             getPropertiesOfType: getPropertiesOfType,
43488             getPropertyOfType: function (type, name) { return getPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
43489             getPrivateIdentifierPropertyOfType: function (leftType, name, location) {
43490                 var node = ts.getParseTreeNode(location);
43491                 if (!node) {
43492                     return undefined;
43493                 }
43494                 var propName = ts.escapeLeadingUnderscores(name);
43495                 var lexicallyScopedIdentifier = lookupSymbolForPrivateIdentifierDeclaration(propName, node);
43496                 return lexicallyScopedIdentifier ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) : undefined;
43497             },
43498             getTypeOfPropertyOfType: function (type, name) { return getTypeOfPropertyOfType(type, ts.escapeLeadingUnderscores(name)); },
43499             getIndexInfoOfType: getIndexInfoOfType,
43500             getSignaturesOfType: getSignaturesOfType,
43501             getIndexTypeOfType: getIndexTypeOfType,
43502             getBaseTypes: getBaseTypes,
43503             getBaseTypeOfLiteralType: getBaseTypeOfLiteralType,
43504             getWidenedType: getWidenedType,
43505             getTypeFromTypeNode: function (nodeIn) {
43506                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
43507                 return node ? getTypeFromTypeNode(node) : errorType;
43508             },
43509             getParameterType: getTypeAtPosition,
43510             getPromisedTypeOfPromise: getPromisedTypeOfPromise,
43511             getAwaitedType: function (type) { return getAwaitedType(type); },
43512             getReturnTypeOfSignature: getReturnTypeOfSignature,
43513             isNullableType: isNullableType,
43514             getNullableType: getNullableType,
43515             getNonNullableType: getNonNullableType,
43516             getNonOptionalType: removeOptionalTypeMarker,
43517             getTypeArguments: getTypeArguments,
43518             typeToTypeNode: nodeBuilder.typeToTypeNode,
43519             indexInfoToIndexSignatureDeclaration: nodeBuilder.indexInfoToIndexSignatureDeclaration,
43520             signatureToSignatureDeclaration: nodeBuilder.signatureToSignatureDeclaration,
43521             symbolToEntityName: nodeBuilder.symbolToEntityName,
43522             symbolToExpression: nodeBuilder.symbolToExpression,
43523             symbolToTypeParameterDeclarations: nodeBuilder.symbolToTypeParameterDeclarations,
43524             symbolToParameterDeclaration: nodeBuilder.symbolToParameterDeclaration,
43525             typeParameterToDeclaration: nodeBuilder.typeParameterToDeclaration,
43526             getSymbolsInScope: function (locationIn, meaning) {
43527                 var location = ts.getParseTreeNode(locationIn);
43528                 return location ? getSymbolsInScope(location, meaning) : [];
43529             },
43530             getSymbolAtLocation: function (nodeIn) {
43531                 var node = ts.getParseTreeNode(nodeIn);
43532                 // set ignoreErrors: true because any lookups invoked by the API shouldn't cause any new errors
43533                 return node ? getSymbolAtLocation(node, /*ignoreErrors*/ true) : undefined;
43534             },
43535             getShorthandAssignmentValueSymbol: function (nodeIn) {
43536                 var node = ts.getParseTreeNode(nodeIn);
43537                 return node ? getShorthandAssignmentValueSymbol(node) : undefined;
43538             },
43539             getExportSpecifierLocalTargetSymbol: function (nodeIn) {
43540                 var node = ts.getParseTreeNode(nodeIn, ts.isExportSpecifier);
43541                 return node ? getExportSpecifierLocalTargetSymbol(node) : undefined;
43542             },
43543             getExportSymbolOfSymbol: function (symbol) {
43544                 return getMergedSymbol(symbol.exportSymbol || symbol);
43545             },
43546             getTypeAtLocation: function (nodeIn) {
43547                 var node = ts.getParseTreeNode(nodeIn);
43548                 return node ? getTypeOfNode(node) : errorType;
43549             },
43550             getTypeOfAssignmentPattern: function (nodeIn) {
43551                 var node = ts.getParseTreeNode(nodeIn, ts.isAssignmentPattern);
43552                 return node && getTypeOfAssignmentPattern(node) || errorType;
43553             },
43554             getPropertySymbolOfDestructuringAssignment: function (locationIn) {
43555                 var location = ts.getParseTreeNode(locationIn, ts.isIdentifier);
43556                 return location ? getPropertySymbolOfDestructuringAssignment(location) : undefined;
43557             },
43558             signatureToString: function (signature, enclosingDeclaration, flags, kind) {
43559                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind);
43560             },
43561             typeToString: function (type, enclosingDeclaration, flags) {
43562                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags);
43563             },
43564             symbolToString: function (symbol, enclosingDeclaration, meaning, flags) {
43565                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags);
43566             },
43567             typePredicateToString: function (predicate, enclosingDeclaration, flags) {
43568                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags);
43569             },
43570             writeSignature: function (signature, enclosingDeclaration, flags, kind, writer) {
43571                 return signatureToString(signature, ts.getParseTreeNode(enclosingDeclaration), flags, kind, writer);
43572             },
43573             writeType: function (type, enclosingDeclaration, flags, writer) {
43574                 return typeToString(type, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
43575             },
43576             writeSymbol: function (symbol, enclosingDeclaration, meaning, flags, writer) {
43577                 return symbolToString(symbol, ts.getParseTreeNode(enclosingDeclaration), meaning, flags, writer);
43578             },
43579             writeTypePredicate: function (predicate, enclosingDeclaration, flags, writer) {
43580                 return typePredicateToString(predicate, ts.getParseTreeNode(enclosingDeclaration), flags, writer);
43581             },
43582             getAugmentedPropertiesOfType: getAugmentedPropertiesOfType,
43583             getRootSymbols: getRootSymbols,
43584             getSymbolOfExpando: getSymbolOfExpando,
43585             getContextualType: function (nodeIn, contextFlags) {
43586                 var node = ts.getParseTreeNode(nodeIn, ts.isExpression);
43587                 if (!node) {
43588                     return undefined;
43589                 }
43590                 var containingCall = ts.findAncestor(node, ts.isCallLikeExpression);
43591                 var containingCallResolvedSignature = containingCall && getNodeLinks(containingCall).resolvedSignature;
43592                 if (contextFlags & 4 /* Completions */ && containingCall) {
43593                     var toMarkSkip = node;
43594                     do {
43595                         getNodeLinks(toMarkSkip).skipDirectInference = true;
43596                         toMarkSkip = toMarkSkip.parent;
43597                     } while (toMarkSkip && toMarkSkip !== containingCall);
43598                     getNodeLinks(containingCall).resolvedSignature = undefined;
43599                 }
43600                 var result = getContextualType(node, contextFlags);
43601                 if (contextFlags & 4 /* Completions */ && containingCall) {
43602                     var toMarkSkip = node;
43603                     do {
43604                         getNodeLinks(toMarkSkip).skipDirectInference = undefined;
43605                         toMarkSkip = toMarkSkip.parent;
43606                     } while (toMarkSkip && toMarkSkip !== containingCall);
43607                     getNodeLinks(containingCall).resolvedSignature = containingCallResolvedSignature;
43608                 }
43609                 return result;
43610             },
43611             getContextualTypeForObjectLiteralElement: function (nodeIn) {
43612                 var node = ts.getParseTreeNode(nodeIn, ts.isObjectLiteralElementLike);
43613                 return node ? getContextualTypeForObjectLiteralElement(node) : undefined;
43614             },
43615             getContextualTypeForArgumentAtIndex: function (nodeIn, argIndex) {
43616                 var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
43617                 return node && getContextualTypeForArgumentAtIndex(node, argIndex);
43618             },
43619             getContextualTypeForJsxAttribute: function (nodeIn) {
43620                 var node = ts.getParseTreeNode(nodeIn, ts.isJsxAttributeLike);
43621                 return node && getContextualTypeForJsxAttribute(node);
43622             },
43623             isContextSensitive: isContextSensitive,
43624             getFullyQualifiedName: getFullyQualifiedName,
43625             getResolvedSignature: function (node, candidatesOutArray, argumentCount) {
43626                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 0 /* Normal */);
43627             },
43628             getResolvedSignatureForSignatureHelp: function (node, candidatesOutArray, argumentCount) {
43629                 return getResolvedSignatureWorker(node, candidatesOutArray, argumentCount, 16 /* IsForSignatureHelp */);
43630             },
43631             getExpandedParameters: getExpandedParameters,
43632             hasEffectiveRestParameter: hasEffectiveRestParameter,
43633             getConstantValue: function (nodeIn) {
43634                 var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
43635                 return node ? getConstantValue(node) : undefined;
43636             },
43637             isValidPropertyAccess: function (nodeIn, propertyName) {
43638                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessOrQualifiedNameOrImportTypeNode);
43639                 return !!node && isValidPropertyAccess(node, ts.escapeLeadingUnderscores(propertyName));
43640             },
43641             isValidPropertyAccessForCompletions: function (nodeIn, type, property) {
43642                 var node = ts.getParseTreeNode(nodeIn, ts.isPropertyAccessExpression);
43643                 return !!node && isValidPropertyAccessForCompletions(node, type, property);
43644             },
43645             getSignatureFromDeclaration: function (declarationIn) {
43646                 var declaration = ts.getParseTreeNode(declarationIn, ts.isFunctionLike);
43647                 return declaration ? getSignatureFromDeclaration(declaration) : undefined;
43648             },
43649             isImplementationOfOverload: function (nodeIn) {
43650                 var node = ts.getParseTreeNode(nodeIn, ts.isFunctionLike);
43651                 return node ? isImplementationOfOverload(node) : undefined;
43652             },
43653             getImmediateAliasedSymbol: getImmediateAliasedSymbol,
43654             getAliasedSymbol: resolveAlias,
43655             getEmitResolver: getEmitResolver,
43656             getExportsOfModule: getExportsOfModuleAsArray,
43657             getExportsAndPropertiesOfModule: getExportsAndPropertiesOfModule,
43658             getSymbolWalker: ts.createGetSymbolWalker(getRestTypeOfSignature, getTypePredicateOfSignature, getReturnTypeOfSignature, getBaseTypes, resolveStructuredTypeMembers, getTypeOfSymbol, getResolvedSymbol, getIndexTypeOfStructuredType, getConstraintOfTypeParameter, ts.getFirstIdentifier, getTypeArguments),
43659             getAmbientModules: getAmbientModules,
43660             getJsxIntrinsicTagNamesAt: getJsxIntrinsicTagNamesAt,
43661             isOptionalParameter: function (nodeIn) {
43662                 var node = ts.getParseTreeNode(nodeIn, ts.isParameter);
43663                 return node ? isOptionalParameter(node) : false;
43664             },
43665             tryGetMemberInModuleExports: function (name, symbol) { return tryGetMemberInModuleExports(ts.escapeLeadingUnderscores(name), symbol); },
43666             tryGetMemberInModuleExportsAndProperties: function (name, symbol) { return tryGetMemberInModuleExportsAndProperties(ts.escapeLeadingUnderscores(name), symbol); },
43667             tryFindAmbientModuleWithoutAugmentations: function (moduleName) {
43668                 // we deliberately exclude augmentations
43669                 // since we are only interested in declarations of the module itself
43670                 return tryFindAmbientModule(moduleName, /*withAugmentations*/ false);
43671             },
43672             getApparentType: getApparentType,
43673             getUnionType: getUnionType,
43674             isTypeAssignableTo: isTypeAssignableTo,
43675             createAnonymousType: createAnonymousType,
43676             createSignature: createSignature,
43677             createSymbol: createSymbol,
43678             createIndexInfo: createIndexInfo,
43679             getAnyType: function () { return anyType; },
43680             getStringType: function () { return stringType; },
43681             getNumberType: function () { return numberType; },
43682             createPromiseType: createPromiseType,
43683             createArrayType: createArrayType,
43684             getElementTypeOfArrayType: getElementTypeOfArrayType,
43685             getBooleanType: function () { return booleanType; },
43686             getFalseType: function (fresh) { return fresh ? falseType : regularFalseType; },
43687             getTrueType: function (fresh) { return fresh ? trueType : regularTrueType; },
43688             getVoidType: function () { return voidType; },
43689             getUndefinedType: function () { return undefinedType; },
43690             getNullType: function () { return nullType; },
43691             getESSymbolType: function () { return esSymbolType; },
43692             getNeverType: function () { return neverType; },
43693             getOptionalType: function () { return optionalType; },
43694             isSymbolAccessible: isSymbolAccessible,
43695             isArrayType: isArrayType,
43696             isTupleType: isTupleType,
43697             isArrayLikeType: isArrayLikeType,
43698             isTypeInvalidDueToUnionDiscriminant: isTypeInvalidDueToUnionDiscriminant,
43699             getAllPossiblePropertiesOfTypes: getAllPossiblePropertiesOfTypes,
43700             getSuggestedSymbolForNonexistentProperty: getSuggestedSymbolForNonexistentProperty,
43701             getSuggestionForNonexistentProperty: getSuggestionForNonexistentProperty,
43702             getSuggestedSymbolForNonexistentJSXAttribute: getSuggestedSymbolForNonexistentJSXAttribute,
43703             getSuggestedSymbolForNonexistentSymbol: function (location, name, meaning) { return getSuggestedSymbolForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
43704             getSuggestionForNonexistentSymbol: function (location, name, meaning) { return getSuggestionForNonexistentSymbol(location, ts.escapeLeadingUnderscores(name), meaning); },
43705             getSuggestedSymbolForNonexistentModule: getSuggestedSymbolForNonexistentModule,
43706             getSuggestionForNonexistentExport: getSuggestionForNonexistentExport,
43707             getBaseConstraintOfType: getBaseConstraintOfType,
43708             getDefaultFromTypeParameter: function (type) { return type && type.flags & 262144 /* TypeParameter */ ? getDefaultFromTypeParameter(type) : undefined; },
43709             resolveName: function (name, location, meaning, excludeGlobals) {
43710                 return resolveName(location, ts.escapeLeadingUnderscores(name), meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false, excludeGlobals);
43711             },
43712             getJsxNamespace: function (n) { return ts.unescapeLeadingUnderscores(getJsxNamespace(n)); },
43713             getAccessibleSymbolChain: getAccessibleSymbolChain,
43714             getTypePredicateOfSignature: getTypePredicateOfSignature,
43715             resolveExternalModuleName: function (moduleSpecifierIn) {
43716                 var moduleSpecifier = ts.getParseTreeNode(moduleSpecifierIn, ts.isExpression);
43717                 return moduleSpecifier && resolveExternalModuleName(moduleSpecifier, moduleSpecifier, /*ignoreErrors*/ true);
43718             },
43719             resolveExternalModuleSymbol: resolveExternalModuleSymbol,
43720             tryGetThisTypeAt: function (nodeIn, includeGlobalThis) {
43721                 var node = ts.getParseTreeNode(nodeIn);
43722                 return node && tryGetThisTypeAt(node, includeGlobalThis);
43723             },
43724             getTypeArgumentConstraint: function (nodeIn) {
43725                 var node = ts.getParseTreeNode(nodeIn, ts.isTypeNode);
43726                 return node && getTypeArgumentConstraint(node);
43727             },
43728             getSuggestionDiagnostics: function (fileIn, ct) {
43729                 var file = ts.getParseTreeNode(fileIn, ts.isSourceFile) || ts.Debug.fail("Could not determine parsed source file.");
43730                 if (ts.skipTypeChecking(file, compilerOptions, host)) {
43731                     return ts.emptyArray;
43732                 }
43733                 var diagnostics;
43734                 try {
43735                     // Record the cancellation token so it can be checked later on during checkSourceElement.
43736                     // Do this in a finally block so we can ensure that it gets reset back to nothing after
43737                     // this call is done.
43738                     cancellationToken = ct;
43739                     // Ensure file is type checked
43740                     checkSourceFile(file);
43741                     ts.Debug.assert(!!(getNodeLinks(file).flags & 1 /* TypeChecked */));
43742                     diagnostics = ts.addRange(diagnostics, suggestionDiagnostics.getDiagnostics(file.fileName));
43743                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(file), function (containingNode, kind, diag) {
43744                         if (!ts.containsParseError(containingNode) && !unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
43745                             (diagnostics || (diagnostics = [])).push(__assign(__assign({}, diag), { category: ts.DiagnosticCategory.Suggestion }));
43746                         }
43747                     });
43748                     return diagnostics || ts.emptyArray;
43749                 }
43750                 finally {
43751                     cancellationToken = undefined;
43752                 }
43753             },
43754             runWithCancellationToken: function (token, callback) {
43755                 try {
43756                     cancellationToken = token;
43757                     return callback(checker);
43758                 }
43759                 finally {
43760                     cancellationToken = undefined;
43761                 }
43762             },
43763             getLocalTypeParametersOfClassOrInterfaceOrTypeAlias: getLocalTypeParametersOfClassOrInterfaceOrTypeAlias,
43764             isDeclarationVisible: isDeclarationVisible,
43765         };
43766         function getResolvedSignatureWorker(nodeIn, candidatesOutArray, argumentCount, checkMode) {
43767             var node = ts.getParseTreeNode(nodeIn, ts.isCallLikeExpression);
43768             apparentArgumentCount = argumentCount;
43769             var res = node ? getResolvedSignature(node, candidatesOutArray, checkMode) : undefined;
43770             apparentArgumentCount = undefined;
43771             return res;
43772         }
43773         var tupleTypes = new ts.Map();
43774         var unionTypes = new ts.Map();
43775         var intersectionTypes = new ts.Map();
43776         var literalTypes = new ts.Map();
43777         var indexedAccessTypes = new ts.Map();
43778         var templateLiteralTypes = new ts.Map();
43779         var stringMappingTypes = new ts.Map();
43780         var substitutionTypes = new ts.Map();
43781         var evolvingArrayTypes = [];
43782         var undefinedProperties = new ts.Map();
43783         var unknownSymbol = createSymbol(4 /* Property */, "unknown");
43784         var resolvingSymbol = createSymbol(0, "__resolving__" /* Resolving */);
43785         var anyType = createIntrinsicType(1 /* Any */, "any");
43786         var autoType = createIntrinsicType(1 /* Any */, "any");
43787         var wildcardType = createIntrinsicType(1 /* Any */, "any");
43788         var errorType = createIntrinsicType(1 /* Any */, "error");
43789         var nonInferrableAnyType = createIntrinsicType(1 /* Any */, "any", 524288 /* ContainsWideningType */);
43790         var intrinsicMarkerType = createIntrinsicType(1 /* Any */, "intrinsic");
43791         var unknownType = createIntrinsicType(2 /* Unknown */, "unknown");
43792         var undefinedType = createIntrinsicType(32768 /* Undefined */, "undefined");
43793         var undefinedWideningType = strictNullChecks ? undefinedType : createIntrinsicType(32768 /* Undefined */, "undefined", 524288 /* ContainsWideningType */);
43794         var optionalType = createIntrinsicType(32768 /* Undefined */, "undefined");
43795         var nullType = createIntrinsicType(65536 /* Null */, "null");
43796         var nullWideningType = strictNullChecks ? nullType : createIntrinsicType(65536 /* Null */, "null", 524288 /* ContainsWideningType */);
43797         var stringType = createIntrinsicType(4 /* String */, "string");
43798         var numberType = createIntrinsicType(8 /* Number */, "number");
43799         var bigintType = createIntrinsicType(64 /* BigInt */, "bigint");
43800         var falseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
43801         var regularFalseType = createIntrinsicType(512 /* BooleanLiteral */, "false");
43802         var trueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
43803         var regularTrueType = createIntrinsicType(512 /* BooleanLiteral */, "true");
43804         trueType.regularType = regularTrueType;
43805         trueType.freshType = trueType;
43806         regularTrueType.regularType = regularTrueType;
43807         regularTrueType.freshType = trueType;
43808         falseType.regularType = regularFalseType;
43809         falseType.freshType = falseType;
43810         regularFalseType.regularType = regularFalseType;
43811         regularFalseType.freshType = falseType;
43812         var booleanType = createBooleanType([regularFalseType, regularTrueType]);
43813         // Also mark all combinations of fresh/regular booleans as "Boolean" so they print as `boolean` instead of `true | false`
43814         // (The union is cached, so simply doing the marking here is sufficient)
43815         createBooleanType([regularFalseType, trueType]);
43816         createBooleanType([falseType, regularTrueType]);
43817         createBooleanType([falseType, trueType]);
43818         var esSymbolType = createIntrinsicType(4096 /* ESSymbol */, "symbol");
43819         var voidType = createIntrinsicType(16384 /* Void */, "void");
43820         var neverType = createIntrinsicType(131072 /* Never */, "never");
43821         var silentNeverType = createIntrinsicType(131072 /* Never */, "never");
43822         var nonInferrableType = createIntrinsicType(131072 /* Never */, "never", 2097152 /* NonInferrableType */);
43823         var implicitNeverType = createIntrinsicType(131072 /* Never */, "never");
43824         var unreachableNeverType = createIntrinsicType(131072 /* Never */, "never");
43825         var nonPrimitiveType = createIntrinsicType(67108864 /* NonPrimitive */, "object");
43826         var stringNumberSymbolType = getUnionType([stringType, numberType, esSymbolType]);
43827         var keyofConstraintType = keyofStringsOnly ? stringType : stringNumberSymbolType;
43828         var numberOrBigIntType = getUnionType([numberType, bigintType]);
43829         var templateConstraintType = getUnionType([stringType, numberType, booleanType, bigintType, nullType, undefinedType]);
43830         var restrictiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? getRestrictiveTypeParameter(t) : t; });
43831         var permissiveMapper = makeFunctionTypeMapper(function (t) { return t.flags & 262144 /* TypeParameter */ ? wildcardType : t; });
43832         var emptyObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43833         var emptyJsxObjectType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43834         emptyJsxObjectType.objectFlags |= 4096 /* JsxAttributes */;
43835         var emptyTypeLiteralSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
43836         emptyTypeLiteralSymbol.members = ts.createSymbolTable();
43837         var emptyTypeLiteralType = createAnonymousType(emptyTypeLiteralSymbol, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43838         var emptyGenericType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43839         emptyGenericType.instantiations = new ts.Map();
43840         var anyFunctionType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43841         // The anyFunctionType contains the anyFunctionType by definition. The flag is further propagated
43842         // in getPropagatingFlagsOfTypes, and it is checked in inferFromTypes.
43843         anyFunctionType.objectFlags |= 2097152 /* NonInferrableType */;
43844         var noConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43845         var circularConstraintType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43846         var resolvingDefaultType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
43847         var markerSuperType = createTypeParameter();
43848         var markerSubType = createTypeParameter();
43849         markerSubType.constraint = markerSuperType;
43850         var markerOtherType = createTypeParameter();
43851         var noTypePredicate = createTypePredicate(1 /* Identifier */, "<<unresolved>>", 0, anyType);
43852         var anySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
43853         var unknownSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, errorType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
43854         var resolvingSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, anyType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
43855         var silentNeverSignature = createSignature(undefined, undefined, undefined, ts.emptyArray, silentNeverType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
43856         var enumNumberIndexInfo = createIndexInfo(stringType, /*isReadonly*/ true);
43857         var iterationTypesCache = new ts.Map(); // cache for common IterationTypes instances
43858         var noIterationTypes = {
43859             get yieldType() { return ts.Debug.fail("Not supported"); },
43860             get returnType() { return ts.Debug.fail("Not supported"); },
43861             get nextType() { return ts.Debug.fail("Not supported"); },
43862         };
43863         var anyIterationTypes = createIterationTypes(anyType, anyType, anyType);
43864         var anyIterationTypesExceptNext = createIterationTypes(anyType, anyType, unknownType);
43865         var defaultIterationTypes = createIterationTypes(neverType, anyType, undefinedType); // default iteration types for `Iterator`.
43866         var asyncIterationTypesResolver = {
43867             iterableCacheKey: "iterationTypesOfAsyncIterable",
43868             iteratorCacheKey: "iterationTypesOfAsyncIterator",
43869             iteratorSymbolName: "asyncIterator",
43870             getGlobalIteratorType: getGlobalAsyncIteratorType,
43871             getGlobalIterableType: getGlobalAsyncIterableType,
43872             getGlobalIterableIteratorType: getGlobalAsyncIterableIteratorType,
43873             getGlobalGeneratorType: getGlobalAsyncGeneratorType,
43874             resolveIterationType: getAwaitedType,
43875             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_async_iterator_must_have_a_next_method,
43876             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_async_iterator_must_be_a_method,
43877             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,
43878         };
43879         var syncIterationTypesResolver = {
43880             iterableCacheKey: "iterationTypesOfIterable",
43881             iteratorCacheKey: "iterationTypesOfIterator",
43882             iteratorSymbolName: "iterator",
43883             getGlobalIteratorType: getGlobalIteratorType,
43884             getGlobalIterableType: getGlobalIterableType,
43885             getGlobalIterableIteratorType: getGlobalIterableIteratorType,
43886             getGlobalGeneratorType: getGlobalGeneratorType,
43887             resolveIterationType: function (type, _errorNode) { return type; },
43888             mustHaveANextMethodDiagnostic: ts.Diagnostics.An_iterator_must_have_a_next_method,
43889             mustBeAMethodDiagnostic: ts.Diagnostics.The_0_property_of_an_iterator_must_be_a_method,
43890             mustHaveAValueDiagnostic: ts.Diagnostics.The_type_returned_by_the_0_method_of_an_iterator_must_have_a_value_property,
43891         };
43892         /** Key is "/path/to/a.ts|/path/to/b.ts". */
43893         var amalgamatedDuplicates;
43894         var reverseMappedCache = new ts.Map();
43895         var inInferTypeForHomomorphicMappedType = false;
43896         var ambientModulesCache;
43897         /**
43898          * List of every ambient module with a "*" wildcard.
43899          * Unlike other ambient modules, these can't be stored in `globals` because symbol tables only deal with exact matches.
43900          * This is only used if there is no exact match.
43901          */
43902         var patternAmbientModules;
43903         var patternAmbientModuleAugmentations;
43904         var globalObjectType;
43905         var globalFunctionType;
43906         var globalCallableFunctionType;
43907         var globalNewableFunctionType;
43908         var globalArrayType;
43909         var globalReadonlyArrayType;
43910         var globalStringType;
43911         var globalNumberType;
43912         var globalBooleanType;
43913         var globalRegExpType;
43914         var globalThisType;
43915         var anyArrayType;
43916         var autoArrayType;
43917         var anyReadonlyArrayType;
43918         var deferredGlobalNonNullableTypeAlias;
43919         // The library files are only loaded when the feature is used.
43920         // This allows users to just specify library files they want to used through --lib
43921         // and they will not get an error from not having unrelated library files
43922         var deferredGlobalESSymbolConstructorSymbol;
43923         var deferredGlobalESSymbolType;
43924         var deferredGlobalTypedPropertyDescriptorType;
43925         var deferredGlobalPromiseType;
43926         var deferredGlobalPromiseLikeType;
43927         var deferredGlobalPromiseConstructorSymbol;
43928         var deferredGlobalPromiseConstructorLikeType;
43929         var deferredGlobalIterableType;
43930         var deferredGlobalIteratorType;
43931         var deferredGlobalIterableIteratorType;
43932         var deferredGlobalGeneratorType;
43933         var deferredGlobalIteratorYieldResultType;
43934         var deferredGlobalIteratorReturnResultType;
43935         var deferredGlobalAsyncIterableType;
43936         var deferredGlobalAsyncIteratorType;
43937         var deferredGlobalAsyncIterableIteratorType;
43938         var deferredGlobalAsyncGeneratorType;
43939         var deferredGlobalTemplateStringsArrayType;
43940         var deferredGlobalImportMetaType;
43941         var deferredGlobalExtractSymbol;
43942         var deferredGlobalOmitSymbol;
43943         var deferredGlobalBigIntType;
43944         var allPotentiallyUnusedIdentifiers = new ts.Map(); // key is file name
43945         var flowLoopStart = 0;
43946         var flowLoopCount = 0;
43947         var sharedFlowCount = 0;
43948         var flowAnalysisDisabled = false;
43949         var flowInvocationCount = 0;
43950         var lastFlowNode;
43951         var lastFlowNodeReachable;
43952         var flowTypeCache;
43953         var emptyStringType = getLiteralType("");
43954         var zeroType = getLiteralType(0);
43955         var zeroBigIntType = getLiteralType({ negative: false, base10Value: "0" });
43956         var resolutionTargets = [];
43957         var resolutionResults = [];
43958         var resolutionPropertyNames = [];
43959         var suggestionCount = 0;
43960         var maximumSuggestionCount = 10;
43961         var mergedSymbols = [];
43962         var symbolLinks = [];
43963         var nodeLinks = [];
43964         var flowLoopCaches = [];
43965         var flowLoopNodes = [];
43966         var flowLoopKeys = [];
43967         var flowLoopTypes = [];
43968         var sharedFlowNodes = [];
43969         var sharedFlowTypes = [];
43970         var flowNodeReachable = [];
43971         var flowNodePostSuper = [];
43972         var potentialThisCollisions = [];
43973         var potentialNewTargetCollisions = [];
43974         var potentialWeakMapCollisions = [];
43975         var awaitedTypeStack = [];
43976         var diagnostics = ts.createDiagnosticCollection();
43977         var suggestionDiagnostics = ts.createDiagnosticCollection();
43978         var typeofTypesByName = new ts.Map(ts.getEntries({
43979             string: stringType,
43980             number: numberType,
43981             bigint: bigintType,
43982             boolean: booleanType,
43983             symbol: esSymbolType,
43984             undefined: undefinedType
43985         }));
43986         var typeofType = createTypeofType();
43987         var _jsxNamespace;
43988         var _jsxFactoryEntity;
43989         var outofbandVarianceMarkerHandler;
43990         var subtypeRelation = new ts.Map();
43991         var strictSubtypeRelation = new ts.Map();
43992         var assignableRelation = new ts.Map();
43993         var comparableRelation = new ts.Map();
43994         var identityRelation = new ts.Map();
43995         var enumRelation = new ts.Map();
43996         var builtinGlobals = ts.createSymbolTable();
43997         builtinGlobals.set(undefinedSymbol.escapedName, undefinedSymbol);
43998         initializeTypeChecker();
43999         return checker;
44000         function getJsxNamespace(location) {
44001             if (location) {
44002                 var file = ts.getSourceFileOfNode(location);
44003                 if (file) {
44004                     if (ts.isJsxOpeningFragment(location)) {
44005                         if (file.localJsxFragmentNamespace) {
44006                             return file.localJsxFragmentNamespace;
44007                         }
44008                         var jsxFragmentPragma = file.pragmas.get("jsxfrag");
44009                         if (jsxFragmentPragma) {
44010                             var chosenPragma = ts.isArray(jsxFragmentPragma) ? jsxFragmentPragma[0] : jsxFragmentPragma;
44011                             file.localJsxFragmentFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
44012                             ts.visitNode(file.localJsxFragmentFactory, markAsSynthetic);
44013                             if (file.localJsxFragmentFactory) {
44014                                 return file.localJsxFragmentNamespace = ts.getFirstIdentifier(file.localJsxFragmentFactory).escapedText;
44015                             }
44016                         }
44017                         var entity = getJsxFragmentFactoryEntity(location);
44018                         if (entity) {
44019                             file.localJsxFragmentFactory = entity;
44020                             return file.localJsxFragmentNamespace = ts.getFirstIdentifier(entity).escapedText;
44021                         }
44022                     }
44023                     else {
44024                         if (file.localJsxNamespace) {
44025                             return file.localJsxNamespace;
44026                         }
44027                         var jsxPragma = file.pragmas.get("jsx");
44028                         if (jsxPragma) {
44029                             var chosenPragma = ts.isArray(jsxPragma) ? jsxPragma[0] : jsxPragma;
44030                             file.localJsxFactory = ts.parseIsolatedEntityName(chosenPragma.arguments.factory, languageVersion);
44031                             ts.visitNode(file.localJsxFactory, markAsSynthetic);
44032                             if (file.localJsxFactory) {
44033                                 return file.localJsxNamespace = ts.getFirstIdentifier(file.localJsxFactory).escapedText;
44034                             }
44035                         }
44036                     }
44037                 }
44038             }
44039             if (!_jsxNamespace) {
44040                 _jsxNamespace = "React";
44041                 if (compilerOptions.jsxFactory) {
44042                     _jsxFactoryEntity = ts.parseIsolatedEntityName(compilerOptions.jsxFactory, languageVersion);
44043                     ts.visitNode(_jsxFactoryEntity, markAsSynthetic);
44044                     if (_jsxFactoryEntity) {
44045                         _jsxNamespace = ts.getFirstIdentifier(_jsxFactoryEntity).escapedText;
44046                     }
44047                 }
44048                 else if (compilerOptions.reactNamespace) {
44049                     _jsxNamespace = ts.escapeLeadingUnderscores(compilerOptions.reactNamespace);
44050                 }
44051             }
44052             if (!_jsxFactoryEntity) {
44053                 _jsxFactoryEntity = ts.factory.createQualifiedName(ts.factory.createIdentifier(ts.unescapeLeadingUnderscores(_jsxNamespace)), "createElement");
44054             }
44055             return _jsxNamespace;
44056             function markAsSynthetic(node) {
44057                 ts.setTextRangePosEnd(node, -1, -1);
44058                 return ts.visitEachChild(node, markAsSynthetic, ts.nullTransformationContext);
44059             }
44060         }
44061         function getEmitResolver(sourceFile, cancellationToken) {
44062             // Ensure we have all the type information in place for this file so that all the
44063             // emitter questions of this resolver will return the right information.
44064             getDiagnostics(sourceFile, cancellationToken);
44065             return emitResolver;
44066         }
44067         function lookupOrIssueError(location, message, arg0, arg1, arg2, arg3) {
44068             var diagnostic = location
44069                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
44070                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
44071             var existing = diagnostics.lookup(diagnostic);
44072             if (existing) {
44073                 return existing;
44074             }
44075             else {
44076                 diagnostics.add(diagnostic);
44077                 return diagnostic;
44078             }
44079         }
44080         function errorSkippedOn(key, location, message, arg0, arg1, arg2, arg3) {
44081             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
44082             diagnostic.skippedOn = key;
44083             return diagnostic;
44084         }
44085         function error(location, message, arg0, arg1, arg2, arg3) {
44086             var diagnostic = location
44087                 ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3)
44088                 : ts.createCompilerDiagnostic(message, arg0, arg1, arg2, arg3);
44089             diagnostics.add(diagnostic);
44090             return diagnostic;
44091         }
44092         function addErrorOrSuggestion(isError, diagnostic) {
44093             if (isError) {
44094                 diagnostics.add(diagnostic);
44095             }
44096             else {
44097                 suggestionDiagnostics.add(__assign(__assign({}, diagnostic), { category: ts.DiagnosticCategory.Suggestion }));
44098             }
44099         }
44100         function errorOrSuggestion(isError, location, message, arg0, arg1, arg2, arg3) {
44101             // Pseudo-synthesized input node
44102             if (location.pos < 0 || location.end < 0) {
44103                 if (!isError) {
44104                     return; // Drop suggestions (we have no span to suggest on)
44105                 }
44106                 // Issue errors globally
44107                 var file = ts.getSourceFileOfNode(location);
44108                 addErrorOrSuggestion(isError, "message" in message ? ts.createFileDiagnostic(file, 0, 0, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForFileFromMessageChain(file, message)); // eslint-disable-line no-in-operator
44109                 return;
44110             }
44111             addErrorOrSuggestion(isError, "message" in message ? ts.createDiagnosticForNode(location, message, arg0, arg1, arg2, arg3) : ts.createDiagnosticForNodeFromMessageChain(location, message)); // eslint-disable-line no-in-operator
44112         }
44113         function errorAndMaybeSuggestAwait(location, maybeMissingAwait, message, arg0, arg1, arg2, arg3) {
44114             var diagnostic = error(location, message, arg0, arg1, arg2, arg3);
44115             if (maybeMissingAwait) {
44116                 var related = ts.createDiagnosticForNode(location, ts.Diagnostics.Did_you_forget_to_use_await);
44117                 ts.addRelatedInfo(diagnostic, related);
44118             }
44119             return diagnostic;
44120         }
44121         function createSymbol(flags, name, checkFlags) {
44122             symbolCount++;
44123             var symbol = (new Symbol(flags | 33554432 /* Transient */, name));
44124             symbol.checkFlags = checkFlags || 0;
44125             return symbol;
44126         }
44127         function getExcludedSymbolFlags(flags) {
44128             var result = 0;
44129             if (flags & 2 /* BlockScopedVariable */)
44130                 result |= 111551 /* BlockScopedVariableExcludes */;
44131             if (flags & 1 /* FunctionScopedVariable */)
44132                 result |= 111550 /* FunctionScopedVariableExcludes */;
44133             if (flags & 4 /* Property */)
44134                 result |= 0 /* PropertyExcludes */;
44135             if (flags & 8 /* EnumMember */)
44136                 result |= 900095 /* EnumMemberExcludes */;
44137             if (flags & 16 /* Function */)
44138                 result |= 110991 /* FunctionExcludes */;
44139             if (flags & 32 /* Class */)
44140                 result |= 899503 /* ClassExcludes */;
44141             if (flags & 64 /* Interface */)
44142                 result |= 788872 /* InterfaceExcludes */;
44143             if (flags & 256 /* RegularEnum */)
44144                 result |= 899327 /* RegularEnumExcludes */;
44145             if (flags & 128 /* ConstEnum */)
44146                 result |= 899967 /* ConstEnumExcludes */;
44147             if (flags & 512 /* ValueModule */)
44148                 result |= 110735 /* ValueModuleExcludes */;
44149             if (flags & 8192 /* Method */)
44150                 result |= 103359 /* MethodExcludes */;
44151             if (flags & 32768 /* GetAccessor */)
44152                 result |= 46015 /* GetAccessorExcludes */;
44153             if (flags & 65536 /* SetAccessor */)
44154                 result |= 78783 /* SetAccessorExcludes */;
44155             if (flags & 262144 /* TypeParameter */)
44156                 result |= 526824 /* TypeParameterExcludes */;
44157             if (flags & 524288 /* TypeAlias */)
44158                 result |= 788968 /* TypeAliasExcludes */;
44159             if (flags & 2097152 /* Alias */)
44160                 result |= 2097152 /* AliasExcludes */;
44161             return result;
44162         }
44163         function recordMergedSymbol(target, source) {
44164             if (!source.mergeId) {
44165                 source.mergeId = nextMergeId;
44166                 nextMergeId++;
44167             }
44168             mergedSymbols[source.mergeId] = target;
44169         }
44170         function cloneSymbol(symbol) {
44171             var result = createSymbol(symbol.flags, symbol.escapedName);
44172             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
44173             result.parent = symbol.parent;
44174             if (symbol.valueDeclaration)
44175                 result.valueDeclaration = symbol.valueDeclaration;
44176             if (symbol.constEnumOnlyModule)
44177                 result.constEnumOnlyModule = true;
44178             if (symbol.members)
44179                 result.members = new ts.Map(symbol.members);
44180             if (symbol.exports)
44181                 result.exports = new ts.Map(symbol.exports);
44182             recordMergedSymbol(result, symbol);
44183             return result;
44184         }
44185         /**
44186          * Note: if target is transient, then it is mutable, and mergeSymbol with both mutate and return it.
44187          * If target is not transient, mergeSymbol will produce a transient clone, mutate that and return it.
44188          */
44189         function mergeSymbol(target, source, unidirectional) {
44190             if (unidirectional === void 0) { unidirectional = false; }
44191             if (!(target.flags & getExcludedSymbolFlags(source.flags)) ||
44192                 (source.flags | target.flags) & 67108864 /* Assignment */) {
44193                 if (source === target) {
44194                     // This can happen when an export assigned namespace exports something also erroneously exported at the top level
44195                     // See `declarationFileNoCrashOnExtraExportModifier` for an example
44196                     return target;
44197                 }
44198                 if (!(target.flags & 33554432 /* Transient */)) {
44199                     var resolvedTarget = resolveSymbol(target);
44200                     if (resolvedTarget === unknownSymbol) {
44201                         return source;
44202                     }
44203                     target = cloneSymbol(resolvedTarget);
44204                 }
44205                 // Javascript static-property-assignment declarations always merge, even though they are also values
44206                 if (source.flags & 512 /* ValueModule */ && target.flags & 512 /* ValueModule */ && target.constEnumOnlyModule && !source.constEnumOnlyModule) {
44207                     // reset flag when merging instantiated module into value module that has only const enums
44208                     target.constEnumOnlyModule = false;
44209                 }
44210                 target.flags |= source.flags;
44211                 if (source.valueDeclaration) {
44212                     ts.setValueDeclaration(target, source.valueDeclaration);
44213                 }
44214                 ts.addRange(target.declarations, source.declarations);
44215                 if (source.members) {
44216                     if (!target.members)
44217                         target.members = ts.createSymbolTable();
44218                     mergeSymbolTable(target.members, source.members, unidirectional);
44219                 }
44220                 if (source.exports) {
44221                     if (!target.exports)
44222                         target.exports = ts.createSymbolTable();
44223                     mergeSymbolTable(target.exports, source.exports, unidirectional);
44224                 }
44225                 if (!unidirectional) {
44226                     recordMergedSymbol(target, source);
44227                 }
44228             }
44229             else if (target.flags & 1024 /* NamespaceModule */) {
44230                 // Do not report an error when merging `var globalThis` with the built-in `globalThis`,
44231                 // as we will already report a "Declaration name conflicts..." error, and this error
44232                 // won't make much sense.
44233                 if (target !== globalThisSymbol) {
44234                     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));
44235                 }
44236             }
44237             else { // error
44238                 var isEitherEnum = !!(target.flags & 384 /* Enum */ || source.flags & 384 /* Enum */);
44239                 var isEitherBlockScoped_1 = !!(target.flags & 2 /* BlockScopedVariable */ || source.flags & 2 /* BlockScopedVariable */);
44240                 var message = isEitherEnum
44241                     ? ts.Diagnostics.Enum_declarations_can_only_merge_with_namespace_or_other_enum_declarations
44242                     : isEitherBlockScoped_1
44243                         ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0
44244                         : ts.Diagnostics.Duplicate_identifier_0;
44245                 var sourceSymbolFile = source.declarations && ts.getSourceFileOfNode(source.declarations[0]);
44246                 var targetSymbolFile = target.declarations && ts.getSourceFileOfNode(target.declarations[0]);
44247                 var symbolName_1 = symbolToString(source);
44248                 // Collect top-level duplicate identifier errors into one mapping, so we can then merge their diagnostics if there are a bunch
44249                 if (sourceSymbolFile && targetSymbolFile && amalgamatedDuplicates && !isEitherEnum && sourceSymbolFile !== targetSymbolFile) {
44250                     var firstFile_1 = ts.comparePaths(sourceSymbolFile.path, targetSymbolFile.path) === -1 /* LessThan */ ? sourceSymbolFile : targetSymbolFile;
44251                     var secondFile_1 = firstFile_1 === sourceSymbolFile ? targetSymbolFile : sourceSymbolFile;
44252                     var filesDuplicates = ts.getOrUpdate(amalgamatedDuplicates, firstFile_1.path + "|" + secondFile_1.path, function () {
44253                         return ({ firstFile: firstFile_1, secondFile: secondFile_1, conflictingSymbols: new ts.Map() });
44254                     });
44255                     var conflictingSymbolInfo = ts.getOrUpdate(filesDuplicates.conflictingSymbols, symbolName_1, function () {
44256                         return ({ isBlockScoped: isEitherBlockScoped_1, firstFileLocations: [], secondFileLocations: [] });
44257                     });
44258                     addDuplicateLocations(conflictingSymbolInfo.firstFileLocations, source);
44259                     addDuplicateLocations(conflictingSymbolInfo.secondFileLocations, target);
44260                 }
44261                 else {
44262                     addDuplicateDeclarationErrorsForSymbols(source, message, symbolName_1, target);
44263                     addDuplicateDeclarationErrorsForSymbols(target, message, symbolName_1, source);
44264                 }
44265             }
44266             return target;
44267             function addDuplicateLocations(locs, symbol) {
44268                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
44269                     var decl = _a[_i];
44270                     ts.pushIfUnique(locs, decl);
44271                 }
44272             }
44273         }
44274         function addDuplicateDeclarationErrorsForSymbols(target, message, symbolName, source) {
44275             ts.forEach(target.declarations, function (node) {
44276                 addDuplicateDeclarationError(node, message, symbolName, source.declarations);
44277             });
44278         }
44279         function addDuplicateDeclarationError(node, message, symbolName, relatedNodes) {
44280             var errorNode = (ts.getExpandoInitializer(node, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(node) : ts.getNameOfDeclaration(node)) || node;
44281             var err = lookupOrIssueError(errorNode, message, symbolName);
44282             var _loop_7 = function (relatedNode) {
44283                 var adjustedNode = (ts.getExpandoInitializer(relatedNode, /*isPrototypeAssignment*/ false) ? ts.getNameOfExpando(relatedNode) : ts.getNameOfDeclaration(relatedNode)) || relatedNode;
44284                 if (adjustedNode === errorNode)
44285                     return "continue";
44286                 err.relatedInformation = err.relatedInformation || [];
44287                 var leadingMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics._0_was_also_declared_here, symbolName);
44288                 var followOnMessage = ts.createDiagnosticForNode(adjustedNode, ts.Diagnostics.and_here);
44289                 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 */; }))
44290                     return "continue";
44291                 ts.addRelatedInfo(err, !ts.length(err.relatedInformation) ? leadingMessage : followOnMessage);
44292             };
44293             for (var _i = 0, _a = relatedNodes || ts.emptyArray; _i < _a.length; _i++) {
44294                 var relatedNode = _a[_i];
44295                 _loop_7(relatedNode);
44296             }
44297         }
44298         function combineSymbolTables(first, second) {
44299             if (!(first === null || first === void 0 ? void 0 : first.size))
44300                 return second;
44301             if (!(second === null || second === void 0 ? void 0 : second.size))
44302                 return first;
44303             var combined = ts.createSymbolTable();
44304             mergeSymbolTable(combined, first);
44305             mergeSymbolTable(combined, second);
44306             return combined;
44307         }
44308         function mergeSymbolTable(target, source, unidirectional) {
44309             if (unidirectional === void 0) { unidirectional = false; }
44310             source.forEach(function (sourceSymbol, id) {
44311                 var targetSymbol = target.get(id);
44312                 target.set(id, targetSymbol ? mergeSymbol(targetSymbol, sourceSymbol, unidirectional) : sourceSymbol);
44313             });
44314         }
44315         function mergeModuleAugmentation(moduleName) {
44316             var _a, _b;
44317             var moduleAugmentation = moduleName.parent;
44318             if (moduleAugmentation.symbol.declarations[0] !== moduleAugmentation) {
44319                 // this is a combined symbol for multiple augmentations within the same file.
44320                 // its symbol already has accumulated information for all declarations
44321                 // so we need to add it just once - do the work only for first declaration
44322                 ts.Debug.assert(moduleAugmentation.symbol.declarations.length > 1);
44323                 return;
44324             }
44325             if (ts.isGlobalScopeAugmentation(moduleAugmentation)) {
44326                 mergeSymbolTable(globals, moduleAugmentation.symbol.exports);
44327             }
44328             else {
44329                 // find a module that about to be augmented
44330                 // do not validate names of augmentations that are defined in ambient context
44331                 var moduleNotFoundError = !(moduleName.parent.parent.flags & 8388608 /* Ambient */)
44332                     ? ts.Diagnostics.Invalid_module_name_in_augmentation_module_0_cannot_be_found
44333                     : undefined;
44334                 var mainModule_1 = resolveExternalModuleNameWorker(moduleName, moduleName, moduleNotFoundError, /*isForAugmentation*/ true);
44335                 if (!mainModule_1) {
44336                     return;
44337                 }
44338                 // obtain item referenced by 'export='
44339                 mainModule_1 = resolveExternalModuleSymbol(mainModule_1);
44340                 if (mainModule_1.flags & 1920 /* Namespace */) {
44341                     // If we're merging an augmentation to a pattern ambient module, we want to
44342                     // perform the merge unidirectionally from the augmentation ('a.foo') to
44343                     // the pattern ('*.foo'), so that 'getMergedSymbol()' on a.foo gives you
44344                     // all the exports both from the pattern and from the augmentation, but
44345                     // 'getMergedSymbol()' on *.foo only gives you exports from *.foo.
44346                     if (ts.some(patternAmbientModules, function (module) { return mainModule_1 === module.symbol; })) {
44347                         var merged = mergeSymbol(moduleAugmentation.symbol, mainModule_1, /*unidirectional*/ true);
44348                         if (!patternAmbientModuleAugmentations) {
44349                             patternAmbientModuleAugmentations = new ts.Map();
44350                         }
44351                         // moduleName will be a StringLiteral since this is not `declare global`.
44352                         patternAmbientModuleAugmentations.set(moduleName.text, merged);
44353                     }
44354                     else {
44355                         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)) {
44356                             // We may need to merge the module augmentation's exports into the target symbols of the resolved exports
44357                             var resolvedExports = getResolvedMembersOrExportsOfSymbol(mainModule_1, "resolvedExports" /* resolvedExports */);
44358                             for (var _i = 0, _c = ts.arrayFrom(moduleAugmentation.symbol.exports.entries()); _i < _c.length; _i++) {
44359                                 var _d = _c[_i], key = _d[0], value = _d[1];
44360                                 if (resolvedExports.has(key) && !mainModule_1.exports.has(key)) {
44361                                     mergeSymbol(resolvedExports.get(key), value);
44362                                 }
44363                             }
44364                         }
44365                         mergeSymbol(mainModule_1, moduleAugmentation.symbol);
44366                     }
44367                 }
44368                 else {
44369                     // moduleName will be a StringLiteral since this is not `declare global`.
44370                     error(moduleName, ts.Diagnostics.Cannot_augment_module_0_because_it_resolves_to_a_non_module_entity, moduleName.text);
44371                 }
44372             }
44373         }
44374         function addToSymbolTable(target, source, message) {
44375             source.forEach(function (sourceSymbol, id) {
44376                 var targetSymbol = target.get(id);
44377                 if (targetSymbol) {
44378                     // Error on redeclarations
44379                     ts.forEach(targetSymbol.declarations, addDeclarationDiagnostic(ts.unescapeLeadingUnderscores(id), message));
44380                 }
44381                 else {
44382                     target.set(id, sourceSymbol);
44383                 }
44384             });
44385             function addDeclarationDiagnostic(id, message) {
44386                 return function (declaration) { return diagnostics.add(ts.createDiagnosticForNode(declaration, message, id)); };
44387             }
44388         }
44389         function getSymbolLinks(symbol) {
44390             if (symbol.flags & 33554432 /* Transient */)
44391                 return symbol;
44392             var id = getSymbolId(symbol);
44393             return symbolLinks[id] || (symbolLinks[id] = new SymbolLinks());
44394         }
44395         function getNodeLinks(node) {
44396             var nodeId = getNodeId(node);
44397             return nodeLinks[nodeId] || (nodeLinks[nodeId] = new NodeLinks());
44398         }
44399         function isGlobalSourceFile(node) {
44400             return node.kind === 297 /* SourceFile */ && !ts.isExternalOrCommonJsModule(node);
44401         }
44402         function getSymbol(symbols, name, meaning) {
44403             if (meaning) {
44404                 var symbol = getMergedSymbol(symbols.get(name));
44405                 if (symbol) {
44406                     ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
44407                     if (symbol.flags & meaning) {
44408                         return symbol;
44409                     }
44410                     if (symbol.flags & 2097152 /* Alias */) {
44411                         var target = resolveAlias(symbol);
44412                         // Unknown symbol means an error occurred in alias resolution, treat it as positive answer to avoid cascading errors
44413                         if (target === unknownSymbol || target.flags & meaning) {
44414                             return symbol;
44415                         }
44416                     }
44417                 }
44418             }
44419             // return undefined if we can't find a symbol.
44420         }
44421         /**
44422          * Get symbols that represent parameter-property-declaration as parameter and as property declaration
44423          * @param parameter a parameterDeclaration node
44424          * @param parameterName a name of the parameter to get the symbols for.
44425          * @return a tuple of two symbols
44426          */
44427         function getSymbolsOfParameterPropertyDeclaration(parameter, parameterName) {
44428             var constructorDeclaration = parameter.parent;
44429             var classDeclaration = parameter.parent.parent;
44430             var parameterSymbol = getSymbol(constructorDeclaration.locals, parameterName, 111551 /* Value */);
44431             var propertySymbol = getSymbol(getMembersOfSymbol(classDeclaration.symbol), parameterName, 111551 /* Value */);
44432             if (parameterSymbol && propertySymbol) {
44433                 return [parameterSymbol, propertySymbol];
44434             }
44435             return ts.Debug.fail("There should exist two symbols, one as property declaration and one as parameter declaration");
44436         }
44437         function isBlockScopedNameDeclaredBeforeUse(declaration, usage) {
44438             var declarationFile = ts.getSourceFileOfNode(declaration);
44439             var useFile = ts.getSourceFileOfNode(usage);
44440             var declContainer = ts.getEnclosingBlockScopeContainer(declaration);
44441             if (declarationFile !== useFile) {
44442                 if ((moduleKind && (declarationFile.externalModuleIndicator || useFile.externalModuleIndicator)) ||
44443                     (!ts.outFile(compilerOptions)) ||
44444                     isInTypeQuery(usage) ||
44445                     declaration.flags & 8388608 /* Ambient */) {
44446                     // nodes are in different files and order cannot be determined
44447                     return true;
44448                 }
44449                 // declaration is after usage
44450                 // can be legal if usage is deferred (i.e. inside function or in initializer of instance property)
44451                 if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
44452                     return true;
44453                 }
44454                 var sourceFiles = host.getSourceFiles();
44455                 return sourceFiles.indexOf(declarationFile) <= sourceFiles.indexOf(useFile);
44456             }
44457             if (declaration.pos <= usage.pos && !(ts.isPropertyDeclaration(declaration) && ts.isThisProperty(usage.parent) && !declaration.initializer && !declaration.exclamationToken)) {
44458                 // declaration is before usage
44459                 if (declaration.kind === 198 /* BindingElement */) {
44460                     // still might be illegal if declaration and usage are both binding elements (eg var [a = b, b = b] = [1, 2])
44461                     var errorBindingElement = ts.getAncestor(usage, 198 /* BindingElement */);
44462                     if (errorBindingElement) {
44463                         return ts.findAncestor(errorBindingElement, ts.isBindingElement) !== ts.findAncestor(declaration, ts.isBindingElement) ||
44464                             declaration.pos < errorBindingElement.pos;
44465                     }
44466                     // or it might be illegal if usage happens before parent variable is declared (eg var [a] = a)
44467                     return isBlockScopedNameDeclaredBeforeUse(ts.getAncestor(declaration, 249 /* VariableDeclaration */), usage);
44468                 }
44469                 else if (declaration.kind === 249 /* VariableDeclaration */) {
44470                     // still might be illegal if usage is in the initializer of the variable declaration (eg var a = a)
44471                     return !isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage);
44472                 }
44473                 else if (ts.isClassDeclaration(declaration)) {
44474                     // still might be illegal if the usage is within a computed property name in the class (eg class A { static p = "a"; [A.p]() {} })
44475                     return !ts.findAncestor(usage, function (n) { return ts.isComputedPropertyName(n) && n.parent.parent === declaration; });
44476                 }
44477                 else if (ts.isPropertyDeclaration(declaration)) {
44478                     // still might be illegal if a self-referencing property initializer (eg private x = this.x)
44479                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ false);
44480                 }
44481                 else if (ts.isParameterPropertyDeclaration(declaration, declaration.parent)) {
44482                     // foo = this.bar is illegal in esnext+useDefineForClassFields when bar is a parameter property
44483                     return !(compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
44484                         && ts.getContainingClass(declaration) === ts.getContainingClass(usage)
44485                         && isUsedInFunctionOrInstanceProperty(usage, declaration));
44486                 }
44487                 return true;
44488             }
44489             // declaration is after usage, but it can still be legal if usage is deferred:
44490             // 1. inside an export specifier
44491             // 2. inside a function
44492             // 3. inside an instance property initializer, a reference to a non-instance property
44493             //    (except when target: "esnext" and useDefineForClassFields: true and the reference is to a parameter property)
44494             // 4. inside a static property initializer, a reference to a static method in the same class
44495             // 5. inside a TS export= declaration (since we will move the export statement during emit to avoid TDZ)
44496             // or if usage is in a type context:
44497             // 1. inside a type query (typeof in type position)
44498             // 2. inside a jsdoc comment
44499             if (usage.parent.kind === 270 /* ExportSpecifier */ || (usage.parent.kind === 266 /* ExportAssignment */ && usage.parent.isExportEquals)) {
44500                 // export specifiers do not use the variable, they only make it available for use
44501                 return true;
44502             }
44503             // When resolving symbols for exports, the `usage` location passed in can be the export site directly
44504             if (usage.kind === 266 /* ExportAssignment */ && usage.isExportEquals) {
44505                 return true;
44506             }
44507             if (!!(usage.flags & 4194304 /* JSDoc */) || isInTypeQuery(usage) || usageInTypeDeclaration()) {
44508                 return true;
44509             }
44510             if (isUsedInFunctionOrInstanceProperty(usage, declaration)) {
44511                 if (compilerOptions.target === 99 /* ESNext */ && !!compilerOptions.useDefineForClassFields
44512                     && ts.getContainingClass(declaration)
44513                     && (ts.isPropertyDeclaration(declaration) || ts.isParameterPropertyDeclaration(declaration, declaration.parent))) {
44514                     return !isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, /*stopAtAnyPropertyDeclaration*/ true);
44515                 }
44516                 else {
44517                     return true;
44518                 }
44519             }
44520             return false;
44521             function usageInTypeDeclaration() {
44522                 return !!ts.findAncestor(usage, function (node) { return ts.isInterfaceDeclaration(node) || ts.isTypeAliasDeclaration(node); });
44523             }
44524             function isImmediatelyUsedInInitializerOfBlockScopedVariable(declaration, usage) {
44525                 switch (declaration.parent.parent.kind) {
44526                     case 232 /* VariableStatement */:
44527                     case 237 /* ForStatement */:
44528                     case 239 /* ForOfStatement */:
44529                         // variable statement/for/for-of statement case,
44530                         // use site should not be inside variable declaration (initializer of declaration or binding element)
44531                         if (isSameScopeDescendentOf(usage, declaration, declContainer)) {
44532                             return true;
44533                         }
44534                         break;
44535                 }
44536                 // ForIn/ForOf case - use site should not be used in expression part
44537                 var grandparent = declaration.parent.parent;
44538                 return ts.isForInOrOfStatement(grandparent) && isSameScopeDescendentOf(usage, grandparent.expression, declContainer);
44539             }
44540             function isUsedInFunctionOrInstanceProperty(usage, declaration) {
44541                 return !!ts.findAncestor(usage, function (current) {
44542                     if (current === declContainer) {
44543                         return "quit";
44544                     }
44545                     if (ts.isFunctionLike(current)) {
44546                         return true;
44547                     }
44548                     var initializerOfProperty = current.parent &&
44549                         current.parent.kind === 163 /* PropertyDeclaration */ &&
44550                         current.parent.initializer === current;
44551                     if (initializerOfProperty) {
44552                         if (ts.hasSyntacticModifier(current.parent, 32 /* Static */)) {
44553                             if (declaration.kind === 165 /* MethodDeclaration */) {
44554                                 return true;
44555                             }
44556                         }
44557                         else {
44558                             var isDeclarationInstanceProperty = declaration.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(declaration, 32 /* Static */);
44559                             if (!isDeclarationInstanceProperty || ts.getContainingClass(usage) !== ts.getContainingClass(declaration)) {
44560                                 return true;
44561                             }
44562                         }
44563                     }
44564                     return false;
44565                 });
44566             }
44567             /** stopAtAnyPropertyDeclaration is used for detecting ES-standard class field use-before-def errors */
44568             function isPropertyImmediatelyReferencedWithinDeclaration(declaration, usage, stopAtAnyPropertyDeclaration) {
44569                 // always legal if usage is after declaration
44570                 if (usage.end > declaration.end) {
44571                     return false;
44572                 }
44573                 // still might be legal if usage is deferred (e.g. x: any = () => this.x)
44574                 // otherwise illegal if immediately referenced within the declaration (e.g. x: any = this.x)
44575                 var ancestorChangingReferenceScope = ts.findAncestor(usage, function (node) {
44576                     if (node === declaration) {
44577                         return "quit";
44578                     }
44579                     switch (node.kind) {
44580                         case 209 /* ArrowFunction */:
44581                             return true;
44582                         case 163 /* PropertyDeclaration */:
44583                             // even when stopping at any property declaration, they need to come from the same class
44584                             return stopAtAnyPropertyDeclaration &&
44585                                 (ts.isPropertyDeclaration(declaration) && node.parent === declaration.parent
44586                                     || ts.isParameterPropertyDeclaration(declaration, declaration.parent) && node.parent === declaration.parent.parent)
44587                                 ? "quit" : true;
44588                         case 230 /* Block */:
44589                             switch (node.parent.kind) {
44590                                 case 167 /* GetAccessor */:
44591                                 case 165 /* MethodDeclaration */:
44592                                 case 168 /* SetAccessor */:
44593                                     return true;
44594                                 default:
44595                                     return false;
44596                             }
44597                         default:
44598                             return false;
44599                     }
44600                 });
44601                 return ancestorChangingReferenceScope === undefined;
44602             }
44603         }
44604         function useOuterVariableScopeInParameter(result, location, lastLocation) {
44605             var target = ts.getEmitScriptTarget(compilerOptions);
44606             var functionLocation = location;
44607             if (ts.isParameter(lastLocation) && functionLocation.body && result.valueDeclaration.pos >= functionLocation.body.pos && result.valueDeclaration.end <= functionLocation.body.end) {
44608                 // check for several cases where we introduce temporaries that require moving the name/initializer of the parameter to the body
44609                 // - static field in a class expression
44610                 // - optional chaining pre-es2020
44611                 // - nullish coalesce pre-es2020
44612                 // - spread assignment in binding pattern pre-es2017
44613                 if (target >= 2 /* ES2015 */) {
44614                     var links = getNodeLinks(functionLocation);
44615                     if (links.declarationRequiresScopeChange === undefined) {
44616                         links.declarationRequiresScopeChange = ts.forEach(functionLocation.parameters, requiresScopeChange) || false;
44617                     }
44618                     return !links.declarationRequiresScopeChange;
44619                 }
44620             }
44621             return false;
44622             function requiresScopeChange(node) {
44623                 return requiresScopeChangeWorker(node.name)
44624                     || !!node.initializer && requiresScopeChangeWorker(node.initializer);
44625             }
44626             function requiresScopeChangeWorker(node) {
44627                 switch (node.kind) {
44628                     case 209 /* ArrowFunction */:
44629                     case 208 /* FunctionExpression */:
44630                     case 251 /* FunctionDeclaration */:
44631                     case 166 /* Constructor */:
44632                         // do not descend into these
44633                         return false;
44634                     case 165 /* MethodDeclaration */:
44635                     case 167 /* GetAccessor */:
44636                     case 168 /* SetAccessor */:
44637                     case 288 /* PropertyAssignment */:
44638                         return requiresScopeChangeWorker(node.name);
44639                     case 163 /* PropertyDeclaration */:
44640                         // static properties in classes introduce temporary variables
44641                         if (ts.hasStaticModifier(node)) {
44642                             return target < 99 /* ESNext */ || !compilerOptions.useDefineForClassFields;
44643                         }
44644                         return requiresScopeChangeWorker(node.name);
44645                     default:
44646                         // null coalesce and optional chain pre-es2020 produce temporary variables
44647                         if (ts.isNullishCoalesce(node) || ts.isOptionalChain(node)) {
44648                             return target < 7 /* ES2020 */;
44649                         }
44650                         if (ts.isBindingElement(node) && node.dotDotDotToken && ts.isObjectBindingPattern(node.parent)) {
44651                             return target < 4 /* ES2017 */;
44652                         }
44653                         if (ts.isTypeNode(node))
44654                             return false;
44655                         return ts.forEachChild(node, requiresScopeChangeWorker) || false;
44656                 }
44657             }
44658         }
44659         /**
44660          * Resolve a given name for a given meaning at a given location. An error is reported if the name was not found and
44661          * the nameNotFoundMessage argument is not undefined. Returns the resolved symbol, or undefined if no symbol with
44662          * the given name can be found.
44663          *
44664          * @param isUse If true, this will count towards --noUnusedLocals / --noUnusedParameters.
44665          */
44666         function resolveName(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, suggestedNameNotFoundMessage) {
44667             if (excludeGlobals === void 0) { excludeGlobals = false; }
44668             return resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, getSymbol, suggestedNameNotFoundMessage);
44669         }
44670         function resolveNameHelper(location, name, meaning, nameNotFoundMessage, nameArg, isUse, excludeGlobals, lookup, suggestedNameNotFoundMessage) {
44671             var originalLocation = location; // needed for did-you-mean error reporting, which gathers candidates starting from the original location
44672             var result;
44673             var lastLocation;
44674             var lastSelfReferenceLocation;
44675             var propertyWithInvalidInitializer;
44676             var associatedDeclarationForContainingInitializerOrBindingName;
44677             var withinDeferredContext = false;
44678             var errorLocation = location;
44679             var grandparent;
44680             var isInExternalModule = false;
44681             loop: while (location) {
44682                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
44683                 if (location.locals && !isGlobalSourceFile(location)) {
44684                     if (result = lookup(location.locals, name, meaning)) {
44685                         var useResult = true;
44686                         if (ts.isFunctionLike(location) && lastLocation && lastLocation !== location.body) {
44687                             // symbol lookup restrictions for function-like declarations
44688                             // - Type parameters of a function are in scope in the entire function declaration, including the parameter
44689                             //   list and return type. However, local types are only in scope in the function body.
44690                             // - parameters are only in the scope of function body
44691                             // This restriction does not apply to JSDoc comment types because they are parented
44692                             // at a higher level than type parameters would normally be
44693                             if (meaning & result.flags & 788968 /* Type */ && lastLocation.kind !== 311 /* JSDocComment */) {
44694                                 useResult = result.flags & 262144 /* TypeParameter */
44695                                     // type parameters are visible in parameter list, return type and type parameter list
44696                                     ? lastLocation === location.type ||
44697                                         lastLocation.kind === 160 /* Parameter */ ||
44698                                         lastLocation.kind === 159 /* TypeParameter */
44699                                     // local types not visible outside the function body
44700                                     : false;
44701                             }
44702                             if (meaning & result.flags & 3 /* Variable */) {
44703                                 // expression inside parameter will lookup as normal variable scope when targeting es2015+
44704                                 if (useOuterVariableScopeInParameter(result, location, lastLocation)) {
44705                                     useResult = false;
44706                                 }
44707                                 else if (result.flags & 1 /* FunctionScopedVariable */) {
44708                                     // parameters are visible only inside function body, parameter list and return type
44709                                     // technically for parameter list case here we might mix parameters and variables declared in function,
44710                                     // however it is detected separately when checking initializers of parameters
44711                                     // to make sure that they reference no variables declared after them.
44712                                     useResult =
44713                                         lastLocation.kind === 160 /* Parameter */ ||
44714                                             (lastLocation === location.type &&
44715                                                 !!ts.findAncestor(result.valueDeclaration, ts.isParameter));
44716                                 }
44717                             }
44718                         }
44719                         else if (location.kind === 184 /* ConditionalType */) {
44720                             // A type parameter declared using 'infer T' in a conditional type is visible only in
44721                             // the true branch of the conditional type.
44722                             useResult = lastLocation === location.trueType;
44723                         }
44724                         if (useResult) {
44725                             break loop;
44726                         }
44727                         else {
44728                             result = undefined;
44729                         }
44730                     }
44731                 }
44732                 withinDeferredContext = withinDeferredContext || getIsDeferredContext(location, lastLocation);
44733                 switch (location.kind) {
44734                     case 297 /* SourceFile */:
44735                         if (!ts.isExternalOrCommonJsModule(location))
44736                             break;
44737                         isInExternalModule = true;
44738                     // falls through
44739                     case 256 /* ModuleDeclaration */:
44740                         var moduleExports = getSymbolOfNode(location).exports || emptySymbols;
44741                         if (location.kind === 297 /* SourceFile */ || (ts.isModuleDeclaration(location) && location.flags & 8388608 /* Ambient */ && !ts.isGlobalScopeAugmentation(location))) {
44742                             // It's an external module. First see if the module has an export default and if the local
44743                             // name of that export default matches.
44744                             if (result = moduleExports.get("default" /* Default */)) {
44745                                 var localSymbol = ts.getLocalSymbolForExportDefault(result);
44746                                 if (localSymbol && (result.flags & meaning) && localSymbol.escapedName === name) {
44747                                     break loop;
44748                                 }
44749                                 result = undefined;
44750                             }
44751                             // Because of module/namespace merging, a module's exports are in scope,
44752                             // yet we never want to treat an export specifier as putting a member in scope.
44753                             // Therefore, if the name we find is purely an export specifier, it is not actually considered in scope.
44754                             // Two things to note about this:
44755                             //     1. We have to check this without calling getSymbol. The problem with calling getSymbol
44756                             //        on an export specifier is that it might find the export specifier itself, and try to
44757                             //        resolve it as an alias. This will cause the checker to consider the export specifier
44758                             //        a circular alias reference when it might not be.
44759                             //     2. We check === SymbolFlags.Alias in order to check that the symbol is *purely*
44760                             //        an alias. If we used &, we'd be throwing out symbols that have non alias aspects,
44761                             //        which is not the desired behavior.
44762                             var moduleExport = moduleExports.get(name);
44763                             if (moduleExport &&
44764                                 moduleExport.flags === 2097152 /* Alias */ &&
44765                                 (ts.getDeclarationOfKind(moduleExport, 270 /* ExportSpecifier */) || ts.getDeclarationOfKind(moduleExport, 269 /* NamespaceExport */))) {
44766                                 break;
44767                             }
44768                         }
44769                         // ES6 exports are also visible locally (except for 'default'), but commonjs exports are not (except typedefs)
44770                         if (name !== "default" /* Default */ && (result = lookup(moduleExports, name, meaning & 2623475 /* ModuleMember */))) {
44771                             if (ts.isSourceFile(location) && location.commonJsModuleIndicator && !result.declarations.some(ts.isJSDocTypeAlias)) {
44772                                 result = undefined;
44773                             }
44774                             else {
44775                                 break loop;
44776                             }
44777                         }
44778                         break;
44779                     case 255 /* EnumDeclaration */:
44780                         if (result = lookup(getSymbolOfNode(location).exports, name, meaning & 8 /* EnumMember */)) {
44781                             break loop;
44782                         }
44783                         break;
44784                     case 163 /* PropertyDeclaration */:
44785                         // TypeScript 1.0 spec (April 2014): 8.4.1
44786                         // Initializer expressions for instance member variables are evaluated in the scope
44787                         // of the class constructor body but are not permitted to reference parameters or
44788                         // local variables of the constructor. This effectively means that entities from outer scopes
44789                         // by the same name as a constructor parameter or local variable are inaccessible
44790                         // in initializer expressions for instance member variables.
44791                         if (!ts.hasSyntacticModifier(location, 32 /* Static */)) {
44792                             var ctor = findConstructorDeclaration(location.parent);
44793                             if (ctor && ctor.locals) {
44794                                 if (lookup(ctor.locals, name, meaning & 111551 /* Value */)) {
44795                                     // Remember the property node, it will be used later to report appropriate error
44796                                     propertyWithInvalidInitializer = location;
44797                                 }
44798                             }
44799                         }
44800                         break;
44801                     case 252 /* ClassDeclaration */:
44802                     case 221 /* ClassExpression */:
44803                     case 253 /* InterfaceDeclaration */:
44804                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
44805                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
44806                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
44807                         if (result = lookup(getSymbolOfNode(location).members || emptySymbols, name, meaning & 788968 /* Type */)) {
44808                             if (!isTypeParameterSymbolDeclaredInContainer(result, location)) {
44809                                 // ignore type parameters not declared in this container
44810                                 result = undefined;
44811                                 break;
44812                             }
44813                             if (lastLocation && ts.hasSyntacticModifier(lastLocation, 32 /* Static */)) {
44814                                 // TypeScript 1.0 spec (April 2014): 3.4.1
44815                                 // The scope of a type parameter extends over the entire declaration with which the type
44816                                 // parameter list is associated, with the exception of static member declarations in classes.
44817                                 error(errorLocation, ts.Diagnostics.Static_members_cannot_reference_class_type_parameters);
44818                                 return undefined;
44819                             }
44820                             break loop;
44821                         }
44822                         if (location.kind === 221 /* ClassExpression */ && meaning & 32 /* Class */) {
44823                             var className = location.name;
44824                             if (className && name === className.escapedText) {
44825                                 result = location.symbol;
44826                                 break loop;
44827                             }
44828                         }
44829                         break;
44830                     case 223 /* ExpressionWithTypeArguments */:
44831                         // The type parameters of a class are not in scope in the base class expression.
44832                         if (lastLocation === location.expression && location.parent.token === 93 /* ExtendsKeyword */) {
44833                             var container = location.parent.parent;
44834                             if (ts.isClassLike(container) && (result = lookup(getSymbolOfNode(container).members, name, meaning & 788968 /* Type */))) {
44835                                 if (nameNotFoundMessage) {
44836                                     error(errorLocation, ts.Diagnostics.Base_class_expressions_cannot_reference_class_type_parameters);
44837                                 }
44838                                 return undefined;
44839                             }
44840                         }
44841                         break;
44842                     // It is not legal to reference a class's own type parameters from a computed property name that
44843                     // belongs to the class. For example:
44844                     //
44845                     //   function foo<T>() { return '' }
44846                     //   class C<T> { // <-- Class's own type parameter T
44847                     //       [foo<T>()]() { } // <-- Reference to T from class's own computed property
44848                     //   }
44849                     //
44850                     case 158 /* ComputedPropertyName */:
44851                         grandparent = location.parent.parent;
44852                         if (ts.isClassLike(grandparent) || grandparent.kind === 253 /* InterfaceDeclaration */) {
44853                             // A reference to this grandparent's type parameters would be an error
44854                             if (result = lookup(getSymbolOfNode(grandparent).members, name, meaning & 788968 /* Type */)) {
44855                                 error(errorLocation, ts.Diagnostics.A_computed_property_name_cannot_reference_a_type_parameter_from_its_containing_type);
44856                                 return undefined;
44857                             }
44858                         }
44859                         break;
44860                     case 209 /* ArrowFunction */:
44861                         // when targeting ES6 or higher there is no 'arguments' in an arrow function
44862                         // for lower compile targets the resolved symbol is used to emit an error
44863                         if (compilerOptions.target >= 2 /* ES2015 */) {
44864                             break;
44865                         }
44866                     // falls through
44867                     case 165 /* MethodDeclaration */:
44868                     case 166 /* Constructor */:
44869                     case 167 /* GetAccessor */:
44870                     case 168 /* SetAccessor */:
44871                     case 251 /* FunctionDeclaration */:
44872                         if (meaning & 3 /* Variable */ && name === "arguments") {
44873                             result = argumentsSymbol;
44874                             break loop;
44875                         }
44876                         break;
44877                     case 208 /* FunctionExpression */:
44878                         if (meaning & 3 /* Variable */ && name === "arguments") {
44879                             result = argumentsSymbol;
44880                             break loop;
44881                         }
44882                         if (meaning & 16 /* Function */) {
44883                             var functionName = location.name;
44884                             if (functionName && name === functionName.escapedText) {
44885                                 result = location.symbol;
44886                                 break loop;
44887                             }
44888                         }
44889                         break;
44890                     case 161 /* Decorator */:
44891                         // Decorators are resolved at the class declaration. Resolving at the parameter
44892                         // or member would result in looking up locals in the method.
44893                         //
44894                         //   function y() {}
44895                         //   class C {
44896                         //       method(@y x, y) {} // <-- decorator y should be resolved at the class declaration, not the parameter.
44897                         //   }
44898                         //
44899                         if (location.parent && location.parent.kind === 160 /* Parameter */) {
44900                             location = location.parent;
44901                         }
44902                         //
44903                         //   function y() {}
44904                         //   class C {
44905                         //       @y method(x, y) {} // <-- decorator y should be resolved at the class declaration, not the method.
44906                         //   }
44907                         //
44908                         // class Decorators are resolved outside of the class to avoid referencing type parameters of that class.
44909                         //
44910                         //   type T = number;
44911                         //   declare function y(x: T): any;
44912                         //   @param(1 as T) // <-- T should resolve to the type alias outside of class C
44913                         //   class C<T> {}
44914                         if (location.parent && (ts.isClassElement(location.parent) || location.parent.kind === 252 /* ClassDeclaration */)) {
44915                             location = location.parent;
44916                         }
44917                         break;
44918                     case 331 /* JSDocTypedefTag */:
44919                     case 324 /* JSDocCallbackTag */:
44920                     case 325 /* JSDocEnumTag */:
44921                         // js type aliases do not resolve names from their host, so skip past it
44922                         location = ts.getJSDocHost(location);
44923                         break;
44924                     case 160 /* Parameter */:
44925                         if (lastLocation && (lastLocation === location.initializer ||
44926                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
44927                             if (!associatedDeclarationForContainingInitializerOrBindingName) {
44928                                 associatedDeclarationForContainingInitializerOrBindingName = location;
44929                             }
44930                         }
44931                         break;
44932                     case 198 /* BindingElement */:
44933                         if (lastLocation && (lastLocation === location.initializer ||
44934                             lastLocation === location.name && ts.isBindingPattern(lastLocation))) {
44935                             if (ts.isParameterDeclaration(location) && !associatedDeclarationForContainingInitializerOrBindingName) {
44936                                 associatedDeclarationForContainingInitializerOrBindingName = location;
44937                             }
44938                         }
44939                         break;
44940                     case 185 /* InferType */:
44941                         if (meaning & 262144 /* TypeParameter */) {
44942                             var parameterName = location.typeParameter.name;
44943                             if (parameterName && name === parameterName.escapedText) {
44944                                 result = location.typeParameter.symbol;
44945                                 break loop;
44946                             }
44947                         }
44948                         break;
44949                 }
44950                 if (isSelfReferenceLocation(location)) {
44951                     lastSelfReferenceLocation = location;
44952                 }
44953                 lastLocation = location;
44954                 location = location.parent;
44955             }
44956             // We just climbed up parents looking for the name, meaning that we started in a descendant node of `lastLocation`.
44957             // If `result === lastSelfReferenceLocation.symbol`, that means that we are somewhere inside `lastSelfReferenceLocation` looking up a name, and resolving to `lastLocation` itself.
44958             // That means that this is a self-reference of `lastLocation`, and shouldn't count this when considering whether `lastLocation` is used.
44959             if (isUse && result && (!lastSelfReferenceLocation || result !== lastSelfReferenceLocation.symbol)) {
44960                 result.isReferenced |= meaning;
44961             }
44962             if (!result) {
44963                 if (lastLocation) {
44964                     ts.Debug.assert(lastLocation.kind === 297 /* SourceFile */);
44965                     if (lastLocation.commonJsModuleIndicator && name === "exports" && meaning & lastLocation.symbol.flags) {
44966                         return lastLocation.symbol;
44967                     }
44968                 }
44969                 if (!excludeGlobals) {
44970                     result = lookup(globals, name, meaning);
44971                 }
44972             }
44973             if (!result) {
44974                 if (originalLocation && ts.isInJSFile(originalLocation) && originalLocation.parent) {
44975                     if (ts.isRequireCall(originalLocation.parent, /*checkArgumentIsStringLiteralLike*/ false)) {
44976                         return requireSymbol;
44977                     }
44978                 }
44979             }
44980             if (!result) {
44981                 if (nameNotFoundMessage) {
44982                     if (!errorLocation ||
44983                         !checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) && // TODO: GH#18217
44984                             !checkAndReportErrorForExtendingInterface(errorLocation) &&
44985                             !checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) &&
44986                             !checkAndReportErrorForExportingPrimitiveType(errorLocation, name) &&
44987                             !checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) &&
44988                             !checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) &&
44989                             !checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning)) {
44990                         var suggestion = void 0;
44991                         if (suggestedNameNotFoundMessage && suggestionCount < maximumSuggestionCount) {
44992                             suggestion = getSuggestedSymbolForNonexistentSymbol(originalLocation, name, meaning);
44993                             if (suggestion) {
44994                                 var suggestionName = symbolToString(suggestion);
44995                                 var diagnostic = error(errorLocation, suggestedNameNotFoundMessage, diagnosticName(nameArg), suggestionName);
44996                                 if (suggestion.valueDeclaration) {
44997                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
44998                                 }
44999                             }
45000                         }
45001                         if (!suggestion) {
45002                             if (nameArg) {
45003                                 var lib = getSuggestedLibForNonExistentName(nameArg);
45004                                 if (lib) {
45005                                     error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg), lib);
45006                                 }
45007                                 else {
45008                                     error(errorLocation, nameNotFoundMessage, diagnosticName(nameArg));
45009                                 }
45010                             }
45011                         }
45012                         suggestionCount++;
45013                     }
45014                 }
45015                 return undefined;
45016             }
45017             // Perform extra checks only if error reporting was requested
45018             if (nameNotFoundMessage) {
45019                 if (propertyWithInvalidInitializer && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
45020                     // We have a match, but the reference occurred within a property initializer and the identifier also binds
45021                     // to a local variable in the constructor where the code will be emitted. Note that this is actually allowed
45022                     // with ESNext+useDefineForClassFields because the scope semantics are different.
45023                     var propertyName = propertyWithInvalidInitializer.name;
45024                     error(errorLocation, ts.Diagnostics.Initializer_of_instance_member_variable_0_cannot_reference_identifier_1_declared_in_the_constructor, ts.declarationNameToString(propertyName), diagnosticName(nameArg));
45025                     return undefined;
45026                 }
45027                 // Only check for block-scoped variable if we have an error location and are looking for the
45028                 // name with variable meaning
45029                 //      For example,
45030                 //          declare module foo {
45031                 //              interface bar {}
45032                 //          }
45033                 //      const foo/*1*/: foo/*2*/.bar;
45034                 // The foo at /*1*/ and /*2*/ will share same symbol with two meanings:
45035                 // block-scoped variable and namespace module. However, only when we
45036                 // try to resolve name in /*1*/ which is used in variable position,
45037                 // we want to check for block-scoped
45038                 if (errorLocation &&
45039                     (meaning & 2 /* BlockScopedVariable */ ||
45040                         ((meaning & 32 /* Class */ || meaning & 384 /* Enum */) && (meaning & 111551 /* Value */) === 111551 /* Value */))) {
45041                     var exportOrLocalSymbol = getExportSymbolOfValueSymbolIfExported(result);
45042                     if (exportOrLocalSymbol.flags & 2 /* BlockScopedVariable */ || exportOrLocalSymbol.flags & 32 /* Class */ || exportOrLocalSymbol.flags & 384 /* Enum */) {
45043                         checkResolvedBlockScopedVariable(exportOrLocalSymbol, errorLocation);
45044                     }
45045                 }
45046                 // If we're in an external module, we can't reference value symbols created from UMD export declarations
45047                 if (result && isInExternalModule && (meaning & 111551 /* Value */) === 111551 /* Value */ && !(originalLocation.flags & 4194304 /* JSDoc */)) {
45048                     var merged = getMergedSymbol(result);
45049                     if (ts.length(merged.declarations) && ts.every(merged.declarations, function (d) { return ts.isNamespaceExportDeclaration(d) || ts.isSourceFile(d) && !!d.symbol.globalExports; })) {
45050                         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));
45051                     }
45052                 }
45053                 // 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
45054                 if (result && associatedDeclarationForContainingInitializerOrBindingName && !withinDeferredContext && (meaning & 111551 /* Value */) === 111551 /* Value */) {
45055                     var candidate = getMergedSymbol(getLateBoundSymbol(result));
45056                     var root = ts.getRootDeclaration(associatedDeclarationForContainingInitializerOrBindingName);
45057                     // A parameter initializer or binding pattern initializer within a parameter cannot refer to itself
45058                     if (candidate === getSymbolOfNode(associatedDeclarationForContainingInitializerOrBindingName)) {
45059                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_itself, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name));
45060                     }
45061                     // And it cannot refer to any declarations which come after it
45062                     else if (candidate.valueDeclaration && candidate.valueDeclaration.pos > associatedDeclarationForContainingInitializerOrBindingName.pos && root.parent.locals && lookup(root.parent.locals, candidate.escapedName, meaning) === candidate) {
45063                         error(errorLocation, ts.Diagnostics.Parameter_0_cannot_reference_identifier_1_declared_after_it, ts.declarationNameToString(associatedDeclarationForContainingInitializerOrBindingName.name), ts.declarationNameToString(errorLocation));
45064                     }
45065                 }
45066                 if (result && errorLocation && meaning & 111551 /* Value */ && result.flags & 2097152 /* Alias */) {
45067                     checkSymbolUsageInExpressionContext(result, name, errorLocation);
45068                 }
45069             }
45070             return result;
45071         }
45072         function checkSymbolUsageInExpressionContext(symbol, name, useSite) {
45073             if (!ts.isValidTypeOnlyAliasUseSite(useSite)) {
45074                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(symbol);
45075                 if (typeOnlyDeclaration) {
45076                     var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
45077                     var message = isExport
45078                         ? ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_exported_using_export_type
45079                         : ts.Diagnostics._0_cannot_be_used_as_a_value_because_it_was_imported_using_import_type;
45080                     var relatedMessage = isExport
45081                         ? ts.Diagnostics._0_was_exported_here
45082                         : ts.Diagnostics._0_was_imported_here;
45083                     var unescapedName = ts.unescapeLeadingUnderscores(name);
45084                     ts.addRelatedInfo(error(useSite, message, unescapedName), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, unescapedName));
45085                 }
45086             }
45087         }
45088         function getIsDeferredContext(location, lastLocation) {
45089             if (location.kind !== 209 /* ArrowFunction */ && location.kind !== 208 /* FunctionExpression */) {
45090                 // initializers in instance property declaration of class like entities are executed in constructor and thus deferred
45091                 return ts.isTypeQueryNode(location) || ((ts.isFunctionLikeDeclaration(location) ||
45092                     (location.kind === 163 /* PropertyDeclaration */ && !ts.hasSyntacticModifier(location, 32 /* Static */))) && (!lastLocation || lastLocation !== location.name)); // A name is evaluated within the enclosing scope - so it shouldn't count as deferred
45093             }
45094             if (lastLocation && lastLocation === location.name) {
45095                 return false;
45096             }
45097             // generator functions and async functions are not inlined in control flow when immediately invoked
45098             if (location.asteriskToken || ts.hasSyntacticModifier(location, 256 /* Async */)) {
45099                 return true;
45100             }
45101             return !ts.getImmediatelyInvokedFunctionExpression(location);
45102         }
45103         function isSelfReferenceLocation(node) {
45104             switch (node.kind) {
45105                 case 251 /* FunctionDeclaration */:
45106                 case 252 /* ClassDeclaration */:
45107                 case 253 /* InterfaceDeclaration */:
45108                 case 255 /* EnumDeclaration */:
45109                 case 254 /* TypeAliasDeclaration */:
45110                 case 256 /* ModuleDeclaration */: // For `namespace N { N; }`
45111                     return true;
45112                 default:
45113                     return false;
45114             }
45115         }
45116         function diagnosticName(nameArg) {
45117             return ts.isString(nameArg) ? ts.unescapeLeadingUnderscores(nameArg) : ts.declarationNameToString(nameArg);
45118         }
45119         function isTypeParameterSymbolDeclaredInContainer(symbol, container) {
45120             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
45121                 var decl = _a[_i];
45122                 if (decl.kind === 159 /* TypeParameter */) {
45123                     var parent = ts.isJSDocTemplateTag(decl.parent) ? ts.getJSDocHost(decl.parent) : decl.parent;
45124                     if (parent === container) {
45125                         return !(ts.isJSDocTemplateTag(decl.parent) && ts.find(decl.parent.parent.tags, ts.isJSDocTypeAlias)); // TODO: GH#18217
45126                     }
45127                 }
45128             }
45129             return false;
45130         }
45131         function checkAndReportErrorForMissingPrefix(errorLocation, name, nameArg) {
45132             if (!ts.isIdentifier(errorLocation) || errorLocation.escapedText !== name || isTypeReferenceIdentifier(errorLocation) || isInTypeQuery(errorLocation)) {
45133                 return false;
45134             }
45135             var container = ts.getThisContainer(errorLocation, /*includeArrowFunctions*/ false);
45136             var location = container;
45137             while (location) {
45138                 if (ts.isClassLike(location.parent)) {
45139                     var classSymbol = getSymbolOfNode(location.parent);
45140                     if (!classSymbol) {
45141                         break;
45142                     }
45143                     // Check to see if a static member exists.
45144                     var constructorType = getTypeOfSymbol(classSymbol);
45145                     if (getPropertyOfType(constructorType, name)) {
45146                         error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_static_member_1_0, diagnosticName(nameArg), symbolToString(classSymbol));
45147                         return true;
45148                     }
45149                     // No static member is present.
45150                     // Check if we're in an instance method and look for a relevant instance member.
45151                     if (location === container && !ts.hasSyntacticModifier(location, 32 /* Static */)) {
45152                         var instanceType = getDeclaredTypeOfSymbol(classSymbol).thisType; // TODO: GH#18217
45153                         if (getPropertyOfType(instanceType, name)) {
45154                             error(errorLocation, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_the_instance_member_this_0, diagnosticName(nameArg));
45155                             return true;
45156                         }
45157                     }
45158                 }
45159                 location = location.parent;
45160             }
45161             return false;
45162         }
45163         function checkAndReportErrorForExtendingInterface(errorLocation) {
45164             var expression = getEntityNameForExtendingInterface(errorLocation);
45165             if (expression && resolveEntityName(expression, 64 /* Interface */, /*ignoreErrors*/ true)) {
45166                 error(errorLocation, ts.Diagnostics.Cannot_extend_an_interface_0_Did_you_mean_implements, ts.getTextOfNode(expression));
45167                 return true;
45168             }
45169             return false;
45170         }
45171         /**
45172          * Climbs up parents to an ExpressionWithTypeArguments, and returns its expression,
45173          * but returns undefined if that expression is not an EntityNameExpression.
45174          */
45175         function getEntityNameForExtendingInterface(node) {
45176             switch (node.kind) {
45177                 case 78 /* Identifier */:
45178                 case 201 /* PropertyAccessExpression */:
45179                     return node.parent ? getEntityNameForExtendingInterface(node.parent) : undefined;
45180                 case 223 /* ExpressionWithTypeArguments */:
45181                     if (ts.isEntityNameExpression(node.expression)) {
45182                         return node.expression;
45183                     }
45184                 // falls through
45185                 default:
45186                     return undefined;
45187             }
45188         }
45189         function checkAndReportErrorForUsingTypeAsNamespace(errorLocation, name, meaning) {
45190             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(errorLocation) ? 111551 /* Value */ : 0);
45191             if (meaning === namespaceMeaning) {
45192                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~namespaceMeaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45193                 var parent = errorLocation.parent;
45194                 if (symbol) {
45195                     if (ts.isQualifiedName(parent)) {
45196                         ts.Debug.assert(parent.left === errorLocation, "Should only be resolving left side of qualified name as a namespace");
45197                         var propName = parent.right.escapedText;
45198                         var propType = getPropertyOfType(getDeclaredTypeOfSymbol(symbol), propName);
45199                         if (propType) {
45200                             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));
45201                             return true;
45202                         }
45203                     }
45204                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_namespace_here, ts.unescapeLeadingUnderscores(name));
45205                     return true;
45206                 }
45207             }
45208             return false;
45209         }
45210         function checkAndReportErrorForUsingValueAsType(errorLocation, name, meaning) {
45211             if (meaning & (788968 /* Type */ & ~1920 /* Namespace */)) {
45212                 var symbol = resolveSymbol(resolveName(errorLocation, name, ~788968 /* Type */ & 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45213                 if (symbol && !(symbol.flags & 1920 /* Namespace */)) {
45214                     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));
45215                     return true;
45216                 }
45217             }
45218             return false;
45219         }
45220         function isPrimitiveTypeName(name) {
45221             return name === "any" || name === "string" || name === "number" || name === "boolean" || name === "never" || name === "unknown";
45222         }
45223         function checkAndReportErrorForExportingPrimitiveType(errorLocation, name) {
45224             if (isPrimitiveTypeName(name) && errorLocation.parent.kind === 270 /* ExportSpecifier */) {
45225                 error(errorLocation, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, name);
45226                 return true;
45227             }
45228             return false;
45229         }
45230         function checkAndReportErrorForUsingTypeAsValue(errorLocation, name, meaning) {
45231             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */)) {
45232                 if (isPrimitiveTypeName(name)) {
45233                     error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, ts.unescapeLeadingUnderscores(name));
45234                     return true;
45235                 }
45236                 var symbol = resolveSymbol(resolveName(errorLocation, name, 788968 /* Type */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45237                 if (symbol && !(symbol.flags & 1024 /* NamespaceModule */)) {
45238                     var rawName = ts.unescapeLeadingUnderscores(name);
45239                     if (isES2015OrLaterConstructorName(name)) {
45240                         error(errorLocation, 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, rawName);
45241                     }
45242                     else if (maybeMappedType(errorLocation, symbol)) {
45243                         error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here_Did_you_mean_to_use_1_in_0, rawName, rawName === "K" ? "P" : "K");
45244                     }
45245                     else {
45246                         error(errorLocation, ts.Diagnostics._0_only_refers_to_a_type_but_is_being_used_as_a_value_here, rawName);
45247                     }
45248                     return true;
45249                 }
45250             }
45251             return false;
45252         }
45253         function maybeMappedType(node, symbol) {
45254             var container = ts.findAncestor(node.parent, function (n) {
45255                 return ts.isComputedPropertyName(n) || ts.isPropertySignature(n) ? false : ts.isTypeLiteralNode(n) || "quit";
45256             });
45257             if (container && container.members.length === 1) {
45258                 var type = getDeclaredTypeOfSymbol(symbol);
45259                 return !!(type.flags & 1048576 /* Union */) && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true);
45260             }
45261             return false;
45262         }
45263         function isES2015OrLaterConstructorName(n) {
45264             switch (n) {
45265                 case "Promise":
45266                 case "Symbol":
45267                 case "Map":
45268                 case "WeakMap":
45269                 case "Set":
45270                 case "WeakSet":
45271                     return true;
45272             }
45273             return false;
45274         }
45275         function checkAndReportErrorForUsingNamespaceModuleAsValue(errorLocation, name, meaning) {
45276             if (meaning & (111551 /* Value */ & ~1024 /* NamespaceModule */ & ~788968 /* Type */)) {
45277                 var symbol = resolveSymbol(resolveName(errorLocation, name, 1024 /* NamespaceModule */ & ~111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45278                 if (symbol) {
45279                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_value, ts.unescapeLeadingUnderscores(name));
45280                     return true;
45281                 }
45282             }
45283             else if (meaning & (788968 /* Type */ & ~1024 /* NamespaceModule */ & ~111551 /* Value */)) {
45284                 var symbol = resolveSymbol(resolveName(errorLocation, name, (512 /* ValueModule */ | 1024 /* NamespaceModule */) & ~788968 /* Type */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false));
45285                 if (symbol) {
45286                     error(errorLocation, ts.Diagnostics.Cannot_use_namespace_0_as_a_type, ts.unescapeLeadingUnderscores(name));
45287                     return true;
45288                 }
45289             }
45290             return false;
45291         }
45292         function checkResolvedBlockScopedVariable(result, errorLocation) {
45293             ts.Debug.assert(!!(result.flags & 2 /* BlockScopedVariable */ || result.flags & 32 /* Class */ || result.flags & 384 /* Enum */));
45294             if (result.flags & (16 /* Function */ | 1 /* FunctionScopedVariable */ | 67108864 /* Assignment */) && result.flags & 32 /* Class */) {
45295                 // constructor functions aren't block scoped
45296                 return;
45297             }
45298             // Block-scoped variables cannot be used before their definition
45299             var declaration = ts.find(result.declarations, function (d) { return ts.isBlockOrCatchScoped(d) || ts.isClassLike(d) || (d.kind === 255 /* EnumDeclaration */); });
45300             if (declaration === undefined)
45301                 return ts.Debug.fail("checkResolvedBlockScopedVariable could not find block-scoped declaration");
45302             if (!(declaration.flags & 8388608 /* Ambient */) && !isBlockScopedNameDeclaredBeforeUse(declaration, errorLocation)) {
45303                 var diagnosticMessage = void 0;
45304                 var declarationName = ts.declarationNameToString(ts.getNameOfDeclaration(declaration));
45305                 if (result.flags & 2 /* BlockScopedVariable */) {
45306                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Block_scoped_variable_0_used_before_its_declaration, declarationName);
45307                 }
45308                 else if (result.flags & 32 /* Class */) {
45309                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
45310                 }
45311                 else if (result.flags & 256 /* RegularEnum */) {
45312                     diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
45313                 }
45314                 else {
45315                     ts.Debug.assert(!!(result.flags & 128 /* ConstEnum */));
45316                     if (compilerOptions.preserveConstEnums) {
45317                         diagnosticMessage = error(errorLocation, ts.Diagnostics.Enum_0_used_before_its_declaration, declarationName);
45318                     }
45319                 }
45320                 if (diagnosticMessage) {
45321                     ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_is_declared_here, declarationName));
45322                 }
45323             }
45324         }
45325         /* Starting from 'initial' node walk up the parent chain until 'stopAt' node is reached.
45326          * If at any point current node is equal to 'parent' node - return true.
45327          * Return false if 'stopAt' node is reached or isFunctionLike(current) === true.
45328          */
45329         function isSameScopeDescendentOf(initial, parent, stopAt) {
45330             return !!parent && !!ts.findAncestor(initial, function (n) { return n === stopAt || ts.isFunctionLike(n) ? "quit" : n === parent; });
45331         }
45332         function getAnyImportSyntax(node) {
45333             switch (node.kind) {
45334                 case 260 /* ImportEqualsDeclaration */:
45335                     return node;
45336                 case 262 /* ImportClause */:
45337                     return node.parent;
45338                 case 263 /* NamespaceImport */:
45339                     return node.parent.parent;
45340                 case 265 /* ImportSpecifier */:
45341                     return node.parent.parent.parent;
45342                 default:
45343                     return undefined;
45344             }
45345         }
45346         function getDeclarationOfAliasSymbol(symbol) {
45347             return ts.find(symbol.declarations, isAliasSymbolDeclaration);
45348         }
45349         /**
45350          * An alias symbol is created by one of the following declarations:
45351          * import <symbol> = ...
45352          * import <symbol> from ...
45353          * import * as <symbol> from ...
45354          * import { x as <symbol> } from ...
45355          * export { x as <symbol> } from ...
45356          * export * as ns <symbol> from ...
45357          * export = <EntityNameExpression>
45358          * export default <EntityNameExpression>
45359          * module.exports = <EntityNameExpression>
45360          * {<Identifier>}
45361          * {name: <EntityNameExpression>}
45362          */
45363         function isAliasSymbolDeclaration(node) {
45364             return node.kind === 260 /* ImportEqualsDeclaration */
45365                 || node.kind === 259 /* NamespaceExportDeclaration */
45366                 || node.kind === 262 /* ImportClause */ && !!node.name
45367                 || node.kind === 263 /* NamespaceImport */
45368                 || node.kind === 269 /* NamespaceExport */
45369                 || node.kind === 265 /* ImportSpecifier */
45370                 || node.kind === 270 /* ExportSpecifier */
45371                 || node.kind === 266 /* ExportAssignment */ && ts.exportAssignmentIsAlias(node)
45372                 || ts.isBinaryExpression(node) && ts.getAssignmentDeclarationKind(node) === 2 /* ModuleExports */ && ts.exportAssignmentIsAlias(node)
45373                 || ts.isAccessExpression(node)
45374                     && ts.isBinaryExpression(node.parent)
45375                     && node.parent.left === node
45376                     && node.parent.operatorToken.kind === 62 /* EqualsToken */
45377                     && isAliasableOrJsExpression(node.parent.right)
45378                 || node.kind === 289 /* ShorthandPropertyAssignment */
45379                 || node.kind === 288 /* PropertyAssignment */ && isAliasableOrJsExpression(node.initializer)
45380                 || ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true);
45381         }
45382         function isAliasableOrJsExpression(e) {
45383             return ts.isAliasableExpression(e) || ts.isFunctionExpression(e) && isJSConstructor(e);
45384         }
45385         function getTargetOfImportEqualsDeclaration(node, dontResolveAlias) {
45386             var commonJSPropertyAccess = getCommonJSPropertyAccess(node);
45387             if (commonJSPropertyAccess) {
45388                 var name = ts.getLeftmostAccessExpression(commonJSPropertyAccess.expression).arguments[0];
45389                 return ts.isIdentifier(commonJSPropertyAccess.name)
45390                     ? resolveSymbol(getPropertyOfType(resolveExternalModuleTypeByLiteral(name), commonJSPropertyAccess.name.escapedText))
45391                     : undefined;
45392             }
45393             if (ts.isVariableDeclaration(node) || node.moduleReference.kind === 272 /* ExternalModuleReference */) {
45394                 var immediate = resolveExternalModuleName(node, ts.getExternalModuleRequireArgument(node) || ts.getExternalModuleImportEqualsDeclarationExpression(node));
45395                 var resolved_4 = resolveExternalModuleSymbol(immediate);
45396                 markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved_4, /*overwriteEmpty*/ false);
45397                 return resolved_4;
45398             }
45399             var resolved = getSymbolOfPartOfRightHandSideOfImportEquals(node.moduleReference, dontResolveAlias);
45400             checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved);
45401             return resolved;
45402         }
45403         function checkAndReportErrorForResolvingImportAliasToTypeOnlySymbol(node, resolved) {
45404             if (markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false)) {
45405                 var typeOnlyDeclaration = getTypeOnlyAliasDeclaration(getSymbolOfNode(node));
45406                 var isExport = ts.typeOnlyDeclarationIsExport(typeOnlyDeclaration);
45407                 var message = isExport
45408                     ? ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_exported_using_export_type
45409                     : ts.Diagnostics.An_import_alias_cannot_reference_a_declaration_that_was_imported_using_import_type;
45410                 var relatedMessage = isExport
45411                     ? ts.Diagnostics._0_was_exported_here
45412                     : ts.Diagnostics._0_was_imported_here;
45413                 // Non-null assertion is safe because the optionality comes from ImportClause,
45414                 // but if an ImportClause was the typeOnlyDeclaration, it had to have a `name`.
45415                 var name = ts.unescapeLeadingUnderscores(typeOnlyDeclaration.name.escapedText);
45416                 ts.addRelatedInfo(error(node.moduleReference, message), ts.createDiagnosticForNode(typeOnlyDeclaration, relatedMessage, name));
45417             }
45418         }
45419         function resolveExportByName(moduleSymbol, name, sourceNode, dontResolveAlias) {
45420             var exportValue = moduleSymbol.exports.get("export=" /* ExportEquals */);
45421             var exportSymbol = exportValue ? getPropertyOfType(getTypeOfSymbol(exportValue), name) : moduleSymbol.exports.get(name);
45422             var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
45423             markSymbolOfAliasDeclarationIfTypeOnly(sourceNode, exportSymbol, resolved, /*overwriteEmpty*/ false);
45424             return resolved;
45425         }
45426         function isSyntacticDefault(node) {
45427             return ((ts.isExportAssignment(node) && !node.isExportEquals) || ts.hasSyntacticModifier(node, 512 /* Default */) || ts.isExportSpecifier(node));
45428         }
45429         function canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias) {
45430             if (!allowSyntheticDefaultImports) {
45431                 return false;
45432             }
45433             // Declaration files (and ambient modules)
45434             if (!file || file.isDeclarationFile) {
45435                 // Definitely cannot have a synthetic default if they have a syntactic default member specified
45436                 var defaultExportSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, /*sourceNode*/ undefined, /*dontResolveAlias*/ true); // Dont resolve alias because we want the immediately exported symbol's declaration
45437                 if (defaultExportSymbol && ts.some(defaultExportSymbol.declarations, isSyntacticDefault)) {
45438                     return false;
45439                 }
45440                 // It _might_ still be incorrect to assume there is no __esModule marker on the import at runtime, even if there is no `default` member
45441                 // So we check a bit more,
45442                 if (resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias)) {
45443                     // If there is an `__esModule` specified in the declaration (meaning someone explicitly added it or wrote it in their code),
45444                     // it definitely is a module and does not have a synthetic default
45445                     return false;
45446                 }
45447                 // There are _many_ declaration files not written with esmodules in mind that still get compiled into a format with __esModule set
45448                 // Meaning there may be no default at runtime - however to be on the permissive side, we allow access to a synthetic default member
45449                 // as there is no marker to indicate if the accompanying JS has `__esModule` or not, or is even native esm
45450                 return true;
45451             }
45452             // TypeScript files never have a synthetic default (as they are always emitted with an __esModule marker) _unless_ they contain an export= statement
45453             if (!ts.isSourceFileJS(file)) {
45454                 return hasExportAssignmentSymbol(moduleSymbol);
45455             }
45456             // 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
45457             return !file.externalModuleIndicator && !resolveExportByName(moduleSymbol, ts.escapeLeadingUnderscores("__esModule"), /*sourceNode*/ undefined, dontResolveAlias);
45458         }
45459         function getTargetOfImportClause(node, dontResolveAlias) {
45460             var moduleSymbol = resolveExternalModuleName(node, node.parent.moduleSpecifier);
45461             if (moduleSymbol) {
45462                 var exportDefaultSymbol = void 0;
45463                 if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
45464                     exportDefaultSymbol = moduleSymbol;
45465                 }
45466                 else {
45467                     exportDefaultSymbol = resolveExportByName(moduleSymbol, "default" /* Default */, node, dontResolveAlias);
45468                 }
45469                 var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
45470                 var hasSyntheticDefault = canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias);
45471                 if (!exportDefaultSymbol && !hasSyntheticDefault) {
45472                     if (hasExportAssignmentSymbol(moduleSymbol)) {
45473                         var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015 ? "allowSyntheticDefaultImports" : "esModuleInterop";
45474                         var exportEqualsSymbol = moduleSymbol.exports.get("export=" /* ExportEquals */);
45475                         var exportAssignment = exportEqualsSymbol.valueDeclaration;
45476                         var err = error(node.name, ts.Diagnostics.Module_0_can_only_be_default_imported_using_the_1_flag, symbolToString(moduleSymbol), compilerOptionName);
45477                         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));
45478                     }
45479                     else {
45480                         reportNonDefaultExport(moduleSymbol, node);
45481                     }
45482                 }
45483                 else if (hasSyntheticDefault) {
45484                     // per emit behavior, a synthetic default overrides a "real" .default member if `__esModule` is not present
45485                     var resolved = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
45486                     markSymbolOfAliasDeclarationIfTypeOnly(node, moduleSymbol, resolved, /*overwriteTypeOnly*/ false);
45487                     return resolved;
45488                 }
45489                 markSymbolOfAliasDeclarationIfTypeOnly(node, exportDefaultSymbol, /*finalTarget*/ undefined, /*overwriteTypeOnly*/ false);
45490                 return exportDefaultSymbol;
45491             }
45492         }
45493         function reportNonDefaultExport(moduleSymbol, node) {
45494             var _a, _b;
45495             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has(node.symbol.escapedName)) {
45496                 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));
45497             }
45498             else {
45499                 var diagnostic = error(node.name, ts.Diagnostics.Module_0_has_no_default_export, symbolToString(moduleSymbol));
45500                 var exportStar = (_b = moduleSymbol.exports) === null || _b === void 0 ? void 0 : _b.get("__export" /* ExportStar */);
45501                 if (exportStar) {
45502                     var defaultExport = ts.find(exportStar.declarations, function (decl) {
45503                         var _a, _b;
45504                         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 */)));
45505                     });
45506                     if (defaultExport) {
45507                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(defaultExport, ts.Diagnostics.export_Asterisk_does_not_re_export_a_default));
45508                     }
45509                 }
45510             }
45511         }
45512         function getTargetOfNamespaceImport(node, dontResolveAlias) {
45513             var moduleSpecifier = node.parent.parent.moduleSpecifier;
45514             var immediate = resolveExternalModuleName(node, moduleSpecifier);
45515             var resolved = resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
45516             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
45517             return resolved;
45518         }
45519         function getTargetOfNamespaceExport(node, dontResolveAlias) {
45520             var moduleSpecifier = node.parent.moduleSpecifier;
45521             var immediate = moduleSpecifier && resolveExternalModuleName(node, moduleSpecifier);
45522             var resolved = moduleSpecifier && resolveESModuleSymbol(immediate, moduleSpecifier, dontResolveAlias, /*suppressUsageError*/ false);
45523             markSymbolOfAliasDeclarationIfTypeOnly(node, immediate, resolved, /*overwriteEmpty*/ false);
45524             return resolved;
45525         }
45526         // This function creates a synthetic symbol that combines the value side of one symbol with the
45527         // type/namespace side of another symbol. Consider this example:
45528         //
45529         //   declare module graphics {
45530         //       interface Point {
45531         //           x: number;
45532         //           y: number;
45533         //       }
45534         //   }
45535         //   declare var graphics: {
45536         //       Point: new (x: number, y: number) => graphics.Point;
45537         //   }
45538         //   declare module "graphics" {
45539         //       export = graphics;
45540         //   }
45541         //
45542         // An 'import { Point } from "graphics"' needs to create a symbol that combines the value side 'Point'
45543         // property with the type/namespace side interface 'Point'.
45544         function combineValueAndTypeSymbols(valueSymbol, typeSymbol) {
45545             if (valueSymbol === unknownSymbol && typeSymbol === unknownSymbol) {
45546                 return unknownSymbol;
45547             }
45548             if (valueSymbol.flags & (788968 /* Type */ | 1920 /* Namespace */)) {
45549                 return valueSymbol;
45550             }
45551             var result = createSymbol(valueSymbol.flags | typeSymbol.flags, valueSymbol.escapedName);
45552             result.declarations = ts.deduplicate(ts.concatenate(valueSymbol.declarations, typeSymbol.declarations), ts.equateValues);
45553             result.parent = valueSymbol.parent || typeSymbol.parent;
45554             if (valueSymbol.valueDeclaration)
45555                 result.valueDeclaration = valueSymbol.valueDeclaration;
45556             if (typeSymbol.members)
45557                 result.members = new ts.Map(typeSymbol.members);
45558             if (valueSymbol.exports)
45559                 result.exports = new ts.Map(valueSymbol.exports);
45560             return result;
45561         }
45562         function getExportOfModule(symbol, name, specifier, dontResolveAlias) {
45563             if (symbol.flags & 1536 /* Module */) {
45564                 var exportSymbol = getExportsOfSymbol(symbol).get(name.escapedText);
45565                 var resolved = resolveSymbol(exportSymbol, dontResolveAlias);
45566                 markSymbolOfAliasDeclarationIfTypeOnly(specifier, exportSymbol, resolved, /*overwriteEmpty*/ false);
45567                 return resolved;
45568             }
45569         }
45570         function getPropertyOfVariable(symbol, name) {
45571             if (symbol.flags & 3 /* Variable */) {
45572                 var typeAnnotation = symbol.valueDeclaration.type;
45573                 if (typeAnnotation) {
45574                     return resolveSymbol(getPropertyOfType(getTypeFromTypeNode(typeAnnotation), name));
45575                 }
45576             }
45577         }
45578         function getExternalModuleMember(node, specifier, dontResolveAlias) {
45579             var _a;
45580             if (dontResolveAlias === void 0) { dontResolveAlias = false; }
45581             var moduleSpecifier = ts.getExternalModuleRequireArgument(node) || node.moduleSpecifier;
45582             var moduleSymbol = resolveExternalModuleName(node, moduleSpecifier); // TODO: GH#18217
45583             var name = !ts.isPropertyAccessExpression(specifier) && specifier.propertyName || specifier.name;
45584             if (!ts.isIdentifier(name)) {
45585                 return undefined;
45586             }
45587             var suppressInteropError = name.escapedText === "default" /* Default */ && !!(compilerOptions.allowSyntheticDefaultImports || compilerOptions.esModuleInterop);
45588             var targetSymbol = resolveESModuleSymbol(moduleSymbol, moduleSpecifier, dontResolveAlias, suppressInteropError);
45589             if (targetSymbol) {
45590                 if (name.escapedText) {
45591                     if (ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
45592                         return moduleSymbol;
45593                     }
45594                     var symbolFromVariable = void 0;
45595                     // First check if module was specified with "export=". If so, get the member from the resolved type
45596                     if (moduleSymbol && moduleSymbol.exports && moduleSymbol.exports.get("export=" /* ExportEquals */)) {
45597                         symbolFromVariable = getPropertyOfType(getTypeOfSymbol(targetSymbol), name.escapedText);
45598                     }
45599                     else {
45600                         symbolFromVariable = getPropertyOfVariable(targetSymbol, name.escapedText);
45601                     }
45602                     // if symbolFromVariable is export - get its final target
45603                     symbolFromVariable = resolveSymbol(symbolFromVariable, dontResolveAlias);
45604                     var symbolFromModule = getExportOfModule(targetSymbol, name, specifier, dontResolveAlias);
45605                     if (symbolFromModule === undefined && name.escapedText === "default" /* Default */) {
45606                         var file = ts.find(moduleSymbol.declarations, ts.isSourceFile);
45607                         if (canHaveSyntheticDefault(file, moduleSymbol, dontResolveAlias)) {
45608                             symbolFromModule = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) || resolveSymbol(moduleSymbol, dontResolveAlias);
45609                         }
45610                     }
45611                     var symbol = symbolFromModule && symbolFromVariable && symbolFromModule !== symbolFromVariable ?
45612                         combineValueAndTypeSymbols(symbolFromVariable, symbolFromModule) :
45613                         symbolFromModule || symbolFromVariable;
45614                     if (!symbol) {
45615                         var moduleName = getFullyQualifiedName(moduleSymbol, node);
45616                         var declarationName = ts.declarationNameToString(name);
45617                         var suggestion = getSuggestedSymbolForNonexistentModule(name, targetSymbol);
45618                         if (suggestion !== undefined) {
45619                             var suggestionName = symbolToString(suggestion);
45620                             var diagnostic = error(name, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, moduleName, declarationName, suggestionName);
45621                             if (suggestion.valueDeclaration) {
45622                                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestionName));
45623                             }
45624                         }
45625                         else {
45626                             if ((_a = moduleSymbol.exports) === null || _a === void 0 ? void 0 : _a.has("default" /* Default */)) {
45627                                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1_Did_you_mean_to_use_import_1_from_0_instead, moduleName, declarationName);
45628                             }
45629                             else {
45630                                 reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName);
45631                             }
45632                         }
45633                     }
45634                     return symbol;
45635                 }
45636             }
45637         }
45638         function reportNonExportedMember(node, name, declarationName, moduleSymbol, moduleName) {
45639             var _a;
45640             var localSymbol = (_a = moduleSymbol.valueDeclaration.locals) === null || _a === void 0 ? void 0 : _a.get(name.escapedText);
45641             var exports = moduleSymbol.exports;
45642             if (localSymbol) {
45643                 var exportedEqualsSymbol = exports === null || exports === void 0 ? void 0 : exports.get("export=" /* ExportEquals */);
45644                 if (exportedEqualsSymbol) {
45645                     getSymbolIfSameReference(exportedEqualsSymbol, localSymbol) ? reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) :
45646                         error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
45647                 }
45648                 else {
45649                     var exportedSymbol = exports ? ts.find(symbolsToArray(exports), function (symbol) { return !!getSymbolIfSameReference(symbol, localSymbol); }) : undefined;
45650                     var diagnostic = exportedSymbol ? error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_exported_as_2, moduleName, declarationName, symbolToString(exportedSymbol)) :
45651                         error(name, ts.Diagnostics.Module_0_declares_1_locally_but_it_is_not_exported, moduleName, declarationName);
45652                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diagnostic], ts.map(localSymbol.declarations, function (decl, index) {
45653                         return ts.createDiagnosticForNode(decl, index === 0 ? ts.Diagnostics._0_is_declared_here : ts.Diagnostics.and_here, declarationName);
45654                     })));
45655                 }
45656             }
45657             else {
45658                 error(name, ts.Diagnostics.Module_0_has_no_exported_member_1, moduleName, declarationName);
45659             }
45660         }
45661         function reportInvalidImportEqualsExportMember(node, name, declarationName, moduleName) {
45662             if (moduleKind >= ts.ModuleKind.ES2015) {
45663                 var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_default_import :
45664                     ts.Diagnostics._0_can_only_be_imported_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
45665                 error(name, message, declarationName);
45666             }
45667             else {
45668                 if (ts.isInJSFile(node)) {
45669                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_using_a_default_import :
45670                         ts.Diagnostics._0_can_only_be_imported_by_using_a_require_call_or_by_turning_on_the_esModuleInterop_flag_and_using_a_default_import;
45671                     error(name, message, declarationName);
45672                 }
45673                 else {
45674                     var message = compilerOptions.esModuleInterop ? ts.Diagnostics._0_can_only_be_imported_by_using_import_1_require_2_or_a_default_import :
45675                         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;
45676                     error(name, message, declarationName, declarationName, moduleName);
45677                 }
45678             }
45679         }
45680         function getTargetOfImportSpecifier(node, dontResolveAlias) {
45681             var root = ts.isBindingElement(node) ? ts.getRootDeclaration(node) : node.parent.parent.parent;
45682             var commonJSPropertyAccess = getCommonJSPropertyAccess(root);
45683             var resolved = getExternalModuleMember(root, commonJSPropertyAccess || node, dontResolveAlias);
45684             var name = node.propertyName || node.name;
45685             if (commonJSPropertyAccess && resolved && ts.isIdentifier(name)) {
45686                 return getPropertyOfType(getTypeOfSymbol(resolved), name.escapedText);
45687             }
45688             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
45689             return resolved;
45690         }
45691         function getCommonJSPropertyAccess(node) {
45692             if (ts.isVariableDeclaration(node) && node.initializer && ts.isPropertyAccessExpression(node.initializer)) {
45693                 return node.initializer;
45694             }
45695         }
45696         function getTargetOfNamespaceExportDeclaration(node, dontResolveAlias) {
45697             var resolved = resolveExternalModuleSymbol(node.parent.symbol, dontResolveAlias);
45698             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
45699             return resolved;
45700         }
45701         function getTargetOfExportSpecifier(node, meaning, dontResolveAlias) {
45702             var resolved = node.parent.parent.moduleSpecifier ?
45703                 getExternalModuleMember(node.parent.parent, node, dontResolveAlias) :
45704                 resolveEntityName(node.propertyName || node.name, meaning, /*ignoreErrors*/ false, dontResolveAlias);
45705             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
45706             return resolved;
45707         }
45708         function getTargetOfExportAssignment(node, dontResolveAlias) {
45709             var expression = ts.isExportAssignment(node) ? node.expression : node.right;
45710             var resolved = getTargetOfAliasLikeExpression(expression, dontResolveAlias);
45711             markSymbolOfAliasDeclarationIfTypeOnly(node, /*immediateTarget*/ undefined, resolved, /*overwriteEmpty*/ false);
45712             return resolved;
45713         }
45714         function getTargetOfAliasLikeExpression(expression, dontResolveAlias) {
45715             if (ts.isClassExpression(expression)) {
45716                 return checkExpressionCached(expression).symbol;
45717             }
45718             if (!ts.isEntityName(expression) && !ts.isEntityNameExpression(expression)) {
45719                 return undefined;
45720             }
45721             var aliasLike = resolveEntityName(expression, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontResolveAlias);
45722             if (aliasLike) {
45723                 return aliasLike;
45724             }
45725             checkExpressionCached(expression);
45726             return getNodeLinks(expression).resolvedSymbol;
45727         }
45728         function getTargetOfPropertyAssignment(node, dontRecursivelyResolve) {
45729             var expression = node.initializer;
45730             return getTargetOfAliasLikeExpression(expression, dontRecursivelyResolve);
45731         }
45732         function getTargetOfAccessExpression(node, dontRecursivelyResolve) {
45733             if (!(ts.isBinaryExpression(node.parent) && node.parent.left === node && node.parent.operatorToken.kind === 62 /* EqualsToken */)) {
45734                 return undefined;
45735             }
45736             return getTargetOfAliasLikeExpression(node.parent.right, dontRecursivelyResolve);
45737         }
45738         function getTargetOfAliasDeclaration(node, dontRecursivelyResolve) {
45739             if (dontRecursivelyResolve === void 0) { dontRecursivelyResolve = false; }
45740             switch (node.kind) {
45741                 case 260 /* ImportEqualsDeclaration */:
45742                 case 249 /* VariableDeclaration */:
45743                     return getTargetOfImportEqualsDeclaration(node, dontRecursivelyResolve);
45744                 case 262 /* ImportClause */:
45745                     return getTargetOfImportClause(node, dontRecursivelyResolve);
45746                 case 263 /* NamespaceImport */:
45747                     return getTargetOfNamespaceImport(node, dontRecursivelyResolve);
45748                 case 269 /* NamespaceExport */:
45749                     return getTargetOfNamespaceExport(node, dontRecursivelyResolve);
45750                 case 265 /* ImportSpecifier */:
45751                 case 198 /* BindingElement */:
45752                     return getTargetOfImportSpecifier(node, dontRecursivelyResolve);
45753                 case 270 /* ExportSpecifier */:
45754                     return getTargetOfExportSpecifier(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, dontRecursivelyResolve);
45755                 case 266 /* ExportAssignment */:
45756                 case 216 /* BinaryExpression */:
45757                     return getTargetOfExportAssignment(node, dontRecursivelyResolve);
45758                 case 259 /* NamespaceExportDeclaration */:
45759                     return getTargetOfNamespaceExportDeclaration(node, dontRecursivelyResolve);
45760                 case 289 /* ShorthandPropertyAssignment */:
45761                     return resolveEntityName(node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ true, dontRecursivelyResolve);
45762                 case 288 /* PropertyAssignment */:
45763                     return getTargetOfPropertyAssignment(node, dontRecursivelyResolve);
45764                 case 202 /* ElementAccessExpression */:
45765                 case 201 /* PropertyAccessExpression */:
45766                     return getTargetOfAccessExpression(node, dontRecursivelyResolve);
45767                 default:
45768                     return ts.Debug.fail();
45769             }
45770         }
45771         /**
45772          * Indicates that a symbol is an alias that does not merge with a local declaration.
45773          * OR Is a JSContainer which may merge an alias with a local declaration
45774          */
45775         function isNonLocalAlias(symbol, excludes) {
45776             if (excludes === void 0) { excludes = 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */; }
45777             if (!symbol)
45778                 return false;
45779             return (symbol.flags & (2097152 /* Alias */ | excludes)) === 2097152 /* Alias */ || !!(symbol.flags & 2097152 /* Alias */ && symbol.flags & 67108864 /* Assignment */);
45780         }
45781         function resolveSymbol(symbol, dontResolveAlias) {
45782             return !dontResolveAlias && isNonLocalAlias(symbol) ? resolveAlias(symbol) : symbol;
45783         }
45784         function resolveAlias(symbol) {
45785             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
45786             var links = getSymbolLinks(symbol);
45787             if (!links.target) {
45788                 links.target = resolvingSymbol;
45789                 var node = getDeclarationOfAliasSymbol(symbol);
45790                 if (!node)
45791                     return ts.Debug.fail();
45792                 var target = getTargetOfAliasDeclaration(node);
45793                 if (links.target === resolvingSymbol) {
45794                     links.target = target || unknownSymbol;
45795                 }
45796                 else {
45797                     error(node, ts.Diagnostics.Circular_definition_of_import_alias_0, symbolToString(symbol));
45798                 }
45799             }
45800             else if (links.target === resolvingSymbol) {
45801                 links.target = unknownSymbol;
45802             }
45803             return links.target;
45804         }
45805         function tryResolveAlias(symbol) {
45806             var links = getSymbolLinks(symbol);
45807             if (links.target !== resolvingSymbol) {
45808                 return resolveAlias(symbol);
45809             }
45810             return undefined;
45811         }
45812         /**
45813          * Marks a symbol as type-only if its declaration is syntactically type-only.
45814          * If it is not itself marked type-only, but resolves to a type-only alias
45815          * somewhere in its resolution chain, save a reference to the type-only alias declaration
45816          * so the alias _not_ marked type-only can be identified as _transitively_ type-only.
45817          *
45818          * This function is called on each alias declaration that could be type-only or resolve to
45819          * another type-only alias during `resolveAlias`, so that later, when an alias is used in a
45820          * JS-emitting expression, we can quickly determine if that symbol is effectively type-only
45821          * and issue an error if so.
45822          *
45823          * @param aliasDeclaration The alias declaration not marked as type-only
45824          * has already been marked as not resolving to a type-only alias. Used when recursively resolving qualified
45825          * names of import aliases, e.g. `import C = a.b.C`. If namespace `a` is not found to be type-only, the
45826          * import declaration will initially be marked as not resolving to a type-only symbol. But, namespace `b`
45827          * must still be checked for a type-only marker, overwriting the previous negative result if found.
45828          * @param immediateTarget The symbol to which the alias declaration immediately resolves
45829          * @param finalTarget The symbol to which the alias declaration ultimately resolves
45830          * @param overwriteEmpty Checks `resolvesToSymbol` for type-only declarations even if `aliasDeclaration`
45831          */
45832         function markSymbolOfAliasDeclarationIfTypeOnly(aliasDeclaration, immediateTarget, finalTarget, overwriteEmpty) {
45833             if (!aliasDeclaration || ts.isPropertyAccessExpression(aliasDeclaration))
45834                 return false;
45835             // If the declaration itself is type-only, mark it and return.
45836             // No need to check what it resolves to.
45837             var sourceSymbol = getSymbolOfNode(aliasDeclaration);
45838             if (ts.isTypeOnlyImportOrExportDeclaration(aliasDeclaration)) {
45839                 var links_1 = getSymbolLinks(sourceSymbol);
45840                 links_1.typeOnlyDeclaration = aliasDeclaration;
45841                 return true;
45842             }
45843             var links = getSymbolLinks(sourceSymbol);
45844             return markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, immediateTarget, overwriteEmpty)
45845                 || markSymbolOfAliasDeclarationIfTypeOnlyWorker(links, finalTarget, overwriteEmpty);
45846         }
45847         function markSymbolOfAliasDeclarationIfTypeOnlyWorker(aliasDeclarationLinks, target, overwriteEmpty) {
45848             var _a, _b, _c;
45849             if (target && (aliasDeclarationLinks.typeOnlyDeclaration === undefined || overwriteEmpty && aliasDeclarationLinks.typeOnlyDeclaration === false)) {
45850                 var exportSymbol = (_b = (_a = target.exports) === null || _a === void 0 ? void 0 : _a.get("export=" /* ExportEquals */)) !== null && _b !== void 0 ? _b : target;
45851                 var typeOnly = exportSymbol.declarations && ts.find(exportSymbol.declarations, ts.isTypeOnlyImportOrExportDeclaration);
45852                 aliasDeclarationLinks.typeOnlyDeclaration = (_c = typeOnly !== null && typeOnly !== void 0 ? typeOnly : getSymbolLinks(exportSymbol).typeOnlyDeclaration) !== null && _c !== void 0 ? _c : false;
45853             }
45854             return !!aliasDeclarationLinks.typeOnlyDeclaration;
45855         }
45856         /** Indicates that a symbol directly or indirectly resolves to a type-only import or export. */
45857         function getTypeOnlyAliasDeclaration(symbol) {
45858             if (!(symbol.flags & 2097152 /* Alias */)) {
45859                 return undefined;
45860             }
45861             var links = getSymbolLinks(symbol);
45862             return links.typeOnlyDeclaration || undefined;
45863         }
45864         function markExportAsReferenced(node) {
45865             var symbol = getSymbolOfNode(node);
45866             var target = resolveAlias(symbol);
45867             if (target) {
45868                 var markAlias = target === unknownSymbol ||
45869                     ((target.flags & 111551 /* Value */) && !isConstEnumOrConstEnumOnlyModule(target) && !getTypeOnlyAliasDeclaration(symbol));
45870                 if (markAlias) {
45871                     markAliasSymbolAsReferenced(symbol);
45872                 }
45873             }
45874         }
45875         // When an alias symbol is referenced, we need to mark the entity it references as referenced and in turn repeat that until
45876         // we reach a non-alias or an exported entity (which is always considered referenced). We do this by checking the target of
45877         // the alias as an expression (which recursively takes us back here if the target references another alias).
45878         function markAliasSymbolAsReferenced(symbol) {
45879             var links = getSymbolLinks(symbol);
45880             if (!links.referenced) {
45881                 links.referenced = true;
45882                 var node = getDeclarationOfAliasSymbol(symbol);
45883                 if (!node)
45884                     return ts.Debug.fail();
45885                 // We defer checking of the reference of an `import =` until the import itself is referenced,
45886                 // This way a chain of imports can be elided if ultimately the final input is only used in a type
45887                 // position.
45888                 if (ts.isInternalModuleImportEqualsDeclaration(node)) {
45889                     var target = resolveSymbol(symbol);
45890                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
45891                         // import foo = <symbol>
45892                         checkExpressionCached(node.moduleReference);
45893                     }
45894                 }
45895             }
45896         }
45897         // Aliases that resolve to const enums are not marked as referenced because they are not emitted,
45898         // but their usage in value positions must be tracked to determine if the import can be type-only.
45899         function markConstEnumAliasAsReferenced(symbol) {
45900             var links = getSymbolLinks(symbol);
45901             if (!links.constEnumReferenced) {
45902                 links.constEnumReferenced = true;
45903             }
45904         }
45905         // This function is only for imports with entity names
45906         function getSymbolOfPartOfRightHandSideOfImportEquals(entityName, dontResolveAlias) {
45907             // There are three things we might try to look for. In the following examples,
45908             // the search term is enclosed in |...|:
45909             //
45910             //     import a = |b|; // Namespace
45911             //     import a = |b.c|; // Value, type, namespace
45912             //     import a = |b.c|.d; // Namespace
45913             if (entityName.kind === 78 /* Identifier */ && ts.isRightSideOfQualifiedNameOrPropertyAccess(entityName)) {
45914                 entityName = entityName.parent;
45915             }
45916             // Check for case 1 and 3 in the above example
45917             if (entityName.kind === 78 /* Identifier */ || entityName.parent.kind === 157 /* QualifiedName */) {
45918                 return resolveEntityName(entityName, 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
45919             }
45920             else {
45921                 // Case 2 in above example
45922                 // entityName.kind could be a QualifiedName or a Missing identifier
45923                 ts.Debug.assert(entityName.parent.kind === 260 /* ImportEqualsDeclaration */);
45924                 return resolveEntityName(entityName, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, /*ignoreErrors*/ false, dontResolveAlias);
45925             }
45926         }
45927         function getFullyQualifiedName(symbol, containingLocation) {
45928             return symbol.parent ? getFullyQualifiedName(symbol.parent, containingLocation) + "." + symbolToString(symbol) : symbolToString(symbol, containingLocation, /*meaning*/ undefined, 16 /* DoNotIncludeSymbolChain */ | 4 /* AllowAnyNodeKind */);
45929         }
45930         /**
45931          * Resolves a qualified name and any involved aliases.
45932          */
45933         function resolveEntityName(name, meaning, ignoreErrors, dontResolveAlias, location) {
45934             if (ts.nodeIsMissing(name)) {
45935                 return undefined;
45936             }
45937             var namespaceMeaning = 1920 /* Namespace */ | (ts.isInJSFile(name) ? meaning & 111551 /* Value */ : 0);
45938             var symbol;
45939             if (name.kind === 78 /* Identifier */) {
45940                 var message = meaning === namespaceMeaning || ts.nodeIsSynthesized(name) ? ts.Diagnostics.Cannot_find_namespace_0 : getCannotFindNameDiagnosticForName(ts.getFirstIdentifier(name));
45941                 var symbolFromJSPrototype = ts.isInJSFile(name) && !ts.nodeIsSynthesized(name) ? resolveEntityNameFromAssignmentDeclaration(name, meaning) : undefined;
45942                 symbol = getMergedSymbol(resolveName(location || name, name.escapedText, meaning, ignoreErrors || symbolFromJSPrototype ? undefined : message, name, /*isUse*/ true));
45943                 if (!symbol) {
45944                     return getMergedSymbol(symbolFromJSPrototype);
45945                 }
45946             }
45947             else if (name.kind === 157 /* QualifiedName */ || name.kind === 201 /* PropertyAccessExpression */) {
45948                 var left = name.kind === 157 /* QualifiedName */ ? name.left : name.expression;
45949                 var right = name.kind === 157 /* QualifiedName */ ? name.right : name.name;
45950                 var namespace = resolveEntityName(left, namespaceMeaning, ignoreErrors, /*dontResolveAlias*/ false, location);
45951                 if (!namespace || ts.nodeIsMissing(right)) {
45952                     return undefined;
45953                 }
45954                 else if (namespace === unknownSymbol) {
45955                     return namespace;
45956                 }
45957                 if (ts.isInJSFile(name)) {
45958                     if (namespace.valueDeclaration &&
45959                         ts.isVariableDeclaration(namespace.valueDeclaration) &&
45960                         namespace.valueDeclaration.initializer &&
45961                         isCommonJsRequire(namespace.valueDeclaration.initializer)) {
45962                         var moduleName = namespace.valueDeclaration.initializer.arguments[0];
45963                         var moduleSym = resolveExternalModuleName(moduleName, moduleName);
45964                         if (moduleSym) {
45965                             var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
45966                             if (resolvedModuleSymbol) {
45967                                 namespace = resolvedModuleSymbol;
45968                             }
45969                         }
45970                     }
45971                 }
45972                 symbol = getMergedSymbol(getSymbol(getExportsOfSymbol(namespace), right.escapedText, meaning));
45973                 if (!symbol) {
45974                     if (!ignoreErrors) {
45975                         var namespaceName = getFullyQualifiedName(namespace);
45976                         var declarationName = ts.declarationNameToString(right);
45977                         var suggestion = getSuggestedSymbolForNonexistentModule(right, namespace);
45978                         suggestion ?
45979                             error(right, ts.Diagnostics._0_has_no_exported_member_named_1_Did_you_mean_2, namespaceName, declarationName, symbolToString(suggestion)) :
45980                             error(right, ts.Diagnostics.Namespace_0_has_no_exported_member_1, namespaceName, declarationName);
45981                     }
45982                     return undefined;
45983                 }
45984             }
45985             else {
45986                 throw ts.Debug.assertNever(name, "Unknown entity name kind.");
45987             }
45988             ts.Debug.assert((ts.getCheckFlags(symbol) & 1 /* Instantiated */) === 0, "Should never get an instantiated symbol here.");
45989             if (!ts.nodeIsSynthesized(name) && ts.isEntityName(name) && (symbol.flags & 2097152 /* Alias */ || name.parent.kind === 266 /* ExportAssignment */)) {
45990                 markSymbolOfAliasDeclarationIfTypeOnly(ts.getAliasDeclarationFromName(name), symbol, /*finalTarget*/ undefined, /*overwriteEmpty*/ true);
45991             }
45992             return (symbol.flags & meaning) || dontResolveAlias ? symbol : resolveAlias(symbol);
45993         }
45994         /**
45995          * 1. For prototype-property methods like `A.prototype.m = function () ...`, try to resolve names in the scope of `A` too.
45996          * Note that prototype-property assignment to locations outside the current file (eg globals) doesn't work, so
45997          * name resolution won't work either.
45998          * 2. For property assignments like `{ x: function f () { } }`, try to resolve names in the scope of `f` too.
45999          */
46000         function resolveEntityNameFromAssignmentDeclaration(name, meaning) {
46001             if (isJSDocTypeReference(name.parent)) {
46002                 var secondaryLocation = getAssignmentDeclarationLocation(name.parent);
46003                 if (secondaryLocation) {
46004                     return resolveName(secondaryLocation, name.escapedText, meaning, /*nameNotFoundMessage*/ undefined, name, /*isUse*/ true);
46005                 }
46006             }
46007         }
46008         function getAssignmentDeclarationLocation(node) {
46009             var typeAlias = ts.findAncestor(node, function (node) { return !(ts.isJSDocNode(node) || node.flags & 4194304 /* JSDoc */) ? "quit" : ts.isJSDocTypeAlias(node); });
46010             if (typeAlias) {
46011                 return;
46012             }
46013             var host = ts.getJSDocHost(node);
46014             if (ts.isExpressionStatement(host) &&
46015                 ts.isBinaryExpression(host.expression) &&
46016                 ts.getAssignmentDeclarationKind(host.expression) === 3 /* PrototypeProperty */) {
46017                 // X.prototype.m = /** @param {K} p */ function () { } <-- look for K on X's declaration
46018                 var symbol = getSymbolOfNode(host.expression.left);
46019                 if (symbol) {
46020                     return getDeclarationOfJSPrototypeContainer(symbol);
46021                 }
46022             }
46023             if ((ts.isObjectLiteralMethod(host) || ts.isPropertyAssignment(host)) &&
46024                 ts.isBinaryExpression(host.parent.parent) &&
46025                 ts.getAssignmentDeclarationKind(host.parent.parent) === 6 /* Prototype */) {
46026                 // X.prototype = { /** @param {K} p */m() { } } <-- look for K on X's declaration
46027                 var symbol = getSymbolOfNode(host.parent.parent.left);
46028                 if (symbol) {
46029                     return getDeclarationOfJSPrototypeContainer(symbol);
46030                 }
46031             }
46032             var sig = ts.getEffectiveJSDocHost(node);
46033             if (sig && ts.isFunctionLike(sig)) {
46034                 var symbol = getSymbolOfNode(sig);
46035                 return symbol && symbol.valueDeclaration;
46036             }
46037         }
46038         function getDeclarationOfJSPrototypeContainer(symbol) {
46039             var decl = symbol.parent.valueDeclaration;
46040             if (!decl) {
46041                 return undefined;
46042             }
46043             var initializer = ts.isAssignmentDeclaration(decl) ? ts.getAssignedExpandoInitializer(decl) :
46044                 ts.hasOnlyExpressionInitializer(decl) ? ts.getDeclaredExpandoInitializer(decl) :
46045                     undefined;
46046             return initializer || decl;
46047         }
46048         /**
46049          * Get the real symbol of a declaration with an expando initializer.
46050          *
46051          * Normally, declarations have an associated symbol, but when a declaration has an expando
46052          * initializer, the expando's symbol is the one that has all the members merged into it.
46053          */
46054         function getExpandoSymbol(symbol) {
46055             var decl = symbol.valueDeclaration;
46056             if (!decl || !ts.isInJSFile(decl) || symbol.flags & 524288 /* TypeAlias */ || ts.getExpandoInitializer(decl, /*isPrototypeAssignment*/ false)) {
46057                 return undefined;
46058             }
46059             var init = ts.isVariableDeclaration(decl) ? ts.getDeclaredExpandoInitializer(decl) : ts.getAssignedExpandoInitializer(decl);
46060             if (init) {
46061                 var initSymbol = getSymbolOfNode(init);
46062                 if (initSymbol) {
46063                     return mergeJSSymbols(initSymbol, symbol);
46064                 }
46065             }
46066         }
46067         function resolveExternalModuleName(location, moduleReferenceExpression, ignoreErrors) {
46068             var isClassic = ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Classic;
46069             var errorMessage = isClassic ?
46070                 ts.Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
46071                 : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
46072             return resolveExternalModuleNameWorker(location, moduleReferenceExpression, ignoreErrors ? undefined : errorMessage);
46073         }
46074         function resolveExternalModuleNameWorker(location, moduleReferenceExpression, moduleNotFoundError, isForAugmentation) {
46075             if (isForAugmentation === void 0) { isForAugmentation = false; }
46076             return ts.isStringLiteralLike(moduleReferenceExpression)
46077                 ? resolveExternalModule(location, moduleReferenceExpression.text, moduleNotFoundError, moduleReferenceExpression, isForAugmentation)
46078                 : undefined;
46079         }
46080         function resolveExternalModule(location, moduleReference, moduleNotFoundError, errorNode, isForAugmentation) {
46081             if (isForAugmentation === void 0) { isForAugmentation = false; }
46082             if (ts.startsWith(moduleReference, "@types/")) {
46083                 var diag = ts.Diagnostics.Cannot_import_type_declaration_files_Consider_importing_0_instead_of_1;
46084                 var withoutAtTypePrefix = ts.removePrefix(moduleReference, "@types/");
46085                 error(errorNode, diag, withoutAtTypePrefix, moduleReference);
46086             }
46087             var ambientModule = tryFindAmbientModule(moduleReference, /*withAugmentations*/ true);
46088             if (ambientModule) {
46089                 return ambientModule;
46090             }
46091             var currentSourceFile = ts.getSourceFileOfNode(location);
46092             var resolvedModule = ts.getResolvedModule(currentSourceFile, moduleReference); // TODO: GH#18217
46093             var resolutionDiagnostic = resolvedModule && ts.getResolutionDiagnostic(compilerOptions, resolvedModule);
46094             var sourceFile = resolvedModule && !resolutionDiagnostic && host.getSourceFile(resolvedModule.resolvedFileName);
46095             if (sourceFile) {
46096                 if (sourceFile.symbol) {
46097                     if (resolvedModule.isExternalLibraryImport && !ts.resolutionExtensionIsTSOrJson(resolvedModule.extension)) {
46098                         errorOnImplicitAnyModule(/*isError*/ false, errorNode, resolvedModule, moduleReference);
46099                     }
46100                     // merged symbol is module declaration symbol combined with all augmentations
46101                     return getMergedSymbol(sourceFile.symbol);
46102                 }
46103                 if (moduleNotFoundError) {
46104                     // report errors only if it was requested
46105                     error(errorNode, ts.Diagnostics.File_0_is_not_a_module, sourceFile.fileName);
46106                 }
46107                 return undefined;
46108             }
46109             if (patternAmbientModules) {
46110                 var pattern = ts.findBestPatternMatch(patternAmbientModules, function (_) { return _.pattern; }, moduleReference);
46111                 if (pattern) {
46112                     // If the module reference matched a pattern ambient module ('*.foo') but there's also a
46113                     // module augmentation by the specific name requested ('a.foo'), we store the merged symbol
46114                     // by the augmentation name ('a.foo'), because asking for *.foo should not give you exports
46115                     // from a.foo.
46116                     var augmentation = patternAmbientModuleAugmentations && patternAmbientModuleAugmentations.get(moduleReference);
46117                     if (augmentation) {
46118                         return getMergedSymbol(augmentation);
46119                     }
46120                     return getMergedSymbol(pattern.symbol);
46121                 }
46122             }
46123             // May be an untyped module. If so, ignore resolutionDiagnostic.
46124             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) {
46125                 if (isForAugmentation) {
46126                     var diag = ts.Diagnostics.Invalid_module_name_in_augmentation_Module_0_resolves_to_an_untyped_module_at_1_which_cannot_be_augmented;
46127                     error(errorNode, diag, moduleReference, resolvedModule.resolvedFileName);
46128                 }
46129                 else {
46130                     errorOnImplicitAnyModule(/*isError*/ noImplicitAny && !!moduleNotFoundError, errorNode, resolvedModule, moduleReference);
46131                 }
46132                 // Failed imports and untyped modules are both treated in an untyped manner; only difference is whether we give a diagnostic first.
46133                 return undefined;
46134             }
46135             if (moduleNotFoundError) {
46136                 // See if this was possibly a projectReference redirect
46137                 if (resolvedModule) {
46138                     var redirect = host.getProjectReferenceRedirect(resolvedModule.resolvedFileName);
46139                     if (redirect) {
46140                         error(errorNode, ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, resolvedModule.resolvedFileName);
46141                         return undefined;
46142                     }
46143                 }
46144                 if (resolutionDiagnostic) {
46145                     error(errorNode, resolutionDiagnostic, moduleReference, resolvedModule.resolvedFileName);
46146                 }
46147                 else {
46148                     var tsExtension = ts.tryExtractTSExtension(moduleReference);
46149                     if (tsExtension) {
46150                         var diag = ts.Diagnostics.An_import_path_cannot_end_with_a_0_extension_Consider_importing_1_instead;
46151                         error(errorNode, diag, tsExtension, ts.removeExtension(moduleReference, tsExtension));
46152                     }
46153                     else if (!compilerOptions.resolveJsonModule &&
46154                         ts.fileExtensionIs(moduleReference, ".json" /* Json */) &&
46155                         ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs &&
46156                         ts.hasJsonModuleEmitEnabled(compilerOptions)) {
46157                         error(errorNode, ts.Diagnostics.Cannot_find_module_0_Consider_using_resolveJsonModule_to_import_module_with_json_extension, moduleReference);
46158                     }
46159                     else {
46160                         error(errorNode, moduleNotFoundError, moduleReference);
46161                     }
46162                 }
46163             }
46164             return undefined;
46165         }
46166         function errorOnImplicitAnyModule(isError, errorNode, _a, moduleReference) {
46167             var packageId = _a.packageId, resolvedFileName = _a.resolvedFileName;
46168             var errorInfo = !ts.isExternalModuleNameRelative(moduleReference) && packageId
46169                 ? typesPackageExists(packageId.name)
46170                     ? ts.chainDiagnosticMessages(
46171                     /*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))
46172                     : ts.chainDiagnosticMessages(
46173                     /*details*/ undefined, ts.Diagnostics.Try_npm_i_save_dev_types_Slash_1_if_it_exists_or_add_a_new_declaration_d_ts_file_containing_declare_module_0, moduleReference, ts.mangleScopedPackageName(packageId.name))
46174                 : undefined;
46175             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));
46176         }
46177         function typesPackageExists(packageName) {
46178             return getPackagesSet().has(ts.getTypesPackageName(packageName));
46179         }
46180         function resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias) {
46181             if (moduleSymbol === null || moduleSymbol === void 0 ? void 0 : moduleSymbol.exports) {
46182                 var exportEquals = resolveSymbol(moduleSymbol.exports.get("export=" /* ExportEquals */), dontResolveAlias);
46183                 var exported = getCommonJsExportEquals(getMergedSymbol(exportEquals), getMergedSymbol(moduleSymbol));
46184                 return getMergedSymbol(exported) || moduleSymbol;
46185             }
46186             return undefined;
46187         }
46188         function getCommonJsExportEquals(exported, moduleSymbol) {
46189             if (!exported || exported === unknownSymbol || exported === moduleSymbol || moduleSymbol.exports.size === 1 || exported.flags & 2097152 /* Alias */) {
46190                 return exported;
46191             }
46192             var links = getSymbolLinks(exported);
46193             if (links.cjsExportMerged) {
46194                 return links.cjsExportMerged;
46195             }
46196             var merged = exported.flags & 33554432 /* Transient */ ? exported : cloneSymbol(exported);
46197             merged.flags = merged.flags | 512 /* ValueModule */;
46198             if (merged.exports === undefined) {
46199                 merged.exports = ts.createSymbolTable();
46200             }
46201             moduleSymbol.exports.forEach(function (s, name) {
46202                 if (name === "export=" /* ExportEquals */)
46203                     return;
46204                 merged.exports.set(name, merged.exports.has(name) ? mergeSymbol(merged.exports.get(name), s) : s);
46205             });
46206             getSymbolLinks(merged).cjsExportMerged = merged;
46207             return links.cjsExportMerged = merged;
46208         }
46209         // An external module with an 'export =' declaration may be referenced as an ES6 module provided the 'export ='
46210         // references a symbol that is at least declared as a module or a variable. The target of the 'export =' may
46211         // combine other declarations with the module or variable (e.g. a class/module, function/module, interface/variable).
46212         function resolveESModuleSymbol(moduleSymbol, referencingLocation, dontResolveAlias, suppressInteropError) {
46213             var symbol = resolveExternalModuleSymbol(moduleSymbol, dontResolveAlias);
46214             if (!dontResolveAlias && symbol) {
46215                 if (!suppressInteropError && !(symbol.flags & (1536 /* Module */ | 3 /* Variable */)) && !ts.getDeclarationOfKind(symbol, 297 /* SourceFile */)) {
46216                     var compilerOptionName = moduleKind >= ts.ModuleKind.ES2015
46217                         ? "allowSyntheticDefaultImports"
46218                         : "esModuleInterop";
46219                     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);
46220                     return symbol;
46221                 }
46222                 if (compilerOptions.esModuleInterop) {
46223                     var referenceParent = referencingLocation.parent;
46224                     if ((ts.isImportDeclaration(referenceParent) && ts.getNamespaceDeclarationNode(referenceParent)) ||
46225                         ts.isImportCall(referenceParent)) {
46226                         var type = getTypeOfSymbol(symbol);
46227                         var sigs = getSignaturesOfStructuredType(type, 0 /* Call */);
46228                         if (!sigs || !sigs.length) {
46229                             sigs = getSignaturesOfStructuredType(type, 1 /* Construct */);
46230                         }
46231                         if (sigs && sigs.length) {
46232                             var moduleType = getTypeWithSyntheticDefaultImportType(type, symbol, moduleSymbol);
46233                             // Create a new symbol which has the module's type less the call and construct signatures
46234                             var result = createSymbol(symbol.flags, symbol.escapedName);
46235                             result.declarations = symbol.declarations ? symbol.declarations.slice() : [];
46236                             result.parent = symbol.parent;
46237                             result.target = symbol;
46238                             result.originatingImport = referenceParent;
46239                             if (symbol.valueDeclaration)
46240                                 result.valueDeclaration = symbol.valueDeclaration;
46241                             if (symbol.constEnumOnlyModule)
46242                                 result.constEnumOnlyModule = true;
46243                             if (symbol.members)
46244                                 result.members = new ts.Map(symbol.members);
46245                             if (symbol.exports)
46246                                 result.exports = new ts.Map(symbol.exports);
46247                             var resolvedModuleType = resolveStructuredTypeMembers(moduleType); // Should already be resolved from the signature checks above
46248                             result.type = createAnonymousType(result, resolvedModuleType.members, ts.emptyArray, ts.emptyArray, resolvedModuleType.stringIndexInfo, resolvedModuleType.numberIndexInfo);
46249                             return result;
46250                         }
46251                     }
46252                 }
46253             }
46254             return symbol;
46255         }
46256         function hasExportAssignmentSymbol(moduleSymbol) {
46257             return moduleSymbol.exports.get("export=" /* ExportEquals */) !== undefined;
46258         }
46259         function getExportsOfModuleAsArray(moduleSymbol) {
46260             return symbolsToArray(getExportsOfModule(moduleSymbol));
46261         }
46262         function getExportsAndPropertiesOfModule(moduleSymbol) {
46263             var exports = getExportsOfModuleAsArray(moduleSymbol);
46264             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
46265             if (exportEquals !== moduleSymbol) {
46266                 ts.addRange(exports, getPropertiesOfType(getTypeOfSymbol(exportEquals)));
46267             }
46268             return exports;
46269         }
46270         function tryGetMemberInModuleExports(memberName, moduleSymbol) {
46271             var symbolTable = getExportsOfModule(moduleSymbol);
46272             if (symbolTable) {
46273                 return symbolTable.get(memberName);
46274             }
46275         }
46276         function tryGetMemberInModuleExportsAndProperties(memberName, moduleSymbol) {
46277             var symbol = tryGetMemberInModuleExports(memberName, moduleSymbol);
46278             if (symbol) {
46279                 return symbol;
46280             }
46281             var exportEquals = resolveExternalModuleSymbol(moduleSymbol);
46282             if (exportEquals === moduleSymbol) {
46283                 return undefined;
46284             }
46285             var type = getTypeOfSymbol(exportEquals);
46286             return type.flags & 131068 /* Primitive */ ||
46287                 ts.getObjectFlags(type) & 1 /* Class */ ||
46288                 isArrayOrTupleLikeType(type)
46289                 ? undefined
46290                 : getPropertyOfType(type, memberName);
46291         }
46292         function getExportsOfSymbol(symbol) {
46293             return symbol.flags & 6256 /* LateBindingContainer */ ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedExports" /* resolvedExports */) :
46294                 symbol.flags & 1536 /* Module */ ? getExportsOfModule(symbol) :
46295                     symbol.exports || emptySymbols;
46296         }
46297         function getExportsOfModule(moduleSymbol) {
46298             var links = getSymbolLinks(moduleSymbol);
46299             return links.resolvedExports || (links.resolvedExports = getExportsOfModuleWorker(moduleSymbol));
46300         }
46301         /**
46302          * Extends one symbol table with another while collecting information on name collisions for error message generation into the `lookupTable` argument
46303          * Not passing `lookupTable` and `exportNode` disables this collection, and just extends the tables
46304          */
46305         function extendExportSymbols(target, source, lookupTable, exportNode) {
46306             if (!source)
46307                 return;
46308             source.forEach(function (sourceSymbol, id) {
46309                 if (id === "default" /* Default */)
46310                     return;
46311                 var targetSymbol = target.get(id);
46312                 if (!targetSymbol) {
46313                     target.set(id, sourceSymbol);
46314                     if (lookupTable && exportNode) {
46315                         lookupTable.set(id, {
46316                             specifierText: ts.getTextOfNode(exportNode.moduleSpecifier)
46317                         });
46318                     }
46319                 }
46320                 else if (lookupTable && exportNode && targetSymbol && resolveSymbol(targetSymbol) !== resolveSymbol(sourceSymbol)) {
46321                     var collisionTracker = lookupTable.get(id);
46322                     if (!collisionTracker.exportsWithDuplicate) {
46323                         collisionTracker.exportsWithDuplicate = [exportNode];
46324                     }
46325                     else {
46326                         collisionTracker.exportsWithDuplicate.push(exportNode);
46327                     }
46328                 }
46329             });
46330         }
46331         function getExportsOfModuleWorker(moduleSymbol) {
46332             var visitedSymbols = [];
46333             // A module defined by an 'export=' consists of one export that needs to be resolved
46334             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
46335             return visit(moduleSymbol) || emptySymbols;
46336             // The ES6 spec permits export * declarations in a module to circularly reference the module itself. For example,
46337             // module 'a' can 'export * from "b"' and 'b' can 'export * from "a"' without error.
46338             function visit(symbol) {
46339                 if (!(symbol && symbol.exports && ts.pushIfUnique(visitedSymbols, symbol))) {
46340                     return;
46341                 }
46342                 var symbols = new ts.Map(symbol.exports);
46343                 // All export * declarations are collected in an __export symbol by the binder
46344                 var exportStars = symbol.exports.get("__export" /* ExportStar */);
46345                 if (exportStars) {
46346                     var nestedSymbols = ts.createSymbolTable();
46347                     var lookupTable_1 = new ts.Map();
46348                     for (var _i = 0, _a = exportStars.declarations; _i < _a.length; _i++) {
46349                         var node = _a[_i];
46350                         var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
46351                         var exportedSymbols = visit(resolvedModule);
46352                         extendExportSymbols(nestedSymbols, exportedSymbols, lookupTable_1, node);
46353                     }
46354                     lookupTable_1.forEach(function (_a, id) {
46355                         var exportsWithDuplicate = _a.exportsWithDuplicate;
46356                         // It's not an error if the file with multiple `export *`s with duplicate names exports a member with that name itself
46357                         if (id === "export=" || !(exportsWithDuplicate && exportsWithDuplicate.length) || symbols.has(id)) {
46358                             return;
46359                         }
46360                         for (var _i = 0, exportsWithDuplicate_1 = exportsWithDuplicate; _i < exportsWithDuplicate_1.length; _i++) {
46361                             var node = exportsWithDuplicate_1[_i];
46362                             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)));
46363                         }
46364                     });
46365                     extendExportSymbols(symbols, nestedSymbols);
46366                 }
46367                 return symbols;
46368             }
46369         }
46370         function getMergedSymbol(symbol) {
46371             var merged;
46372             return symbol && symbol.mergeId && (merged = mergedSymbols[symbol.mergeId]) ? merged : symbol;
46373         }
46374         function getSymbolOfNode(node) {
46375             return getMergedSymbol(node.symbol && getLateBoundSymbol(node.symbol));
46376         }
46377         function getParentOfSymbol(symbol) {
46378             return getMergedSymbol(symbol.parent && getLateBoundSymbol(symbol.parent));
46379         }
46380         function getAlternativeContainingModules(symbol, enclosingDeclaration) {
46381             var containingFile = ts.getSourceFileOfNode(enclosingDeclaration);
46382             var id = getNodeId(containingFile);
46383             var links = getSymbolLinks(symbol);
46384             var results;
46385             if (links.extendedContainersByFile && (results = links.extendedContainersByFile.get(id))) {
46386                 return results;
46387             }
46388             if (containingFile && containingFile.imports) {
46389                 // Try to make an import using an import already in the enclosing file, if possible
46390                 for (var _i = 0, _a = containingFile.imports; _i < _a.length; _i++) {
46391                     var importRef = _a[_i];
46392                     if (ts.nodeIsSynthesized(importRef))
46393                         continue; // Synthetic names can't be resolved by `resolveExternalModuleName` - they'll cause a debug assert if they error
46394                     var resolvedModule = resolveExternalModuleName(enclosingDeclaration, importRef, /*ignoreErrors*/ true);
46395                     if (!resolvedModule)
46396                         continue;
46397                     var ref = getAliasForSymbolInContainer(resolvedModule, symbol);
46398                     if (!ref)
46399                         continue;
46400                     results = ts.append(results, resolvedModule);
46401                 }
46402                 if (ts.length(results)) {
46403                     (links.extendedContainersByFile || (links.extendedContainersByFile = new ts.Map())).set(id, results);
46404                     return results;
46405                 }
46406             }
46407             if (links.extendedContainers) {
46408                 return links.extendedContainers;
46409             }
46410             // No results from files already being imported by this file - expand search (expensive, but not location-specific, so cached)
46411             var otherFiles = host.getSourceFiles();
46412             for (var _b = 0, otherFiles_1 = otherFiles; _b < otherFiles_1.length; _b++) {
46413                 var file = otherFiles_1[_b];
46414                 if (!ts.isExternalModule(file))
46415                     continue;
46416                 var sym = getSymbolOfNode(file);
46417                 var ref = getAliasForSymbolInContainer(sym, symbol);
46418                 if (!ref)
46419                     continue;
46420                 results = ts.append(results, sym);
46421             }
46422             return links.extendedContainers = results || ts.emptyArray;
46423         }
46424         /**
46425          * Attempts to find the symbol corresponding to the container a symbol is in - usually this
46426          * is just its' `.parent`, but for locals, this value is `undefined`
46427          */
46428         function getContainersOfSymbol(symbol, enclosingDeclaration, meaning) {
46429             var container = getParentOfSymbol(symbol);
46430             // Type parameters end up in the `members` lists but are not externally visible
46431             if (container && !(symbol.flags & 262144 /* TypeParameter */)) {
46432                 var additionalContainers = ts.mapDefined(container.declarations, fileSymbolIfFileSymbolExportEqualsContainer);
46433                 var reexportContainers = enclosingDeclaration && getAlternativeContainingModules(symbol, enclosingDeclaration);
46434                 var objectLiteralContainer = getVariableDeclarationOfObjectLiteral(container, meaning);
46435                 if (enclosingDeclaration && getAccessibleSymbolChain(container, enclosingDeclaration, 1920 /* Namespace */, /*externalOnly*/ false)) {
46436                     return ts.append(ts.concatenate(ts.concatenate([container], additionalContainers), reexportContainers), objectLiteralContainer); // This order expresses a preference for the real container if it is in scope
46437                 }
46438                 var res = ts.append(ts.append(additionalContainers, container), objectLiteralContainer);
46439                 return ts.concatenate(res, reexportContainers);
46440             }
46441             var candidates = ts.mapDefined(symbol.declarations, function (d) {
46442                 if (!ts.isAmbientModule(d) && d.parent && hasNonGlobalAugmentationExternalModuleSymbol(d.parent)) {
46443                     return getSymbolOfNode(d.parent);
46444                 }
46445                 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)) {
46446                     if (ts.isModuleExportsAccessExpression(d.parent.left) || ts.isExportsIdentifier(d.parent.left.expression)) {
46447                         return getSymbolOfNode(ts.getSourceFileOfNode(d));
46448                     }
46449                     checkExpressionCached(d.parent.left.expression);
46450                     return getNodeLinks(d.parent.left.expression).resolvedSymbol;
46451                 }
46452             });
46453             if (!ts.length(candidates)) {
46454                 return undefined;
46455             }
46456             return ts.mapDefined(candidates, function (candidate) { return getAliasForSymbolInContainer(candidate, symbol) ? candidate : undefined; });
46457             function fileSymbolIfFileSymbolExportEqualsContainer(d) {
46458                 return container && getFileSymbolIfFileSymbolExportEqualsContainer(d, container);
46459             }
46460         }
46461         function getVariableDeclarationOfObjectLiteral(symbol, meaning) {
46462             // If we're trying to reference some object literal in, eg `var a = { x: 1 }`, the symbol for the literal, `__object`, is distinct
46463             // from the symbol of the declaration it is being assigned to. Since we can use the declaration to refer to the literal, however,
46464             // we'd like to make that connection here - potentially causing us to paint the declaration's visibility, and therefore the literal.
46465             var firstDecl = !!ts.length(symbol.declarations) && ts.first(symbol.declarations);
46466             if (meaning & 111551 /* Value */ && firstDecl && firstDecl.parent && ts.isVariableDeclaration(firstDecl.parent)) {
46467                 if (ts.isObjectLiteralExpression(firstDecl) && firstDecl === firstDecl.parent.initializer || ts.isTypeLiteralNode(firstDecl) && firstDecl === firstDecl.parent.type) {
46468                     return getSymbolOfNode(firstDecl.parent);
46469                 }
46470             }
46471         }
46472         function getFileSymbolIfFileSymbolExportEqualsContainer(d, container) {
46473             var fileSymbol = getExternalModuleContainer(d);
46474             var exported = fileSymbol && fileSymbol.exports && fileSymbol.exports.get("export=" /* ExportEquals */);
46475             return exported && getSymbolIfSameReference(exported, container) ? fileSymbol : undefined;
46476         }
46477         function getAliasForSymbolInContainer(container, symbol) {
46478             if (container === getParentOfSymbol(symbol)) {
46479                 // fast path, `symbol` is either already the alias or isn't aliased
46480                 return symbol;
46481             }
46482             // Check if container is a thing with an `export=` which points directly at `symbol`, and if so, return
46483             // the container itself as the alias for the symbol
46484             var exportEquals = container.exports && container.exports.get("export=" /* ExportEquals */);
46485             if (exportEquals && getSymbolIfSameReference(exportEquals, symbol)) {
46486                 return container;
46487             }
46488             var exports = getExportsOfSymbol(container);
46489             var quick = exports.get(symbol.escapedName);
46490             if (quick && getSymbolIfSameReference(quick, symbol)) {
46491                 return quick;
46492             }
46493             return ts.forEachEntry(exports, function (exported) {
46494                 if (getSymbolIfSameReference(exported, symbol)) {
46495                     return exported;
46496                 }
46497             });
46498         }
46499         /**
46500          * Checks if two symbols, through aliasing and/or merging, refer to the same thing
46501          */
46502         function getSymbolIfSameReference(s1, s2) {
46503             if (getMergedSymbol(resolveSymbol(getMergedSymbol(s1))) === getMergedSymbol(resolveSymbol(getMergedSymbol(s2)))) {
46504                 return s1;
46505             }
46506         }
46507         function getExportSymbolOfValueSymbolIfExported(symbol) {
46508             return getMergedSymbol(symbol && (symbol.flags & 1048576 /* ExportValue */) !== 0 ? symbol.exportSymbol : symbol);
46509         }
46510         function symbolIsValue(symbol) {
46511             return !!(symbol.flags & 111551 /* Value */ || symbol.flags & 2097152 /* Alias */ && resolveAlias(symbol).flags & 111551 /* Value */ && !getTypeOnlyAliasDeclaration(symbol));
46512         }
46513         function findConstructorDeclaration(node) {
46514             var members = node.members;
46515             for (var _i = 0, members_3 = members; _i < members_3.length; _i++) {
46516                 var member = members_3[_i];
46517                 if (member.kind === 166 /* Constructor */ && ts.nodeIsPresent(member.body)) {
46518                     return member;
46519                 }
46520             }
46521         }
46522         function createType(flags) {
46523             var result = new Type(checker, flags);
46524             typeCount++;
46525             result.id = typeCount;
46526             typeCatalog.push(result);
46527             return result;
46528         }
46529         function createIntrinsicType(kind, intrinsicName, objectFlags) {
46530             if (objectFlags === void 0) { objectFlags = 0; }
46531             var type = createType(kind);
46532             type.intrinsicName = intrinsicName;
46533             type.objectFlags = objectFlags;
46534             return type;
46535         }
46536         function createBooleanType(trueFalseTypes) {
46537             var type = getUnionType(trueFalseTypes);
46538             type.flags |= 16 /* Boolean */;
46539             type.intrinsicName = "boolean";
46540             return type;
46541         }
46542         function createObjectType(objectFlags, symbol) {
46543             var type = createType(524288 /* Object */);
46544             type.objectFlags = objectFlags;
46545             type.symbol = symbol;
46546             type.members = undefined;
46547             type.properties = undefined;
46548             type.callSignatures = undefined;
46549             type.constructSignatures = undefined;
46550             type.stringIndexInfo = undefined;
46551             type.numberIndexInfo = undefined;
46552             return type;
46553         }
46554         function createTypeofType() {
46555             return getUnionType(ts.arrayFrom(typeofEQFacts.keys(), getLiteralType));
46556         }
46557         function createTypeParameter(symbol) {
46558             var type = createType(262144 /* TypeParameter */);
46559             if (symbol)
46560                 type.symbol = symbol;
46561             return type;
46562         }
46563         // A reserved member name starts with two underscores, but the third character cannot be an underscore,
46564         // @, or #. A third underscore indicates an escaped form of an identifier that started
46565         // with at least two underscores. The @ character indicates that the name is denoted by a well known ES
46566         // Symbol instance and the # character indicates that the name is a PrivateIdentifier.
46567         function isReservedMemberName(name) {
46568             return name.charCodeAt(0) === 95 /* _ */ &&
46569                 name.charCodeAt(1) === 95 /* _ */ &&
46570                 name.charCodeAt(2) !== 95 /* _ */ &&
46571                 name.charCodeAt(2) !== 64 /* at */ &&
46572                 name.charCodeAt(2) !== 35 /* hash */;
46573         }
46574         function getNamedMembers(members) {
46575             var result;
46576             members.forEach(function (symbol, id) {
46577                 if (!isReservedMemberName(id) && symbolIsValue(symbol)) {
46578                     (result || (result = [])).push(symbol);
46579                 }
46580             });
46581             return result || ts.emptyArray;
46582         }
46583         function setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
46584             type.members = members;
46585             type.properties = members === emptySymbols ? ts.emptyArray : getNamedMembers(members);
46586             type.callSignatures = callSignatures;
46587             type.constructSignatures = constructSignatures;
46588             type.stringIndexInfo = stringIndexInfo;
46589             type.numberIndexInfo = numberIndexInfo;
46590             return type;
46591         }
46592         function createAnonymousType(symbol, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo) {
46593             return setStructuredTypeMembers(createObjectType(16 /* Anonymous */, symbol), members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
46594         }
46595         function forEachSymbolTableInScope(enclosingDeclaration, callback) {
46596             var result;
46597             var _loop_8 = function (location) {
46598                 // Locals of a source file are not in scope (because they get merged into the global symbol table)
46599                 if (location.locals && !isGlobalSourceFile(location)) {
46600                     if (result = callback(location.locals)) {
46601                         return { value: result };
46602                     }
46603                 }
46604                 switch (location.kind) {
46605                     case 297 /* SourceFile */:
46606                         if (!ts.isExternalOrCommonJsModule(location)) {
46607                             break;
46608                         }
46609                     // falls through
46610                     case 256 /* ModuleDeclaration */:
46611                         var sym = getSymbolOfNode(location);
46612                         // `sym` may not have exports if this module declaration is backed by the symbol for a `const` that's being rewritten
46613                         // into a namespace - in such cases, it's best to just let the namespace appear empty (the const members couldn't have referred
46614                         // to one another anyway)
46615                         if (result = callback((sym === null || sym === void 0 ? void 0 : sym.exports) || emptySymbols)) {
46616                             return { value: result };
46617                         }
46618                         break;
46619                     case 252 /* ClassDeclaration */:
46620                     case 221 /* ClassExpression */:
46621                     case 253 /* InterfaceDeclaration */:
46622                         // Type parameters are bound into `members` lists so they can merge across declarations
46623                         // This is troublesome, since in all other respects, they behave like locals :cries:
46624                         // TODO: the below is shared with similar code in `resolveName` - in fact, rephrasing all this symbol
46625                         // lookup logic in terms of `resolveName` would be nice
46626                         // The below is used to lookup type parameters within a class or interface, as they are added to the class/interface locals
46627                         // These can never be latebound, so the symbol's raw members are sufficient. `getMembersOfNode` cannot be used, as it would
46628                         // trigger resolving late-bound names, which we may already be in the process of doing while we're here!
46629                         var table_1;
46630                         // TODO: Should this filtered table be cached in some way?
46631                         (getSymbolOfNode(location).members || emptySymbols).forEach(function (memberSymbol, key) {
46632                             if (memberSymbol.flags & (788968 /* Type */ & ~67108864 /* Assignment */)) {
46633                                 (table_1 || (table_1 = ts.createSymbolTable())).set(key, memberSymbol);
46634                             }
46635                         });
46636                         if (table_1 && (result = callback(table_1))) {
46637                             return { value: result };
46638                         }
46639                         break;
46640                 }
46641             };
46642             for (var location = enclosingDeclaration; location; location = location.parent) {
46643                 var state_2 = _loop_8(location);
46644                 if (typeof state_2 === "object")
46645                     return state_2.value;
46646             }
46647             return callback(globals);
46648         }
46649         function getQualifiedLeftMeaning(rightMeaning) {
46650             // If we are looking in value space, the parent meaning is value, other wise it is namespace
46651             return rightMeaning === 111551 /* Value */ ? 111551 /* Value */ : 1920 /* Namespace */;
46652         }
46653         function getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, useOnlyExternalAliasing, visitedSymbolTablesMap) {
46654             if (visitedSymbolTablesMap === void 0) { visitedSymbolTablesMap = new ts.Map(); }
46655             if (!(symbol && !isPropertyOrMethodDeclarationSymbol(symbol))) {
46656                 return undefined;
46657             }
46658             var id = getSymbolId(symbol);
46659             var visitedSymbolTables = visitedSymbolTablesMap.get(id);
46660             if (!visitedSymbolTables) {
46661                 visitedSymbolTablesMap.set(id, visitedSymbolTables = []);
46662             }
46663             return forEachSymbolTableInScope(enclosingDeclaration, getAccessibleSymbolChainFromSymbolTable);
46664             /**
46665              * @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)
46666              */
46667             function getAccessibleSymbolChainFromSymbolTable(symbols, ignoreQualification) {
46668                 if (!ts.pushIfUnique(visitedSymbolTables, symbols)) {
46669                     return undefined;
46670                 }
46671                 var result = trySymbolTable(symbols, ignoreQualification);
46672                 visitedSymbolTables.pop();
46673                 return result;
46674             }
46675             function canQualifySymbol(symbolFromSymbolTable, meaning) {
46676                 // If the symbol is equivalent and doesn't need further qualification, this symbol is accessible
46677                 return !needsQualification(symbolFromSymbolTable, enclosingDeclaration, meaning) ||
46678                     // If symbol needs qualification, make sure that parent is accessible, if it is then this symbol is accessible too
46679                     !!getAccessibleSymbolChain(symbolFromSymbolTable.parent, enclosingDeclaration, getQualifiedLeftMeaning(meaning), useOnlyExternalAliasing, visitedSymbolTablesMap);
46680             }
46681             function isAccessible(symbolFromSymbolTable, resolvedAliasSymbol, ignoreQualification) {
46682                 return (symbol === (resolvedAliasSymbol || symbolFromSymbolTable) || getMergedSymbol(symbol) === getMergedSymbol(resolvedAliasSymbol || symbolFromSymbolTable)) &&
46683                     // if the symbolFromSymbolTable is not external module (it could be if it was determined as ambient external module and would be in globals table)
46684                     // and if symbolFromSymbolTable or alias resolution matches the symbol,
46685                     // check the symbol can be qualified, it is only then this symbol is accessible
46686                     !ts.some(symbolFromSymbolTable.declarations, hasNonGlobalAugmentationExternalModuleSymbol) &&
46687                     (ignoreQualification || canQualifySymbol(getMergedSymbol(symbolFromSymbolTable), meaning));
46688             }
46689             function trySymbolTable(symbols, ignoreQualification) {
46690                 // If symbol is directly available by its name in the symbol table
46691                 if (isAccessible(symbols.get(symbol.escapedName), /*resolvedAliasSymbol*/ undefined, ignoreQualification)) {
46692                     return [symbol];
46693                 }
46694                 // Check if symbol is any of the aliases in scope
46695                 var result = ts.forEachEntry(symbols, function (symbolFromSymbolTable) {
46696                     if (symbolFromSymbolTable.flags & 2097152 /* Alias */
46697                         && symbolFromSymbolTable.escapedName !== "export=" /* ExportEquals */
46698                         && symbolFromSymbolTable.escapedName !== "default" /* Default */
46699                         && !(ts.isUMDExportSymbol(symbolFromSymbolTable) && enclosingDeclaration && ts.isExternalModule(ts.getSourceFileOfNode(enclosingDeclaration)))
46700                         // If `!useOnlyExternalAliasing`, we can use any type of alias to get the name
46701                         && (!useOnlyExternalAliasing || ts.some(symbolFromSymbolTable.declarations, ts.isExternalModuleImportEqualsDeclaration))
46702                         // While exports are generally considered to be in scope, export-specifier declared symbols are _not_
46703                         // See similar comment in `resolveName` for details
46704                         && (ignoreQualification || !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */))) {
46705                         var resolvedImportedSymbol = resolveAlias(symbolFromSymbolTable);
46706                         var candidate = getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification);
46707                         if (candidate) {
46708                             return candidate;
46709                         }
46710                     }
46711                     if (symbolFromSymbolTable.escapedName === symbol.escapedName && symbolFromSymbolTable.exportSymbol) {
46712                         if (isAccessible(getMergedSymbol(symbolFromSymbolTable.exportSymbol), /*aliasSymbol*/ undefined, ignoreQualification)) {
46713                             return [symbol];
46714                         }
46715                     }
46716                 });
46717                 // 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
46718                 return result || (symbols === globals ? getCandidateListForSymbol(globalThisSymbol, globalThisSymbol, ignoreQualification) : undefined);
46719             }
46720             function getCandidateListForSymbol(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification) {
46721                 if (isAccessible(symbolFromSymbolTable, resolvedImportedSymbol, ignoreQualification)) {
46722                     return [symbolFromSymbolTable];
46723                 }
46724                 // Look in the exported members, if we can find accessibleSymbolChain, symbol is accessible using this chain
46725                 // but only if the symbolFromSymbolTable can be qualified
46726                 var candidateTable = getExportsOfSymbol(resolvedImportedSymbol);
46727                 var accessibleSymbolsFromExports = candidateTable && getAccessibleSymbolChainFromSymbolTable(candidateTable, /*ignoreQualification*/ true);
46728                 if (accessibleSymbolsFromExports && canQualifySymbol(symbolFromSymbolTable, getQualifiedLeftMeaning(meaning))) {
46729                     return [symbolFromSymbolTable].concat(accessibleSymbolsFromExports);
46730                 }
46731             }
46732         }
46733         function needsQualification(symbol, enclosingDeclaration, meaning) {
46734             var qualify = false;
46735             forEachSymbolTableInScope(enclosingDeclaration, function (symbolTable) {
46736                 // If symbol of this name is not available in the symbol table we are ok
46737                 var symbolFromSymbolTable = getMergedSymbol(symbolTable.get(symbol.escapedName));
46738                 if (!symbolFromSymbolTable) {
46739                     // Continue to the next symbol table
46740                     return false;
46741                 }
46742                 // If the symbol with this name is present it should refer to the symbol
46743                 if (symbolFromSymbolTable === symbol) {
46744                     // No need to qualify
46745                     return true;
46746                 }
46747                 // Qualify if the symbol from symbol table has same meaning as expected
46748                 symbolFromSymbolTable = (symbolFromSymbolTable.flags & 2097152 /* Alias */ && !ts.getDeclarationOfKind(symbolFromSymbolTable, 270 /* ExportSpecifier */)) ? resolveAlias(symbolFromSymbolTable) : symbolFromSymbolTable;
46749                 if (symbolFromSymbolTable.flags & meaning) {
46750                     qualify = true;
46751                     return true;
46752                 }
46753                 // Continue to the next symbol table
46754                 return false;
46755             });
46756             return qualify;
46757         }
46758         function isPropertyOrMethodDeclarationSymbol(symbol) {
46759             if (symbol.declarations && symbol.declarations.length) {
46760                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
46761                     var declaration = _a[_i];
46762                     switch (declaration.kind) {
46763                         case 163 /* PropertyDeclaration */:
46764                         case 165 /* MethodDeclaration */:
46765                         case 167 /* GetAccessor */:
46766                         case 168 /* SetAccessor */:
46767                             continue;
46768                         default:
46769                             return false;
46770                     }
46771                 }
46772                 return true;
46773             }
46774             return false;
46775         }
46776         function isTypeSymbolAccessible(typeSymbol, enclosingDeclaration) {
46777             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 788968 /* Type */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
46778             return access.accessibility === 0 /* Accessible */;
46779         }
46780         function isValueSymbolAccessible(typeSymbol, enclosingDeclaration) {
46781             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, 111551 /* Value */, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ true);
46782             return access.accessibility === 0 /* Accessible */;
46783         }
46784         function isSymbolAccessibleByFlags(typeSymbol, enclosingDeclaration, flags) {
46785             var access = isSymbolAccessibleWorker(typeSymbol, enclosingDeclaration, flags, /*shouldComputeAliasesToMakeVisible*/ false, /*allowModules*/ false);
46786             return access.accessibility === 0 /* Accessible */;
46787         }
46788         function isAnySymbolAccessible(symbols, enclosingDeclaration, initialSymbol, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
46789             if (!ts.length(symbols))
46790                 return;
46791             var hadAccessibleChain;
46792             var earlyModuleBail = false;
46793             for (var _i = 0, _a = symbols; _i < _a.length; _i++) {
46794                 var symbol = _a[_i];
46795                 // Symbol is accessible if it by itself is accessible
46796                 var accessibleSymbolChain = getAccessibleSymbolChain(symbol, enclosingDeclaration, meaning, /*useOnlyExternalAliasing*/ false);
46797                 if (accessibleSymbolChain) {
46798                     hadAccessibleChain = symbol;
46799                     var hasAccessibleDeclarations = hasVisibleDeclarations(accessibleSymbolChain[0], shouldComputeAliasesToMakeVisible);
46800                     if (hasAccessibleDeclarations) {
46801                         return hasAccessibleDeclarations;
46802                     }
46803                 }
46804                 else if (allowModules) {
46805                     if (ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
46806                         if (shouldComputeAliasesToMakeVisible) {
46807                             earlyModuleBail = true;
46808                             // Generally speaking, we want to use the aliases that already exist to refer to a module, if present
46809                             // In order to do so, we need to find those aliases in order to retain them in declaration emit; so
46810                             // if we are in declaration emit, we cannot use the fast path for module visibility until we've exhausted
46811                             // all other visibility options (in order to capture the possible aliases used to reference the module)
46812                             continue;
46813                         }
46814                         // Any meaning of a module symbol is always accessible via an `import` type
46815                         return {
46816                             accessibility: 0 /* Accessible */
46817                         };
46818                     }
46819                 }
46820                 // If we haven't got the accessible symbol, it doesn't mean the symbol is actually inaccessible.
46821                 // It could be a qualified symbol and hence verify the path
46822                 // e.g.:
46823                 // module m {
46824                 //     export class c {
46825                 //     }
46826                 // }
46827                 // const x: typeof m.c
46828                 // In the above example when we start with checking if typeof m.c symbol is accessible,
46829                 // we are going to see if c can be accessed in scope directly.
46830                 // But it can't, hence the accessible is going to be undefined, but that doesn't mean m.c is inaccessible
46831                 // It is accessible if the parent m is accessible because then m.c can be accessed through qualification
46832                 var containers = getContainersOfSymbol(symbol, enclosingDeclaration, meaning);
46833                 var parentResult = isAnySymbolAccessible(containers, enclosingDeclaration, initialSymbol, initialSymbol === symbol ? getQualifiedLeftMeaning(meaning) : meaning, shouldComputeAliasesToMakeVisible, allowModules);
46834                 if (parentResult) {
46835                     return parentResult;
46836                 }
46837             }
46838             if (earlyModuleBail) {
46839                 return {
46840                     accessibility: 0 /* Accessible */
46841                 };
46842             }
46843             if (hadAccessibleChain) {
46844                 return {
46845                     accessibility: 1 /* NotAccessible */,
46846                     errorSymbolName: symbolToString(initialSymbol, enclosingDeclaration, meaning),
46847                     errorModuleName: hadAccessibleChain !== initialSymbol ? symbolToString(hadAccessibleChain, enclosingDeclaration, 1920 /* Namespace */) : undefined,
46848                 };
46849             }
46850         }
46851         /**
46852          * Check if the given symbol in given enclosing declaration is accessible and mark all associated alias to be visible if requested
46853          *
46854          * @param symbol a Symbol to check if accessible
46855          * @param enclosingDeclaration a Node containing reference to the symbol
46856          * @param meaning a SymbolFlags to check if such meaning of the symbol is accessible
46857          * @param shouldComputeAliasToMakeVisible a boolean value to indicate whether to return aliases to be mark visible in case the symbol is accessible
46858          */
46859         function isSymbolAccessible(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible) {
46860             return isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, /*allowModules*/ true);
46861         }
46862         function isSymbolAccessibleWorker(symbol, enclosingDeclaration, meaning, shouldComputeAliasesToMakeVisible, allowModules) {
46863             if (symbol && enclosingDeclaration) {
46864                 var result = isAnySymbolAccessible([symbol], enclosingDeclaration, symbol, meaning, shouldComputeAliasesToMakeVisible, allowModules);
46865                 if (result) {
46866                     return result;
46867                 }
46868                 // This could be a symbol that is not exported in the external module
46869                 // or it could be a symbol from different external module that is not aliased and hence cannot be named
46870                 var symbolExternalModule = ts.forEach(symbol.declarations, getExternalModuleContainer);
46871                 if (symbolExternalModule) {
46872                     var enclosingExternalModule = getExternalModuleContainer(enclosingDeclaration);
46873                     if (symbolExternalModule !== enclosingExternalModule) {
46874                         // name from different external module that is not visible
46875                         return {
46876                             accessibility: 2 /* CannotBeNamed */,
46877                             errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
46878                             errorModuleName: symbolToString(symbolExternalModule)
46879                         };
46880                     }
46881                 }
46882                 // Just a local name that is not accessible
46883                 return {
46884                     accessibility: 1 /* NotAccessible */,
46885                     errorSymbolName: symbolToString(symbol, enclosingDeclaration, meaning),
46886                 };
46887             }
46888             return { accessibility: 0 /* Accessible */ };
46889         }
46890         function getExternalModuleContainer(declaration) {
46891             var node = ts.findAncestor(declaration, hasExternalModuleSymbol);
46892             return node && getSymbolOfNode(node);
46893         }
46894         function hasExternalModuleSymbol(declaration) {
46895             return ts.isAmbientModule(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
46896         }
46897         function hasNonGlobalAugmentationExternalModuleSymbol(declaration) {
46898             return ts.isModuleWithStringLiteralName(declaration) || (declaration.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(declaration));
46899         }
46900         function hasVisibleDeclarations(symbol, shouldComputeAliasToMakeVisible) {
46901             var aliasesToMakeVisible;
46902             if (!ts.every(ts.filter(symbol.declarations, function (d) { return d.kind !== 78 /* Identifier */; }), getIsDeclarationVisible)) {
46903                 return undefined;
46904             }
46905             return { accessibility: 0 /* Accessible */, aliasesToMakeVisible: aliasesToMakeVisible };
46906             function getIsDeclarationVisible(declaration) {
46907                 var _a, _b;
46908                 if (!isDeclarationVisible(declaration)) {
46909                     // Mark the unexported alias as visible if its parent is visible
46910                     // because these kind of aliases can be used to name types in declaration file
46911                     var anyImportSyntax = getAnyImportSyntax(declaration);
46912                     if (anyImportSyntax &&
46913                         !ts.hasSyntacticModifier(anyImportSyntax, 1 /* Export */) && // import clause without export
46914                         isDeclarationVisible(anyImportSyntax.parent)) {
46915                         return addVisibleAlias(declaration, anyImportSyntax);
46916                     }
46917                     else if (ts.isVariableDeclaration(declaration) && ts.isVariableStatement(declaration.parent.parent) &&
46918                         !ts.hasSyntacticModifier(declaration.parent.parent, 1 /* Export */) && // unexported variable statement
46919                         isDeclarationVisible(declaration.parent.parent.parent)) {
46920                         return addVisibleAlias(declaration, declaration.parent.parent);
46921                     }
46922                     else if (ts.isLateVisibilityPaintedStatement(declaration) // unexported top-level statement
46923                         && !ts.hasSyntacticModifier(declaration, 1 /* Export */)
46924                         && isDeclarationVisible(declaration.parent)) {
46925                         return addVisibleAlias(declaration, declaration);
46926                     }
46927                     else if (symbol.flags & 2097152 /* Alias */ && ts.isBindingElement(declaration) && ts.isInJSFile(declaration) && ((_a = declaration.parent) === null || _a === void 0 ? void 0 : _a.parent) // exported import-like top-level JS require statement
46928                         && ts.isVariableDeclaration(declaration.parent.parent)
46929                         && ((_b = declaration.parent.parent.parent) === null || _b === void 0 ? void 0 : _b.parent) && ts.isVariableStatement(declaration.parent.parent.parent.parent)
46930                         && !ts.hasSyntacticModifier(declaration.parent.parent.parent.parent, 1 /* Export */)
46931                         && declaration.parent.parent.parent.parent.parent // check if the thing containing the variable statement is visible (ie, the file)
46932                         && isDeclarationVisible(declaration.parent.parent.parent.parent.parent)) {
46933                         return addVisibleAlias(declaration, declaration.parent.parent.parent.parent);
46934                     }
46935                     // Declaration is not visible
46936                     return false;
46937                 }
46938                 return true;
46939             }
46940             function addVisibleAlias(declaration, aliasingStatement) {
46941                 // In function "buildTypeDisplay" where we decide whether to write type-alias or serialize types,
46942                 // we want to just check if type- alias is accessible or not but we don't care about emitting those alias at that time
46943                 // since we will do the emitting later in trackSymbol.
46944                 if (shouldComputeAliasToMakeVisible) {
46945                     getNodeLinks(declaration).isVisible = true;
46946                     aliasesToMakeVisible = ts.appendIfUnique(aliasesToMakeVisible, aliasingStatement);
46947                 }
46948                 return true;
46949             }
46950         }
46951         function isEntityNameVisible(entityName, enclosingDeclaration) {
46952             // get symbol of the first identifier of the entityName
46953             var meaning;
46954             if (entityName.parent.kind === 176 /* TypeQuery */ ||
46955                 ts.isExpressionWithTypeArgumentsInClassExtendsClause(entityName.parent) ||
46956                 entityName.parent.kind === 158 /* ComputedPropertyName */) {
46957                 // Typeof value
46958                 meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
46959             }
46960             else if (entityName.kind === 157 /* QualifiedName */ || entityName.kind === 201 /* PropertyAccessExpression */ ||
46961                 entityName.parent.kind === 260 /* ImportEqualsDeclaration */) {
46962                 // Left identifier from type reference or TypeAlias
46963                 // Entity name of the import declaration
46964                 meaning = 1920 /* Namespace */;
46965             }
46966             else {
46967                 // Type Reference or TypeAlias entity = Identifier
46968                 meaning = 788968 /* Type */;
46969             }
46970             var firstIdentifier = ts.getFirstIdentifier(entityName);
46971             var symbol = resolveName(enclosingDeclaration, firstIdentifier.escapedText, meaning, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
46972             if (symbol && symbol.flags & 262144 /* TypeParameter */ && meaning & 788968 /* Type */) {
46973                 return { accessibility: 0 /* Accessible */ };
46974             }
46975             // Verify if the symbol is accessible
46976             return (symbol && hasVisibleDeclarations(symbol, /*shouldComputeAliasToMakeVisible*/ true)) || {
46977                 accessibility: 1 /* NotAccessible */,
46978                 errorSymbolName: ts.getTextOfNode(firstIdentifier),
46979                 errorNode: firstIdentifier
46980             };
46981         }
46982         function symbolToString(symbol, enclosingDeclaration, meaning, flags, writer) {
46983             if (flags === void 0) { flags = 4 /* AllowAnyNodeKind */; }
46984             var nodeFlags = 70221824 /* IgnoreErrors */;
46985             if (flags & 2 /* UseOnlyExternalAliasing */) {
46986                 nodeFlags |= 128 /* UseOnlyExternalAliasing */;
46987             }
46988             if (flags & 1 /* WriteTypeParametersOrArguments */) {
46989                 nodeFlags |= 512 /* WriteTypeParametersInQualifiedName */;
46990             }
46991             if (flags & 8 /* UseAliasDefinedOutsideCurrentScope */) {
46992                 nodeFlags |= 16384 /* UseAliasDefinedOutsideCurrentScope */;
46993             }
46994             if (flags & 16 /* DoNotIncludeSymbolChain */) {
46995                 nodeFlags |= 134217728 /* DoNotIncludeSymbolChain */;
46996             }
46997             var builder = flags & 4 /* AllowAnyNodeKind */ ? nodeBuilder.symbolToExpression : nodeBuilder.symbolToEntityName;
46998             return writer ? symbolToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(symbolToStringWorker);
46999             function symbolToStringWorker(writer) {
47000                 var entity = builder(symbol, meaning, enclosingDeclaration, nodeFlags); // TODO: GH#18217
47001                 // add neverAsciiEscape for GH#39027
47002                 var printer = (enclosingDeclaration === null || enclosingDeclaration === void 0 ? void 0 : enclosingDeclaration.kind) === 297 /* SourceFile */ ? ts.createPrinter({ removeComments: true, neverAsciiEscape: true }) : ts.createPrinter({ removeComments: true });
47003                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
47004                 printer.writeNode(4 /* Unspecified */, entity, /*sourceFile*/ sourceFile, writer);
47005                 return writer;
47006             }
47007         }
47008         function signatureToString(signature, enclosingDeclaration, flags, kind, writer) {
47009             if (flags === void 0) { flags = 0 /* None */; }
47010             return writer ? signatureToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(signatureToStringWorker);
47011             function signatureToStringWorker(writer) {
47012                 var sigOutput;
47013                 if (flags & 262144 /* WriteArrowStyleSignature */) {
47014                     sigOutput = kind === 1 /* Construct */ ? 175 /* ConstructorType */ : 174 /* FunctionType */;
47015                 }
47016                 else {
47017                     sigOutput = kind === 1 /* Construct */ ? 170 /* ConstructSignature */ : 169 /* CallSignature */;
47018                 }
47019                 var sig = nodeBuilder.signatureToSignatureDeclaration(signature, sigOutput, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */);
47020                 var printer = ts.createPrinter({ removeComments: true, omitTrailingSemicolon: true });
47021                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
47022                 printer.writeNode(4 /* Unspecified */, sig, /*sourceFile*/ sourceFile, ts.getTrailingSemicolonDeferringWriter(writer)); // TODO: GH#18217
47023                 return writer;
47024             }
47025         }
47026         function typeToString(type, enclosingDeclaration, flags, writer) {
47027             if (flags === void 0) { flags = 1048576 /* AllowUniqueESSymbolType */ | 16384 /* UseAliasDefinedOutsideCurrentScope */; }
47028             if (writer === void 0) { writer = ts.createTextWriter(""); }
47029             var noTruncation = compilerOptions.noErrorTruncation || flags & 1 /* NoTruncation */;
47030             var typeNode = nodeBuilder.typeToTypeNode(type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | (noTruncation ? 1 /* NoTruncation */ : 0), writer);
47031             if (typeNode === undefined)
47032                 return ts.Debug.fail("should always get typenode");
47033             var options = { removeComments: true };
47034             var printer = ts.createPrinter(options);
47035             var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
47036             printer.writeNode(4 /* Unspecified */, typeNode, /*sourceFile*/ sourceFile, writer);
47037             var result = writer.getText();
47038             var maxLength = noTruncation ? ts.noTruncationMaximumTruncationLength * 2 : ts.defaultMaximumTruncationLength * 2;
47039             if (maxLength && result && result.length >= maxLength) {
47040                 return result.substr(0, maxLength - "...".length) + "...";
47041             }
47042             return result;
47043         }
47044         function getTypeNamesForErrorDisplay(left, right) {
47045             var leftStr = symbolValueDeclarationIsContextSensitive(left.symbol) ? typeToString(left, left.symbol.valueDeclaration) : typeToString(left);
47046             var rightStr = symbolValueDeclarationIsContextSensitive(right.symbol) ? typeToString(right, right.symbol.valueDeclaration) : typeToString(right);
47047             if (leftStr === rightStr) {
47048                 leftStr = getTypeNameForErrorDisplay(left);
47049                 rightStr = getTypeNameForErrorDisplay(right);
47050             }
47051             return [leftStr, rightStr];
47052         }
47053         function getTypeNameForErrorDisplay(type) {
47054             return typeToString(type, /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */);
47055         }
47056         function symbolValueDeclarationIsContextSensitive(symbol) {
47057             return symbol && symbol.valueDeclaration && ts.isExpression(symbol.valueDeclaration) && !isContextSensitive(symbol.valueDeclaration);
47058         }
47059         function toNodeBuilderFlags(flags) {
47060             if (flags === void 0) { flags = 0 /* None */; }
47061             return flags & 814775659 /* NodeBuilderFlagsMask */;
47062         }
47063         function isClassInstanceSide(type) {
47064             return !!type.symbol && !!(type.symbol.flags & 32 /* Class */) && (type === getDeclaredTypeOfClassOrInterface(type.symbol) || !!(ts.getObjectFlags(type) & 1073741824 /* IsClassInstanceClone */));
47065         }
47066         function createNodeBuilder() {
47067             return {
47068                 typeToTypeNode: function (type, enclosingDeclaration, flags, tracker) {
47069                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeToTypeNodeHelper(type, context); });
47070                 },
47071                 indexInfoToIndexSignatureDeclaration: function (indexInfo, kind, enclosingDeclaration, flags, tracker) {
47072                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context, /*typeNode*/ undefined); });
47073                 },
47074                 signatureToSignatureDeclaration: function (signature, kind, enclosingDeclaration, flags, tracker) {
47075                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return signatureToSignatureDeclarationHelper(signature, kind, context); });
47076                 },
47077                 symbolToEntityName: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
47078                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToName(symbol, context, meaning, /*expectsIdentifier*/ false); });
47079                 },
47080                 symbolToExpression: function (symbol, meaning, enclosingDeclaration, flags, tracker) {
47081                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToExpression(symbol, context, meaning); });
47082                 },
47083                 symbolToTypeParameterDeclarations: function (symbol, enclosingDeclaration, flags, tracker) {
47084                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParametersToTypeParameterDeclarations(symbol, context); });
47085                 },
47086                 symbolToParameterDeclaration: function (symbol, enclosingDeclaration, flags, tracker) {
47087                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolToParameterDeclaration(symbol, context); });
47088                 },
47089                 typeParameterToDeclaration: function (parameter, enclosingDeclaration, flags, tracker) {
47090                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return typeParameterToDeclaration(parameter, context); });
47091                 },
47092                 symbolTableToDeclarationStatements: function (symbolTable, enclosingDeclaration, flags, tracker, bundled) {
47093                     return withContext(enclosingDeclaration, flags, tracker, function (context) { return symbolTableToDeclarationStatements(symbolTable, context, bundled); });
47094                 },
47095             };
47096             function withContext(enclosingDeclaration, flags, tracker, cb) {
47097                 var _a, _b;
47098                 ts.Debug.assert(enclosingDeclaration === undefined || (enclosingDeclaration.flags & 8 /* Synthesized */) === 0);
47099                 var context = {
47100                     enclosingDeclaration: enclosingDeclaration,
47101                     flags: flags || 0 /* None */,
47102                     // If no full tracker is provided, fake up a dummy one with a basic limited-functionality moduleResolverHost
47103                     tracker: tracker && tracker.trackSymbol ? tracker : { trackSymbol: ts.noop, moduleResolverHost: flags & 134217728 /* DoNotIncludeSymbolChain */ ? {
47104                             getCommonSourceDirectory: !!host.getCommonSourceDirectory ? function () { return host.getCommonSourceDirectory(); } : function () { return ""; },
47105                             getSourceFiles: function () { return host.getSourceFiles(); },
47106                             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
47107                             getSymlinkCache: ts.maybeBind(host, host.getSymlinkCache),
47108                             useCaseSensitiveFileNames: ts.maybeBind(host, host.useCaseSensitiveFileNames),
47109                             redirectTargetsMap: host.redirectTargetsMap,
47110                             getProjectReferenceRedirect: function (fileName) { return host.getProjectReferenceRedirect(fileName); },
47111                             isSourceOfProjectReferenceRedirect: function (fileName) { return host.isSourceOfProjectReferenceRedirect(fileName); },
47112                             fileExists: function (fileName) { return host.fileExists(fileName); },
47113                         } : undefined },
47114                     encounteredError: false,
47115                     visitedTypes: undefined,
47116                     symbolDepth: undefined,
47117                     inferTypeParameters: undefined,
47118                     approximateLength: 0
47119                 };
47120                 var resultingNode = cb(context);
47121                 if (context.truncating && context.flags & 1 /* NoTruncation */) {
47122                     (_b = (_a = context.tracker) === null || _a === void 0 ? void 0 : _a.reportTruncationError) === null || _b === void 0 ? void 0 : _b.call(_a);
47123                 }
47124                 return context.encounteredError ? undefined : resultingNode;
47125             }
47126             function checkTruncationLength(context) {
47127                 if (context.truncating)
47128                     return context.truncating;
47129                 return context.truncating = context.approximateLength > ((context.flags & 1 /* NoTruncation */) ? ts.noTruncationMaximumTruncationLength : ts.defaultMaximumTruncationLength);
47130             }
47131             function typeToTypeNodeHelper(type, context) {
47132                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
47133                     cancellationToken.throwIfCancellationRequested();
47134                 }
47135                 var inTypeAlias = context.flags & 8388608 /* InTypeAlias */;
47136                 context.flags &= ~8388608 /* InTypeAlias */;
47137                 if (!type) {
47138                     if (!(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
47139                         context.encounteredError = true;
47140                         return undefined; // TODO: GH#18217
47141                     }
47142                     context.approximateLength += 3;
47143                     return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47144                 }
47145                 if (!(context.flags & 536870912 /* NoTypeReduction */)) {
47146                     type = getReducedType(type);
47147                 }
47148                 if (type.flags & 1 /* Any */) {
47149                     context.approximateLength += 3;
47150                     return ts.factory.createKeywordTypeNode(type === intrinsicMarkerType ? 136 /* IntrinsicKeyword */ : 128 /* AnyKeyword */);
47151                 }
47152                 if (type.flags & 2 /* Unknown */) {
47153                     return ts.factory.createKeywordTypeNode(152 /* UnknownKeyword */);
47154                 }
47155                 if (type.flags & 4 /* String */) {
47156                     context.approximateLength += 6;
47157                     return ts.factory.createKeywordTypeNode(147 /* StringKeyword */);
47158                 }
47159                 if (type.flags & 8 /* Number */) {
47160                     context.approximateLength += 6;
47161                     return ts.factory.createKeywordTypeNode(144 /* NumberKeyword */);
47162                 }
47163                 if (type.flags & 64 /* BigInt */) {
47164                     context.approximateLength += 6;
47165                     return ts.factory.createKeywordTypeNode(155 /* BigIntKeyword */);
47166                 }
47167                 if (type.flags & 16 /* Boolean */) {
47168                     context.approximateLength += 7;
47169                     return ts.factory.createKeywordTypeNode(131 /* BooleanKeyword */);
47170                 }
47171                 if (type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */)) {
47172                     var parentSymbol = getParentOfSymbol(type.symbol);
47173                     var parentName = symbolToTypeNode(parentSymbol, context, 788968 /* Type */);
47174                     if (getDeclaredTypeOfSymbol(parentSymbol) === type) {
47175                         return parentName;
47176                     }
47177                     var memberName = ts.symbolName(type.symbol);
47178                     if (ts.isIdentifierText(memberName, 0 /* ES3 */)) {
47179                         return appendReferenceToType(parentName, ts.factory.createTypeReferenceNode(memberName, /*typeArguments*/ undefined));
47180                     }
47181                     if (ts.isImportTypeNode(parentName)) {
47182                         parentName.isTypeOf = true; // mutably update, node is freshly manufactured anyhow
47183                         return ts.factory.createIndexedAccessTypeNode(parentName, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(memberName)));
47184                     }
47185                     else if (ts.isTypeReferenceNode(parentName)) {
47186                         return ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeQueryNode(parentName.typeName), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(memberName)));
47187                     }
47188                     else {
47189                         return ts.Debug.fail("Unhandled type node kind returned from `symbolToTypeNode`.");
47190                     }
47191                 }
47192                 if (type.flags & 1056 /* EnumLike */) {
47193                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */);
47194                 }
47195                 if (type.flags & 128 /* StringLiteral */) {
47196                     context.approximateLength += (type.value.length + 2);
47197                     return ts.factory.createLiteralTypeNode(ts.setEmitFlags(ts.factory.createStringLiteral(type.value, !!(context.flags & 268435456 /* UseSingleQuotesForStringLiteralType */)), 16777216 /* NoAsciiEscaping */));
47198                 }
47199                 if (type.flags & 256 /* NumberLiteral */) {
47200                     var value = type.value;
47201                     context.approximateLength += ("" + value).length;
47202                     return ts.factory.createLiteralTypeNode(value < 0 ? ts.factory.createPrefixUnaryExpression(40 /* MinusToken */, ts.factory.createNumericLiteral(-value)) : ts.factory.createNumericLiteral(value));
47203                 }
47204                 if (type.flags & 2048 /* BigIntLiteral */) {
47205                     context.approximateLength += (ts.pseudoBigIntToString(type.value).length) + 1;
47206                     return ts.factory.createLiteralTypeNode((ts.factory.createBigIntLiteral(type.value)));
47207                 }
47208                 if (type.flags & 512 /* BooleanLiteral */) {
47209                     context.approximateLength += type.intrinsicName.length;
47210                     return ts.factory.createLiteralTypeNode(type.intrinsicName === "true" ? ts.factory.createTrue() : ts.factory.createFalse());
47211                 }
47212                 if (type.flags & 8192 /* UniqueESSymbol */) {
47213                     if (!(context.flags & 1048576 /* AllowUniqueESSymbolType */)) {
47214                         if (isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
47215                             context.approximateLength += 6;
47216                             return symbolToTypeNode(type.symbol, context, 111551 /* Value */);
47217                         }
47218                         if (context.tracker.reportInaccessibleUniqueSymbolError) {
47219                             context.tracker.reportInaccessibleUniqueSymbolError();
47220                         }
47221                     }
47222                     context.approximateLength += 13;
47223                     return ts.factory.createTypeOperatorNode(151 /* UniqueKeyword */, ts.factory.createKeywordTypeNode(148 /* SymbolKeyword */));
47224                 }
47225                 if (type.flags & 16384 /* Void */) {
47226                     context.approximateLength += 4;
47227                     return ts.factory.createKeywordTypeNode(113 /* VoidKeyword */);
47228                 }
47229                 if (type.flags & 32768 /* Undefined */) {
47230                     context.approximateLength += 9;
47231                     return ts.factory.createKeywordTypeNode(150 /* UndefinedKeyword */);
47232                 }
47233                 if (type.flags & 65536 /* Null */) {
47234                     context.approximateLength += 4;
47235                     return ts.factory.createLiteralTypeNode(ts.factory.createNull());
47236                 }
47237                 if (type.flags & 131072 /* Never */) {
47238                     context.approximateLength += 5;
47239                     return ts.factory.createKeywordTypeNode(141 /* NeverKeyword */);
47240                 }
47241                 if (type.flags & 4096 /* ESSymbol */) {
47242                     context.approximateLength += 6;
47243                     return ts.factory.createKeywordTypeNode(148 /* SymbolKeyword */);
47244                 }
47245                 if (type.flags & 67108864 /* NonPrimitive */) {
47246                     context.approximateLength += 6;
47247                     return ts.factory.createKeywordTypeNode(145 /* ObjectKeyword */);
47248                 }
47249                 if (isThisTypeParameter(type)) {
47250                     if (context.flags & 4194304 /* InObjectTypeLiteral */) {
47251                         if (!context.encounteredError && !(context.flags & 32768 /* AllowThisInObjectLiteral */)) {
47252                             context.encounteredError = true;
47253                         }
47254                         if (context.tracker.reportInaccessibleThisError) {
47255                             context.tracker.reportInaccessibleThisError();
47256                         }
47257                     }
47258                     context.approximateLength += 4;
47259                     return ts.factory.createThisTypeNode();
47260                 }
47261                 if (!inTypeAlias && type.aliasSymbol && (context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */ || isTypeSymbolAccessible(type.aliasSymbol, context.enclosingDeclaration))) {
47262                     var typeArgumentNodes = mapToTypeNodes(type.aliasTypeArguments, context);
47263                     if (isReservedMemberName(type.aliasSymbol.escapedName) && !(type.aliasSymbol.flags & 32 /* Class */))
47264                         return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""), typeArgumentNodes);
47265                     return symbolToTypeNode(type.aliasSymbol, context, 788968 /* Type */, typeArgumentNodes);
47266                 }
47267                 var objectFlags = ts.getObjectFlags(type);
47268                 if (objectFlags & 4 /* Reference */) {
47269                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
47270                     return type.node ? visitAndTransformType(type, typeReferenceToTypeNode) : typeReferenceToTypeNode(type);
47271                 }
47272                 if (type.flags & 262144 /* TypeParameter */ || objectFlags & 3 /* ClassOrInterface */) {
47273                     if (type.flags & 262144 /* TypeParameter */ && ts.contains(context.inferTypeParameters, type)) {
47274                         context.approximateLength += (ts.symbolName(type.symbol).length + 6);
47275                         return ts.factory.createInferTypeNode(typeParameterToDeclarationWithConstraint(type, context, /*constraintNode*/ undefined));
47276                     }
47277                     if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ &&
47278                         type.flags & 262144 /* TypeParameter */ &&
47279                         !isTypeSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
47280                         var name = typeParameterToName(type, context);
47281                         context.approximateLength += ts.idText(name).length;
47282                         return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(ts.idText(name)), /*typeArguments*/ undefined);
47283                     }
47284                     // Ignore constraint/default when creating a usage (as opposed to declaration) of a type parameter.
47285                     return type.symbol
47286                         ? symbolToTypeNode(type.symbol, context, 788968 /* Type */)
47287                         : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("?"), /*typeArguments*/ undefined);
47288                 }
47289                 if (type.flags & (1048576 /* Union */ | 2097152 /* Intersection */)) {
47290                     var types = type.flags & 1048576 /* Union */ ? formatUnionTypes(type.types) : type.types;
47291                     if (ts.length(types) === 1) {
47292                         return typeToTypeNodeHelper(types[0], context);
47293                     }
47294                     var typeNodes = mapToTypeNodes(types, context, /*isBareList*/ true);
47295                     if (typeNodes && typeNodes.length > 0) {
47296                         var unionOrIntersectionTypeNode = type.flags & 1048576 /* Union */ ? ts.factory.createUnionTypeNode(typeNodes) : ts.factory.createIntersectionTypeNode(typeNodes);
47297                         return unionOrIntersectionTypeNode;
47298                     }
47299                     else {
47300                         if (!context.encounteredError && !(context.flags & 262144 /* AllowEmptyUnionOrIntersection */)) {
47301                             context.encounteredError = true;
47302                         }
47303                         return undefined; // TODO: GH#18217
47304                     }
47305                 }
47306                 if (objectFlags & (16 /* Anonymous */ | 32 /* Mapped */)) {
47307                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
47308                     // The type is an object literal type.
47309                     return createAnonymousTypeNode(type);
47310                 }
47311                 if (type.flags & 4194304 /* Index */) {
47312                     var indexedType = type.type;
47313                     context.approximateLength += 6;
47314                     var indexTypeNode = typeToTypeNodeHelper(indexedType, context);
47315                     return ts.factory.createTypeOperatorNode(138 /* KeyOfKeyword */, indexTypeNode);
47316                 }
47317                 if (type.flags & 134217728 /* TemplateLiteral */) {
47318                     var texts_1 = type.texts;
47319                     var types_1 = type.types;
47320                     var templateHead = ts.factory.createTemplateHead(texts_1[0]);
47321                     var templateSpans = ts.factory.createNodeArray(ts.map(types_1, function (t, i) { return ts.factory.createTemplateLiteralTypeSpan(typeToTypeNodeHelper(t, context), (i < types_1.length - 1 ? ts.factory.createTemplateMiddle : ts.factory.createTemplateTail)(texts_1[i + 1])); }));
47322                     context.approximateLength += 2;
47323                     return ts.factory.createTemplateLiteralType(templateHead, templateSpans);
47324                 }
47325                 if (type.flags & 268435456 /* StringMapping */) {
47326                     var typeNode = typeToTypeNodeHelper(type.type, context);
47327                     return symbolToTypeNode(type.symbol, context, 788968 /* Type */, [typeNode]);
47328                 }
47329                 if (type.flags & 8388608 /* IndexedAccess */) {
47330                     var objectTypeNode = typeToTypeNodeHelper(type.objectType, context);
47331                     var indexTypeNode = typeToTypeNodeHelper(type.indexType, context);
47332                     context.approximateLength += 2;
47333                     return ts.factory.createIndexedAccessTypeNode(objectTypeNode, indexTypeNode);
47334                 }
47335                 if (type.flags & 16777216 /* Conditional */) {
47336                     var checkTypeNode = typeToTypeNodeHelper(type.checkType, context);
47337                     var saveInferTypeParameters = context.inferTypeParameters;
47338                     context.inferTypeParameters = type.root.inferTypeParameters;
47339                     var extendsTypeNode = typeToTypeNodeHelper(type.extendsType, context);
47340                     context.inferTypeParameters = saveInferTypeParameters;
47341                     var trueTypeNode = typeToTypeNodeOrCircularityElision(getTrueTypeFromConditionalType(type));
47342                     var falseTypeNode = typeToTypeNodeOrCircularityElision(getFalseTypeFromConditionalType(type));
47343                     context.approximateLength += 15;
47344                     return ts.factory.createConditionalTypeNode(checkTypeNode, extendsTypeNode, trueTypeNode, falseTypeNode);
47345                 }
47346                 if (type.flags & 33554432 /* Substitution */) {
47347                     return typeToTypeNodeHelper(type.baseType, context);
47348                 }
47349                 return ts.Debug.fail("Should be unreachable.");
47350                 function typeToTypeNodeOrCircularityElision(type) {
47351                     var _a, _b, _c;
47352                     if (type.flags & 1048576 /* Union */) {
47353                         if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(getTypeId(type))) {
47354                             if (!(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
47355                                 context.encounteredError = true;
47356                                 (_c = (_b = context.tracker) === null || _b === void 0 ? void 0 : _b.reportCyclicStructureError) === null || _c === void 0 ? void 0 : _c.call(_b);
47357                             }
47358                             return createElidedInformationPlaceholder(context);
47359                         }
47360                         return visitAndTransformType(type, function (type) { return typeToTypeNodeHelper(type, context); });
47361                     }
47362                     return typeToTypeNodeHelper(type, context);
47363                 }
47364                 function createMappedTypeNodeFromType(type) {
47365                     ts.Debug.assert(!!(type.flags & 524288 /* Object */));
47366                     var readonlyToken = type.declaration.readonlyToken ? ts.factory.createToken(type.declaration.readonlyToken.kind) : undefined;
47367                     var questionToken = type.declaration.questionToken ? ts.factory.createToken(type.declaration.questionToken.kind) : undefined;
47368                     var appropriateConstraintTypeNode;
47369                     if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
47370                         // We have a { [P in keyof T]: X }
47371                         // We do this to ensure we retain the toplevel keyof-ness of the type which may be lost due to keyof distribution during `getConstraintTypeFromMappedType`
47372                         appropriateConstraintTypeNode = ts.factory.createTypeOperatorNode(138 /* KeyOfKeyword */, typeToTypeNodeHelper(getModifiersTypeFromMappedType(type), context));
47373                     }
47374                     else {
47375                         appropriateConstraintTypeNode = typeToTypeNodeHelper(getConstraintTypeFromMappedType(type), context);
47376                     }
47377                     var typeParameterNode = typeParameterToDeclarationWithConstraint(getTypeParameterFromMappedType(type), context, appropriateConstraintTypeNode);
47378                     var nameTypeNode = type.declaration.nameType ? typeToTypeNodeHelper(getNameTypeFromMappedType(type), context) : undefined;
47379                     var templateTypeNode = typeToTypeNodeHelper(getTemplateTypeFromMappedType(type), context);
47380                     var mappedTypeNode = ts.factory.createMappedTypeNode(readonlyToken, typeParameterNode, nameTypeNode, questionToken, templateTypeNode);
47381                     context.approximateLength += 10;
47382                     return ts.setEmitFlags(mappedTypeNode, 1 /* SingleLine */);
47383                 }
47384                 function createAnonymousTypeNode(type) {
47385                     var _a;
47386                     var typeId = type.id;
47387                     var symbol = type.symbol;
47388                     if (symbol) {
47389                         var isInstanceType = isClassInstanceSide(type) ? 788968 /* Type */ : 111551 /* Value */;
47390                         if (isJSConstructor(symbol.valueDeclaration)) {
47391                             // Instance and static types share the same symbol; only add 'typeof' for the static side.
47392                             return symbolToTypeNode(symbol, context, isInstanceType);
47393                         }
47394                         // Always use 'typeof T' for type of class, enum, and module objects
47395                         else if (symbol.flags & 32 /* Class */ && !getBaseTypeVariableOfClass(symbol) && !(symbol.valueDeclaration.kind === 221 /* ClassExpression */ && context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) ||
47396                             symbol.flags & (384 /* Enum */ | 512 /* ValueModule */) ||
47397                             shouldWriteTypeOfFunctionSymbol()) {
47398                             return symbolToTypeNode(symbol, context, isInstanceType);
47399                         }
47400                         else if ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(typeId)) {
47401                             // If type is an anonymous type literal in a type alias declaration, use type alias name
47402                             var typeAlias = getTypeAliasForTypeLiteral(type);
47403                             if (typeAlias) {
47404                                 // The specified symbol flags need to be reinterpreted as type flags
47405                                 return symbolToTypeNode(typeAlias, context, 788968 /* Type */);
47406                             }
47407                             else {
47408                                 return createElidedInformationPlaceholder(context);
47409                             }
47410                         }
47411                         else {
47412                             return visitAndTransformType(type, createTypeNodeFromObjectType);
47413                         }
47414                     }
47415                     else {
47416                         // Anonymous types without a symbol are never circular.
47417                         return createTypeNodeFromObjectType(type);
47418                     }
47419                     function shouldWriteTypeOfFunctionSymbol() {
47420                         var _a;
47421                         var isStaticMethodSymbol = !!(symbol.flags & 8192 /* Method */) && // typeof static method
47422                             ts.some(symbol.declarations, function (declaration) { return ts.hasSyntacticModifier(declaration, 32 /* Static */); });
47423                         var isNonLocalFunctionSymbol = !!(symbol.flags & 16 /* Function */) &&
47424                             (symbol.parent || // is exported function symbol
47425                                 ts.forEach(symbol.declarations, function (declaration) {
47426                                     return declaration.parent.kind === 297 /* SourceFile */ || declaration.parent.kind === 257 /* ModuleBlock */;
47427                                 }));
47428                         if (isStaticMethodSymbol || isNonLocalFunctionSymbol) {
47429                             // typeof is allowed only for static/non local functions
47430                             return (!!(context.flags & 4096 /* UseTypeOfFunction */) || ((_a = context.visitedTypes) === null || _a === void 0 ? void 0 : _a.has(typeId))) && // it is type of the symbol uses itself recursively
47431                                 (!(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
47432                         }
47433                     }
47434                 }
47435                 function visitAndTransformType(type, transform) {
47436                     var typeId = type.id;
47437                     var isConstructorObject = ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol && type.symbol.flags & 32 /* Class */;
47438                     var id = ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? "N" + getNodeId(type.node) :
47439                         type.symbol ? (isConstructorObject ? "+" : "") + getSymbolId(type.symbol) :
47440                             undefined;
47441                     // Since instantiations of the same anonymous type have the same symbol, tracking symbols instead
47442                     // of types allows us to catch circular references to instantiations of the same anonymous type
47443                     if (!context.visitedTypes) {
47444                         context.visitedTypes = new ts.Set();
47445                     }
47446                     if (id && !context.symbolDepth) {
47447                         context.symbolDepth = new ts.Map();
47448                     }
47449                     var depth;
47450                     if (id) {
47451                         depth = context.symbolDepth.get(id) || 0;
47452                         if (depth > 10) {
47453                             return createElidedInformationPlaceholder(context);
47454                         }
47455                         context.symbolDepth.set(id, depth + 1);
47456                     }
47457                     context.visitedTypes.add(typeId);
47458                     var result = transform(type);
47459                     context.visitedTypes.delete(typeId);
47460                     if (id) {
47461                         context.symbolDepth.set(id, depth);
47462                     }
47463                     return result;
47464                 }
47465                 function createTypeNodeFromObjectType(type) {
47466                     if (isGenericMappedType(type) || type.containsError) {
47467                         return createMappedTypeNodeFromType(type);
47468                     }
47469                     var resolved = resolveStructuredTypeMembers(type);
47470                     if (!resolved.properties.length && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
47471                         if (!resolved.callSignatures.length && !resolved.constructSignatures.length) {
47472                             context.approximateLength += 2;
47473                             return ts.setEmitFlags(ts.factory.createTypeLiteralNode(/*members*/ undefined), 1 /* SingleLine */);
47474                         }
47475                         if (resolved.callSignatures.length === 1 && !resolved.constructSignatures.length) {
47476                             var signature = resolved.callSignatures[0];
47477                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 174 /* FunctionType */, context);
47478                             return signatureNode;
47479                         }
47480                         if (resolved.constructSignatures.length === 1 && !resolved.callSignatures.length) {
47481                             var signature = resolved.constructSignatures[0];
47482                             var signatureNode = signatureToSignatureDeclarationHelper(signature, 175 /* ConstructorType */, context);
47483                             return signatureNode;
47484                         }
47485                     }
47486                     var savedFlags = context.flags;
47487                     context.flags |= 4194304 /* InObjectTypeLiteral */;
47488                     var members = createTypeNodesFromResolvedType(resolved);
47489                     context.flags = savedFlags;
47490                     var typeLiteralNode = ts.factory.createTypeLiteralNode(members);
47491                     context.approximateLength += 2;
47492                     return ts.setEmitFlags(typeLiteralNode, (context.flags & 1024 /* MultilineObjectLiterals */) ? 0 : 1 /* SingleLine */);
47493                 }
47494                 function typeReferenceToTypeNode(type) {
47495                     var typeArguments = getTypeArguments(type);
47496                     if (type.target === globalArrayType || type.target === globalReadonlyArrayType) {
47497                         if (context.flags & 2 /* WriteArrayAsGenericType */) {
47498                             var typeArgumentNode = typeToTypeNodeHelper(typeArguments[0], context);
47499                             return ts.factory.createTypeReferenceNode(type.target === globalArrayType ? "Array" : "ReadonlyArray", [typeArgumentNode]);
47500                         }
47501                         var elementType = typeToTypeNodeHelper(typeArguments[0], context);
47502                         var arrayType = ts.factory.createArrayTypeNode(elementType);
47503                         return type.target === globalArrayType ? arrayType : ts.factory.createTypeOperatorNode(142 /* ReadonlyKeyword */, arrayType);
47504                     }
47505                     else if (type.target.objectFlags & 8 /* Tuple */) {
47506                         if (typeArguments.length > 0) {
47507                             var arity = getTypeReferenceArity(type);
47508                             var tupleConstituentNodes = mapToTypeNodes(typeArguments.slice(0, arity), context);
47509                             if (tupleConstituentNodes) {
47510                                 if (type.target.labeledElementDeclarations) {
47511                                     for (var i = 0; i < tupleConstituentNodes.length; i++) {
47512                                         var flags = type.target.elementFlags[i];
47513                                         tupleConstituentNodes[i] = ts.factory.createNamedTupleMember(flags & 12 /* Variable */ ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined, ts.factory.createIdentifier(ts.unescapeLeadingUnderscores(getTupleElementLabel(type.target.labeledElementDeclarations[i]))), flags & 2 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, flags & 4 /* Rest */ ? ts.factory.createArrayTypeNode(tupleConstituentNodes[i]) :
47514                                             tupleConstituentNodes[i]);
47515                                     }
47516                                 }
47517                                 else {
47518                                     for (var i = 0; i < Math.min(arity, tupleConstituentNodes.length); i++) {
47519                                         var flags = type.target.elementFlags[i];
47520                                         tupleConstituentNodes[i] =
47521                                             flags & 12 /* Variable */ ? ts.factory.createRestTypeNode(flags & 4 /* Rest */ ? ts.factory.createArrayTypeNode(tupleConstituentNodes[i]) : tupleConstituentNodes[i]) :
47522                                                 flags & 2 /* Optional */ ? ts.factory.createOptionalTypeNode(tupleConstituentNodes[i]) :
47523                                                     tupleConstituentNodes[i];
47524                                     }
47525                                 }
47526                                 var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode(tupleConstituentNodes), 1 /* SingleLine */);
47527                                 return type.target.readonly ? ts.factory.createTypeOperatorNode(142 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
47528                             }
47529                         }
47530                         if (context.encounteredError || (context.flags & 524288 /* AllowEmptyTuple */)) {
47531                             var tupleTypeNode = ts.setEmitFlags(ts.factory.createTupleTypeNode([]), 1 /* SingleLine */);
47532                             return type.target.readonly ? ts.factory.createTypeOperatorNode(142 /* ReadonlyKeyword */, tupleTypeNode) : tupleTypeNode;
47533                         }
47534                         context.encounteredError = true;
47535                         return undefined; // TODO: GH#18217
47536                     }
47537                     else if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */ &&
47538                         type.symbol.valueDeclaration &&
47539                         ts.isClassLike(type.symbol.valueDeclaration) &&
47540                         !isValueSymbolAccessible(type.symbol, context.enclosingDeclaration)) {
47541                         return createAnonymousTypeNode(type);
47542                     }
47543                     else {
47544                         var outerTypeParameters = type.target.outerTypeParameters;
47545                         var i = 0;
47546                         var resultType = void 0;
47547                         if (outerTypeParameters) {
47548                             var length_2 = outerTypeParameters.length;
47549                             while (i < length_2) {
47550                                 // Find group of type arguments for type parameters with the same declaring container.
47551                                 var start = i;
47552                                 var parent = getParentSymbolOfTypeParameter(outerTypeParameters[i]);
47553                                 do {
47554                                     i++;
47555                                 } while (i < length_2 && getParentSymbolOfTypeParameter(outerTypeParameters[i]) === parent);
47556                                 // When type parameters are their own type arguments for the whole group (i.e. we have
47557                                 // the default outer type arguments), we don't show the group.
47558                                 if (!ts.rangeEquals(outerTypeParameters, typeArguments, start, i)) {
47559                                     var typeArgumentSlice = mapToTypeNodes(typeArguments.slice(start, i), context);
47560                                     var flags_3 = context.flags;
47561                                     context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
47562                                     var ref = symbolToTypeNode(parent, context, 788968 /* Type */, typeArgumentSlice);
47563                                     context.flags = flags_3;
47564                                     resultType = !resultType ? ref : appendReferenceToType(resultType, ref);
47565                                 }
47566                             }
47567                         }
47568                         var typeArgumentNodes = void 0;
47569                         if (typeArguments.length > 0) {
47570                             var typeParameterCount = (type.target.typeParameters || ts.emptyArray).length;
47571                             typeArgumentNodes = mapToTypeNodes(typeArguments.slice(i, typeParameterCount), context);
47572                         }
47573                         var flags = context.flags;
47574                         context.flags |= 16 /* ForbidIndexedAccessSymbolReferences */;
47575                         var finalRef = symbolToTypeNode(type.symbol, context, 788968 /* Type */, typeArgumentNodes);
47576                         context.flags = flags;
47577                         return !resultType ? finalRef : appendReferenceToType(resultType, finalRef);
47578                     }
47579                 }
47580                 function appendReferenceToType(root, ref) {
47581                     if (ts.isImportTypeNode(root)) {
47582                         // first shift type arguments
47583                         var typeArguments = root.typeArguments;
47584                         var qualifier = root.qualifier;
47585                         if (qualifier) {
47586                             if (ts.isIdentifier(qualifier)) {
47587                                 qualifier = ts.factory.updateIdentifier(qualifier, typeArguments);
47588                             }
47589                             else {
47590                                 qualifier = ts.factory.updateQualifiedName(qualifier, qualifier.left, ts.factory.updateIdentifier(qualifier.right, typeArguments));
47591                             }
47592                         }
47593                         typeArguments = ref.typeArguments;
47594                         // then move qualifiers
47595                         var ids = getAccessStack(ref);
47596                         for (var _i = 0, ids_1 = ids; _i < ids_1.length; _i++) {
47597                             var id = ids_1[_i];
47598                             qualifier = qualifier ? ts.factory.createQualifiedName(qualifier, id) : id;
47599                         }
47600                         return ts.factory.updateImportTypeNode(root, root.argument, qualifier, typeArguments, root.isTypeOf);
47601                     }
47602                     else {
47603                         // first shift type arguments
47604                         var typeArguments = root.typeArguments;
47605                         var typeName = root.typeName;
47606                         if (ts.isIdentifier(typeName)) {
47607                             typeName = ts.factory.updateIdentifier(typeName, typeArguments);
47608                         }
47609                         else {
47610                             typeName = ts.factory.updateQualifiedName(typeName, typeName.left, ts.factory.updateIdentifier(typeName.right, typeArguments));
47611                         }
47612                         typeArguments = ref.typeArguments;
47613                         // then move qualifiers
47614                         var ids = getAccessStack(ref);
47615                         for (var _a = 0, ids_2 = ids; _a < ids_2.length; _a++) {
47616                             var id = ids_2[_a];
47617                             typeName = ts.factory.createQualifiedName(typeName, id);
47618                         }
47619                         return ts.factory.updateTypeReferenceNode(root, typeName, typeArguments);
47620                     }
47621                 }
47622                 function getAccessStack(ref) {
47623                     var state = ref.typeName;
47624                     var ids = [];
47625                     while (!ts.isIdentifier(state)) {
47626                         ids.unshift(state.right);
47627                         state = state.left;
47628                     }
47629                     ids.unshift(state);
47630                     return ids;
47631                 }
47632                 function createTypeNodesFromResolvedType(resolvedType) {
47633                     if (checkTruncationLength(context)) {
47634                         return [ts.factory.createPropertySignature(/*modifiers*/ undefined, "...", /*questionToken*/ undefined, /*type*/ undefined)];
47635                     }
47636                     var typeElements = [];
47637                     for (var _i = 0, _a = resolvedType.callSignatures; _i < _a.length; _i++) {
47638                         var signature = _a[_i];
47639                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 169 /* CallSignature */, context));
47640                     }
47641                     for (var _b = 0, _c = resolvedType.constructSignatures; _b < _c.length; _b++) {
47642                         var signature = _c[_b];
47643                         typeElements.push(signatureToSignatureDeclarationHelper(signature, 170 /* ConstructSignature */, context));
47644                     }
47645                     if (resolvedType.stringIndexInfo) {
47646                         var indexSignature = void 0;
47647                         if (resolvedType.objectFlags & 2048 /* ReverseMapped */) {
47648                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(createIndexInfo(anyType, resolvedType.stringIndexInfo.isReadonly, resolvedType.stringIndexInfo.declaration), 0 /* String */, context, createElidedInformationPlaceholder(context));
47649                         }
47650                         else {
47651                             indexSignature = indexInfoToIndexSignatureDeclarationHelper(resolvedType.stringIndexInfo, 0 /* String */, context, /*typeNode*/ undefined);
47652                         }
47653                         typeElements.push(indexSignature);
47654                     }
47655                     if (resolvedType.numberIndexInfo) {
47656                         typeElements.push(indexInfoToIndexSignatureDeclarationHelper(resolvedType.numberIndexInfo, 1 /* Number */, context, /*typeNode*/ undefined));
47657                     }
47658                     var properties = resolvedType.properties;
47659                     if (!properties) {
47660                         return typeElements;
47661                     }
47662                     var i = 0;
47663                     for (var _d = 0, properties_1 = properties; _d < properties_1.length; _d++) {
47664                         var propertySymbol = properties_1[_d];
47665                         i++;
47666                         if (context.flags & 2048 /* WriteClassExpressionAsTypeLiteral */) {
47667                             if (propertySymbol.flags & 4194304 /* Prototype */) {
47668                                 continue;
47669                             }
47670                             if (ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & (8 /* Private */ | 16 /* Protected */) && context.tracker.reportPrivateInBaseOfClassExpression) {
47671                                 context.tracker.reportPrivateInBaseOfClassExpression(ts.unescapeLeadingUnderscores(propertySymbol.escapedName));
47672                             }
47673                         }
47674                         if (checkTruncationLength(context) && (i + 2 < properties.length - 1)) {
47675                             typeElements.push(ts.factory.createPropertySignature(/*modifiers*/ undefined, "... " + (properties.length - i) + " more ...", /*questionToken*/ undefined, /*type*/ undefined));
47676                             addPropertyToElementList(properties[properties.length - 1], context, typeElements);
47677                             break;
47678                         }
47679                         addPropertyToElementList(propertySymbol, context, typeElements);
47680                     }
47681                     return typeElements.length ? typeElements : undefined;
47682                 }
47683             }
47684             function createElidedInformationPlaceholder(context) {
47685                 context.approximateLength += 3;
47686                 if (!(context.flags & 1 /* NoTruncation */)) {
47687                     return ts.factory.createTypeReferenceNode(ts.factory.createIdentifier("..."), /*typeArguments*/ undefined);
47688                 }
47689                 return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47690             }
47691             function addPropertyToElementList(propertySymbol, context, typeElements) {
47692                 var propertyIsReverseMapped = !!(ts.getCheckFlags(propertySymbol) & 8192 /* ReverseMapped */);
47693                 var propertyType = propertyIsReverseMapped && context.flags & 33554432 /* InReverseMappedType */ ?
47694                     anyType : getTypeOfSymbol(propertySymbol);
47695                 var saveEnclosingDeclaration = context.enclosingDeclaration;
47696                 context.enclosingDeclaration = undefined;
47697                 if (context.tracker.trackSymbol && ts.getCheckFlags(propertySymbol) & 4096 /* Late */) {
47698                     var decl = ts.first(propertySymbol.declarations);
47699                     if (hasLateBindableName(decl)) {
47700                         if (ts.isBinaryExpression(decl)) {
47701                             var name = ts.getNameOfDeclaration(decl);
47702                             if (name && ts.isElementAccessExpression(name) && ts.isPropertyAccessEntityNameExpression(name.argumentExpression)) {
47703                                 trackComputedName(name.argumentExpression, saveEnclosingDeclaration, context);
47704                             }
47705                         }
47706                         else {
47707                             trackComputedName(decl.name.expression, saveEnclosingDeclaration, context);
47708                         }
47709                     }
47710                 }
47711                 context.enclosingDeclaration = saveEnclosingDeclaration;
47712                 var propertyName = getPropertyNameNodeForSymbol(propertySymbol, context);
47713                 context.approximateLength += (ts.symbolName(propertySymbol).length + 1);
47714                 var optionalToken = propertySymbol.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
47715                 if (propertySymbol.flags & (16 /* Function */ | 8192 /* Method */) && !getPropertiesOfObjectType(propertyType).length && !isReadonlySymbol(propertySymbol)) {
47716                     var signatures = getSignaturesOfType(filterType(propertyType, function (t) { return !(t.flags & 32768 /* Undefined */); }), 0 /* Call */);
47717                     for (var _i = 0, signatures_1 = signatures; _i < signatures_1.length; _i++) {
47718                         var signature = signatures_1[_i];
47719                         var methodDeclaration = signatureToSignatureDeclarationHelper(signature, 164 /* MethodSignature */, context, { name: propertyName, questionToken: optionalToken });
47720                         typeElements.push(preserveCommentsOn(methodDeclaration));
47721                     }
47722                 }
47723                 else {
47724                     var savedFlags = context.flags;
47725                     context.flags |= propertyIsReverseMapped ? 33554432 /* InReverseMappedType */ : 0;
47726                     var propertyTypeNode = void 0;
47727                     if (propertyIsReverseMapped && !!(savedFlags & 33554432 /* InReverseMappedType */)) {
47728                         propertyTypeNode = createElidedInformationPlaceholder(context);
47729                     }
47730                     else {
47731                         propertyTypeNode = propertyType ? serializeTypeForDeclaration(context, propertyType, propertySymbol, saveEnclosingDeclaration) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47732                     }
47733                     context.flags = savedFlags;
47734                     var modifiers = isReadonlySymbol(propertySymbol) ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined;
47735                     if (modifiers) {
47736                         context.approximateLength += 9;
47737                     }
47738                     var propertySignature = ts.factory.createPropertySignature(modifiers, propertyName, optionalToken, propertyTypeNode);
47739                     typeElements.push(preserveCommentsOn(propertySignature));
47740                 }
47741                 function preserveCommentsOn(node) {
47742                     if (ts.some(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; })) {
47743                         var d = ts.find(propertySymbol.declarations, function (d) { return d.kind === 333 /* JSDocPropertyTag */; });
47744                         var commentText = d.comment;
47745                         if (commentText) {
47746                             ts.setSyntheticLeadingComments(node, [{ kind: 3 /* MultiLineCommentTrivia */, text: "*\n * " + commentText.replace(/\n/g, "\n * ") + "\n ", pos: -1, end: -1, hasTrailingNewLine: true }]);
47747                         }
47748                     }
47749                     else if (propertySymbol.valueDeclaration) {
47750                         // Copy comments to node for declaration emit
47751                         ts.setCommentRange(node, propertySymbol.valueDeclaration);
47752                     }
47753                     return node;
47754                 }
47755             }
47756             function mapToTypeNodes(types, context, isBareList) {
47757                 if (ts.some(types)) {
47758                     if (checkTruncationLength(context)) {
47759                         if (!isBareList) {
47760                             return [ts.factory.createTypeReferenceNode("...", /*typeArguments*/ undefined)];
47761                         }
47762                         else if (types.length > 2) {
47763                             return [
47764                                 typeToTypeNodeHelper(types[0], context),
47765                                 ts.factory.createTypeReferenceNode("... " + (types.length - 2) + " more ...", /*typeArguments*/ undefined),
47766                                 typeToTypeNodeHelper(types[types.length - 1], context)
47767                             ];
47768                         }
47769                     }
47770                     var mayHaveNameCollisions = !(context.flags & 64 /* UseFullyQualifiedType */);
47771                     /** Map from type reference identifier text to [type, index in `result` where the type node is] */
47772                     var seenNames = mayHaveNameCollisions ? ts.createUnderscoreEscapedMultiMap() : undefined;
47773                     var result_4 = [];
47774                     var i = 0;
47775                     for (var _i = 0, types_2 = types; _i < types_2.length; _i++) {
47776                         var type = types_2[_i];
47777                         i++;
47778                         if (checkTruncationLength(context) && (i + 2 < types.length - 1)) {
47779                             result_4.push(ts.factory.createTypeReferenceNode("... " + (types.length - i) + " more ...", /*typeArguments*/ undefined));
47780                             var typeNode_1 = typeToTypeNodeHelper(types[types.length - 1], context);
47781                             if (typeNode_1) {
47782                                 result_4.push(typeNode_1);
47783                             }
47784                             break;
47785                         }
47786                         context.approximateLength += 2; // Account for whitespace + separator
47787                         var typeNode = typeToTypeNodeHelper(type, context);
47788                         if (typeNode) {
47789                             result_4.push(typeNode);
47790                             if (seenNames && ts.isIdentifierTypeReference(typeNode)) {
47791                                 seenNames.add(typeNode.typeName.escapedText, [type, result_4.length - 1]);
47792                             }
47793                         }
47794                     }
47795                     if (seenNames) {
47796                         // To avoid printing types like `[Foo, Foo]` or `Bar & Bar` where
47797                         // occurrences of the same name actually come from different
47798                         // namespaces, go through the single-identifier type reference nodes
47799                         // we just generated, and see if any names were generated more than
47800                         // once while referring to different types. If so, regenerate the
47801                         // type node for each entry by that name with the
47802                         // `UseFullyQualifiedType` flag enabled.
47803                         var saveContextFlags = context.flags;
47804                         context.flags |= 64 /* UseFullyQualifiedType */;
47805                         seenNames.forEach(function (types) {
47806                             if (!ts.arrayIsHomogeneous(types, function (_a, _b) {
47807                                 var a = _a[0];
47808                                 var b = _b[0];
47809                                 return typesAreSameReference(a, b);
47810                             })) {
47811                                 for (var _i = 0, types_3 = types; _i < types_3.length; _i++) {
47812                                     var _a = types_3[_i], type = _a[0], resultIndex = _a[1];
47813                                     result_4[resultIndex] = typeToTypeNodeHelper(type, context);
47814                                 }
47815                             }
47816                         });
47817                         context.flags = saveContextFlags;
47818                     }
47819                     return result_4;
47820                 }
47821             }
47822             function typesAreSameReference(a, b) {
47823                 return a === b
47824                     || !!a.symbol && a.symbol === b.symbol
47825                     || !!a.aliasSymbol && a.aliasSymbol === b.aliasSymbol;
47826             }
47827             function indexInfoToIndexSignatureDeclarationHelper(indexInfo, kind, context, typeNode) {
47828                 var name = ts.getNameFromIndexInfo(indexInfo) || "x";
47829                 var indexerTypeNode = ts.factory.createKeywordTypeNode(kind === 0 /* String */ ? 147 /* StringKeyword */ : 144 /* NumberKeyword */);
47830                 var indexingParameter = ts.factory.createParameterDeclaration(
47831                 /*decorators*/ undefined, 
47832                 /*modifiers*/ undefined, 
47833                 /*dotDotDotToken*/ undefined, name, 
47834                 /*questionToken*/ undefined, indexerTypeNode, 
47835                 /*initializer*/ undefined);
47836                 if (!typeNode) {
47837                     typeNode = typeToTypeNodeHelper(indexInfo.type || anyType, context);
47838                 }
47839                 if (!indexInfo.type && !(context.flags & 2097152 /* AllowEmptyIndexInfoType */)) {
47840                     context.encounteredError = true;
47841                 }
47842                 context.approximateLength += (name.length + 4);
47843                 return ts.factory.createIndexSignature(
47844                 /*decorators*/ undefined, indexInfo.isReadonly ? [ts.factory.createToken(142 /* ReadonlyKeyword */)] : undefined, [indexingParameter], typeNode);
47845             }
47846             function signatureToSignatureDeclarationHelper(signature, kind, context, options) {
47847                 var _a, _b, _c, _d;
47848                 var suppressAny = context.flags & 256 /* SuppressAnyReturnType */;
47849                 if (suppressAny)
47850                     context.flags &= ~256 /* SuppressAnyReturnType */; // suppress only toplevel `any`s
47851                 var typeParameters;
47852                 var typeArguments;
47853                 if (context.flags & 32 /* WriteTypeArgumentsOfSignature */ && signature.target && signature.mapper && signature.target.typeParameters) {
47854                     typeArguments = signature.target.typeParameters.map(function (parameter) { return typeToTypeNodeHelper(instantiateType(parameter, signature.mapper), context); });
47855                 }
47856                 else {
47857                     typeParameters = signature.typeParameters && signature.typeParameters.map(function (parameter) { return typeParameterToDeclaration(parameter, context); });
47858                 }
47859                 var expandedParams = getExpandedParameters(signature, /*skipUnionExpanding*/ true)[0];
47860                 // If the expanded parameter list had a variadic in a non-trailing position, don't expand it
47861                 var parameters = (ts.some(expandedParams, function (p) { return p !== expandedParams[expandedParams.length - 1] && !!(ts.getCheckFlags(p) & 32768 /* RestParameter */); }) ? signature.parameters : expandedParams).map(function (parameter) { return symbolToParameterDeclaration(parameter, context, kind === 166 /* Constructor */, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports); });
47862                 if (signature.thisParameter) {
47863                     var thisParameter = symbolToParameterDeclaration(signature.thisParameter, context);
47864                     parameters.unshift(thisParameter);
47865                 }
47866                 var returnTypeNode;
47867                 var typePredicate = getTypePredicateOfSignature(signature);
47868                 if (typePredicate) {
47869                     var assertsModifier = typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
47870                         ts.factory.createToken(127 /* AssertsKeyword */) :
47871                         undefined;
47872                     var parameterName = typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ?
47873                         ts.setEmitFlags(ts.factory.createIdentifier(typePredicate.parameterName), 16777216 /* NoAsciiEscaping */) :
47874                         ts.factory.createThisTypeNode();
47875                     var typeNode = typePredicate.type && typeToTypeNodeHelper(typePredicate.type, context);
47876                     returnTypeNode = ts.factory.createTypePredicateNode(assertsModifier, parameterName, typeNode);
47877                 }
47878                 else {
47879                     var returnType = getReturnTypeOfSignature(signature);
47880                     if (returnType && !(suppressAny && isTypeAny(returnType))) {
47881                         returnTypeNode = serializeReturnTypeForSignature(context, returnType, signature, options === null || options === void 0 ? void 0 : options.privateSymbolVisitor, options === null || options === void 0 ? void 0 : options.bundledImports);
47882                     }
47883                     else if (!suppressAny) {
47884                         returnTypeNode = ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
47885                     }
47886                 }
47887                 context.approximateLength += 3; // Usually a signature contributes a few more characters than this, but 3 is the minimum
47888                 var node = kind === 169 /* CallSignature */ ? ts.factory.createCallSignature(typeParameters, parameters, returnTypeNode) :
47889                     kind === 170 /* ConstructSignature */ ? ts.factory.createConstructSignature(typeParameters, parameters, returnTypeNode) :
47890                         kind === 164 /* MethodSignature */ ? ts.factory.createMethodSignature(options === null || options === void 0 ? void 0 : options.modifiers, (_a = options === null || options === void 0 ? void 0 : options.name) !== null && _a !== void 0 ? _a : ts.factory.createIdentifier(""), options === null || options === void 0 ? void 0 : options.questionToken, typeParameters, parameters, returnTypeNode) :
47891                             kind === 165 /* MethodDeclaration */ ? ts.factory.createMethodDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, /*asteriskToken*/ undefined, (_b = options === null || options === void 0 ? void 0 : options.name) !== null && _b !== void 0 ? _b : ts.factory.createIdentifier(""), /*questionToken*/ undefined, typeParameters, parameters, returnTypeNode, /*body*/ undefined) :
47892                                 kind === 166 /* Constructor */ ? ts.factory.createConstructorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, parameters, /*body*/ undefined) :
47893                                     kind === 167 /* GetAccessor */ ? ts.factory.createGetAccessorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, (_c = options === null || options === void 0 ? void 0 : options.name) !== null && _c !== void 0 ? _c : ts.factory.createIdentifier(""), parameters, returnTypeNode, /*body*/ undefined) :
47894                                         kind === 168 /* SetAccessor */ ? ts.factory.createSetAccessorDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, (_d = options === null || options === void 0 ? void 0 : options.name) !== null && _d !== void 0 ? _d : ts.factory.createIdentifier(""), parameters, /*body*/ undefined) :
47895                                             kind === 171 /* IndexSignature */ ? ts.factory.createIndexSignature(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, parameters, returnTypeNode) :
47896                                                 kind === 308 /* JSDocFunctionType */ ? ts.factory.createJSDocFunctionType(parameters, returnTypeNode) :
47897                                                     kind === 174 /* FunctionType */ ? ts.factory.createFunctionTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
47898                                                         kind === 175 /* ConstructorType */ ? ts.factory.createConstructorTypeNode(typeParameters, parameters, returnTypeNode !== null && returnTypeNode !== void 0 ? returnTypeNode : ts.factory.createTypeReferenceNode(ts.factory.createIdentifier(""))) :
47899                                                             kind === 251 /* FunctionDeclaration */ ? ts.factory.createFunctionDeclaration(/*decorators*/ undefined, options === null || options === void 0 ? void 0 : options.modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, /*body*/ undefined) :
47900                                                                 kind === 208 /* FunctionExpression */ ? ts.factory.createFunctionExpression(options === null || options === void 0 ? void 0 : options.modifiers, /*asteriskToken*/ undefined, (options === null || options === void 0 ? void 0 : options.name) ? ts.cast(options.name, ts.isIdentifier) : ts.factory.createIdentifier(""), typeParameters, parameters, returnTypeNode, ts.factory.createBlock([])) :
47901                                                                     kind === 209 /* ArrowFunction */ ? ts.factory.createArrowFunction(options === null || options === void 0 ? void 0 : options.modifiers, typeParameters, parameters, returnTypeNode, /*equalsGreaterThanToken*/ undefined, ts.factory.createBlock([])) :
47902                                                                         ts.Debug.assertNever(kind);
47903                 if (typeArguments) {
47904                     node.typeArguments = ts.factory.createNodeArray(typeArguments);
47905                 }
47906                 return node;
47907             }
47908             function typeParameterToDeclarationWithConstraint(type, context, constraintNode) {
47909                 var savedContextFlags = context.flags;
47910                 context.flags &= ~512 /* WriteTypeParametersInQualifiedName */; // Avoids potential infinite loop when building for a claimspace with a generic
47911                 var name = typeParameterToName(type, context);
47912                 var defaultParameter = getDefaultFromTypeParameter(type);
47913                 var defaultParameterNode = defaultParameter && typeToTypeNodeHelper(defaultParameter, context);
47914                 context.flags = savedContextFlags;
47915                 return ts.factory.createTypeParameterDeclaration(name, constraintNode, defaultParameterNode);
47916             }
47917             function typeParameterToDeclaration(type, context, constraint) {
47918                 if (constraint === void 0) { constraint = getConstraintOfTypeParameter(type); }
47919                 var constraintNode = constraint && typeToTypeNodeHelper(constraint, context);
47920                 return typeParameterToDeclarationWithConstraint(type, context, constraintNode);
47921             }
47922             function symbolToParameterDeclaration(parameterSymbol, context, preserveModifierFlags, privateSymbolVisitor, bundledImports) {
47923                 var parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 160 /* Parameter */);
47924                 if (!parameterDeclaration && !ts.isTransientSymbol(parameterSymbol)) {
47925                     parameterDeclaration = ts.getDeclarationOfKind(parameterSymbol, 326 /* JSDocParameterTag */);
47926                 }
47927                 var parameterType = getTypeOfSymbol(parameterSymbol);
47928                 if (parameterDeclaration && isRequiredInitializedParameter(parameterDeclaration)) {
47929                     parameterType = getOptionalType(parameterType);
47930                 }
47931                 if ((context.flags & 1073741824 /* NoUndefinedOptionalParameterType */) && parameterDeclaration && !ts.isJSDocParameterTag(parameterDeclaration) && isOptionalUninitializedParameter(parameterDeclaration)) {
47932                     parameterType = getTypeWithFacts(parameterType, 524288 /* NEUndefined */);
47933                 }
47934                 var parameterTypeNode = serializeTypeForDeclaration(context, parameterType, parameterSymbol, context.enclosingDeclaration, privateSymbolVisitor, bundledImports);
47935                 var modifiers = !(context.flags & 8192 /* OmitParameterModifiers */) && preserveModifierFlags && parameterDeclaration && parameterDeclaration.modifiers ? parameterDeclaration.modifiers.map(ts.factory.cloneNode) : undefined;
47936                 var isRest = parameterDeclaration && ts.isRestParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 32768 /* RestParameter */;
47937                 var dotDotDotToken = isRest ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined;
47938                 var name = parameterDeclaration ? parameterDeclaration.name ?
47939                     parameterDeclaration.name.kind === 78 /* Identifier */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name), 16777216 /* NoAsciiEscaping */) :
47940                         parameterDeclaration.name.kind === 157 /* QualifiedName */ ? ts.setEmitFlags(ts.factory.cloneNode(parameterDeclaration.name.right), 16777216 /* NoAsciiEscaping */) :
47941                             cloneBindingName(parameterDeclaration.name) :
47942                     ts.symbolName(parameterSymbol) :
47943                     ts.symbolName(parameterSymbol);
47944                 var isOptional = parameterDeclaration && isOptionalParameter(parameterDeclaration) || ts.getCheckFlags(parameterSymbol) & 16384 /* OptionalParameter */;
47945                 var questionToken = isOptional ? ts.factory.createToken(57 /* QuestionToken */) : undefined;
47946                 var parameterNode = ts.factory.createParameterDeclaration(
47947                 /*decorators*/ undefined, modifiers, dotDotDotToken, name, questionToken, parameterTypeNode, 
47948                 /*initializer*/ undefined);
47949                 context.approximateLength += ts.symbolName(parameterSymbol).length + 3;
47950                 return parameterNode;
47951                 function cloneBindingName(node) {
47952                     return elideInitializerAndSetEmitFlags(node);
47953                     function elideInitializerAndSetEmitFlags(node) {
47954                         if (context.tracker.trackSymbol && ts.isComputedPropertyName(node) && isLateBindableName(node)) {
47955                             trackComputedName(node.expression, context.enclosingDeclaration, context);
47956                         }
47957                         var visited = ts.visitEachChild(node, elideInitializerAndSetEmitFlags, ts.nullTransformationContext, /*nodesVisitor*/ undefined, elideInitializerAndSetEmitFlags);
47958                         if (ts.isBindingElement(visited)) {
47959                             visited = ts.factory.updateBindingElement(visited, visited.dotDotDotToken, visited.propertyName, visited.name, 
47960                             /*initializer*/ undefined);
47961                         }
47962                         if (!ts.nodeIsSynthesized(visited)) {
47963                             visited = ts.factory.cloneNode(visited);
47964                         }
47965                         return ts.setEmitFlags(visited, 1 /* SingleLine */ | 16777216 /* NoAsciiEscaping */);
47966                     }
47967                 }
47968             }
47969             function trackComputedName(accessExpression, enclosingDeclaration, context) {
47970                 if (!context.tracker.trackSymbol)
47971                     return;
47972                 // get symbol of the first identifier of the entityName
47973                 var firstIdentifier = ts.getFirstIdentifier(accessExpression);
47974                 var name = resolveName(firstIdentifier, firstIdentifier.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
47975                 if (name) {
47976                     context.tracker.trackSymbol(name, enclosingDeclaration, 111551 /* Value */);
47977                 }
47978             }
47979             function lookupSymbolChain(symbol, context, meaning, yieldModuleSymbol) {
47980                 context.tracker.trackSymbol(symbol, context.enclosingDeclaration, meaning); // TODO: GH#18217
47981                 return lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol);
47982             }
47983             function lookupSymbolChainWorker(symbol, context, meaning, yieldModuleSymbol) {
47984                 // Try to get qualified name if the symbol is not a type parameter and there is an enclosing declaration.
47985                 var chain;
47986                 var isTypeParameter = symbol.flags & 262144 /* TypeParameter */;
47987                 if (!isTypeParameter && (context.enclosingDeclaration || context.flags & 64 /* UseFullyQualifiedType */) && !(context.flags & 134217728 /* DoNotIncludeSymbolChain */)) {
47988                     chain = ts.Debug.checkDefined(getSymbolChain(symbol, meaning, /*endOfChain*/ true));
47989                     ts.Debug.assert(chain && chain.length > 0);
47990                 }
47991                 else {
47992                     chain = [symbol];
47993                 }
47994                 return chain;
47995                 /** @param endOfChain Set to false for recursive calls; non-recursive calls should always output something. */
47996                 function getSymbolChain(symbol, meaning, endOfChain) {
47997                     var accessibleSymbolChain = getAccessibleSymbolChain(symbol, context.enclosingDeclaration, meaning, !!(context.flags & 128 /* UseOnlyExternalAliasing */));
47998                     var parentSpecifiers;
47999                     if (!accessibleSymbolChain ||
48000                         needsQualification(accessibleSymbolChain[0], context.enclosingDeclaration, accessibleSymbolChain.length === 1 ? meaning : getQualifiedLeftMeaning(meaning))) {
48001                         // Go up and add our parent.
48002                         var parents_1 = getContainersOfSymbol(accessibleSymbolChain ? accessibleSymbolChain[0] : symbol, context.enclosingDeclaration, meaning);
48003                         if (ts.length(parents_1)) {
48004                             parentSpecifiers = parents_1.map(function (symbol) {
48005                                 return ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)
48006                                     ? getSpecifierForModuleSymbol(symbol, context)
48007                                     : undefined;
48008                             });
48009                             var indices = parents_1.map(function (_, i) { return i; });
48010                             indices.sort(sortByBestName);
48011                             var sortedParents = indices.map(function (i) { return parents_1[i]; });
48012                             for (var _i = 0, sortedParents_1 = sortedParents; _i < sortedParents_1.length; _i++) {
48013                                 var parent = sortedParents_1[_i];
48014                                 var parentChain = getSymbolChain(parent, getQualifiedLeftMeaning(meaning), /*endOfChain*/ false);
48015                                 if (parentChain) {
48016                                     if (parent.exports && parent.exports.get("export=" /* ExportEquals */) &&
48017                                         getSymbolIfSameReference(parent.exports.get("export=" /* ExportEquals */), symbol)) {
48018                                         // parentChain root _is_ symbol - symbol is a module export=, so it kinda looks like it's own parent
48019                                         // No need to lookup an alias for the symbol in itself
48020                                         accessibleSymbolChain = parentChain;
48021                                         break;
48022                                     }
48023                                     accessibleSymbolChain = parentChain.concat(accessibleSymbolChain || [getAliasForSymbolInContainer(parent, symbol) || symbol]);
48024                                     break;
48025                                 }
48026                             }
48027                         }
48028                     }
48029                     if (accessibleSymbolChain) {
48030                         return accessibleSymbolChain;
48031                     }
48032                     if (
48033                     // If this is the last part of outputting the symbol, always output. The cases apply only to parent symbols.
48034                     endOfChain ||
48035                         // If a parent symbol is an anonymous type, don't write it.
48036                         !(symbol.flags & (2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */))) {
48037                         // If a parent symbol is an external module, don't write it. (We prefer just `x` vs `"foo/bar".x`.)
48038                         if (!endOfChain && !yieldModuleSymbol && !!ts.forEach(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
48039                             return;
48040                         }
48041                         return [symbol];
48042                     }
48043                     function sortByBestName(a, b) {
48044                         var specifierA = parentSpecifiers[a];
48045                         var specifierB = parentSpecifiers[b];
48046                         if (specifierA && specifierB) {
48047                             var isBRelative = ts.pathIsRelative(specifierB);
48048                             if (ts.pathIsRelative(specifierA) === isBRelative) {
48049                                 // Both relative or both non-relative, sort by number of parts
48050                                 return ts.moduleSpecifiers.countPathComponents(specifierA) - ts.moduleSpecifiers.countPathComponents(specifierB);
48051                             }
48052                             if (isBRelative) {
48053                                 // A is non-relative, B is relative: prefer A
48054                                 return -1;
48055                             }
48056                             // A is relative, B is non-relative: prefer B
48057                             return 1;
48058                         }
48059                         return 0;
48060                     }
48061                 }
48062             }
48063             function typeParametersToTypeParameterDeclarations(symbol, context) {
48064                 var typeParameterNodes;
48065                 var targetSymbol = getTargetSymbol(symbol);
48066                 if (targetSymbol.flags & (32 /* Class */ | 64 /* Interface */ | 524288 /* TypeAlias */)) {
48067                     typeParameterNodes = ts.factory.createNodeArray(ts.map(getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol), function (tp) { return typeParameterToDeclaration(tp, context); }));
48068                 }
48069                 return typeParameterNodes;
48070             }
48071             function lookupTypeParameterNodes(chain, index, context) {
48072                 var _a;
48073                 ts.Debug.assert(chain && 0 <= index && index < chain.length);
48074                 var symbol = chain[index];
48075                 var symbolId = getSymbolId(symbol);
48076                 if ((_a = context.typeParameterSymbolList) === null || _a === void 0 ? void 0 : _a.has(symbolId)) {
48077                     return undefined;
48078                 }
48079                 (context.typeParameterSymbolList || (context.typeParameterSymbolList = new ts.Set())).add(symbolId);
48080                 var typeParameterNodes;
48081                 if (context.flags & 512 /* WriteTypeParametersInQualifiedName */ && index < (chain.length - 1)) {
48082                     var parentSymbol = symbol;
48083                     var nextSymbol_1 = chain[index + 1];
48084                     if (ts.getCheckFlags(nextSymbol_1) & 1 /* Instantiated */) {
48085                         var params = getTypeParametersOfClassOrInterface(parentSymbol.flags & 2097152 /* Alias */ ? resolveAlias(parentSymbol) : parentSymbol);
48086                         typeParameterNodes = mapToTypeNodes(ts.map(params, function (t) { return getMappedType(t, nextSymbol_1.mapper); }), context);
48087                     }
48088                     else {
48089                         typeParameterNodes = typeParametersToTypeParameterDeclarations(symbol, context);
48090                     }
48091                 }
48092                 return typeParameterNodes;
48093             }
48094             /**
48095              * Given A[B][C][D], finds A[B]
48096              */
48097             function getTopmostIndexedAccessType(top) {
48098                 if (ts.isIndexedAccessTypeNode(top.objectType)) {
48099                     return getTopmostIndexedAccessType(top.objectType);
48100                 }
48101                 return top;
48102             }
48103             function getSpecifierForModuleSymbol(symbol, context) {
48104                 var _a;
48105                 var file = ts.getDeclarationOfKind(symbol, 297 /* SourceFile */);
48106                 if (!file) {
48107                     var equivalentFileSymbol = ts.firstDefined(symbol.declarations, function (d) { return getFileSymbolIfFileSymbolExportEqualsContainer(d, symbol); });
48108                     if (equivalentFileSymbol) {
48109                         file = ts.getDeclarationOfKind(equivalentFileSymbol, 297 /* SourceFile */);
48110                     }
48111                 }
48112                 if (file && file.moduleName !== undefined) {
48113                     // Use the amd name if it is available
48114                     return file.moduleName;
48115                 }
48116                 if (!file) {
48117                     if (context.tracker.trackReferencedAmbientModule) {
48118                         var ambientDecls = ts.filter(symbol.declarations, ts.isAmbientModule);
48119                         if (ts.length(ambientDecls)) {
48120                             for (var _i = 0, ambientDecls_1 = ambientDecls; _i < ambientDecls_1.length; _i++) {
48121                                 var decl = ambientDecls_1[_i];
48122                                 context.tracker.trackReferencedAmbientModule(decl, symbol);
48123                             }
48124                         }
48125                     }
48126                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
48127                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
48128                     }
48129                 }
48130                 if (!context.enclosingDeclaration || !context.tracker.moduleResolverHost) {
48131                     // If there's no context declaration, we can't lookup a non-ambient specifier, so we just use the symbol name
48132                     if (ambientModuleSymbolRegex.test(symbol.escapedName)) {
48133                         return symbol.escapedName.substring(1, symbol.escapedName.length - 1);
48134                     }
48135                     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
48136                 }
48137                 var contextFile = ts.getSourceFileOfNode(ts.getOriginalNode(context.enclosingDeclaration));
48138                 var links = getSymbolLinks(symbol);
48139                 var specifier = links.specifierCache && links.specifierCache.get(contextFile.path);
48140                 if (!specifier) {
48141                     var isBundle_1 = !!ts.outFile(compilerOptions);
48142                     // For declaration bundles, we need to generate absolute paths relative to the common source dir for imports,
48143                     // just like how the declaration emitter does for the ambient module declarations - we can easily accomplish this
48144                     // using the `baseUrl` compiler option (which we would otherwise never use in declaration emit) and a non-relative
48145                     // specifier preference
48146                     var moduleResolverHost = context.tracker.moduleResolverHost;
48147                     var specifierCompilerOptions = isBundle_1 ? __assign(__assign({}, compilerOptions), { baseUrl: moduleResolverHost.getCommonSourceDirectory() }) : compilerOptions;
48148                     specifier = ts.first(ts.moduleSpecifiers.getModuleSpecifiers(symbol, specifierCompilerOptions, contextFile, moduleResolverHost, { importModuleSpecifierPreference: isBundle_1 ? "non-relative" : "relative", importModuleSpecifierEnding: isBundle_1 ? "minimal" : undefined }));
48149                     (_a = links.specifierCache) !== null && _a !== void 0 ? _a : (links.specifierCache = new ts.Map());
48150                     links.specifierCache.set(contextFile.path, specifier);
48151                 }
48152                 return specifier;
48153             }
48154             function symbolToTypeNode(symbol, context, meaning, overrideTypeArguments) {
48155                 var chain = lookupSymbolChain(symbol, context, meaning, !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */)); // If we're using aliases outside the current scope, dont bother with the module
48156                 var isTypeOf = meaning === 111551 /* Value */;
48157                 if (ts.some(chain[0].declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
48158                     // module is root, must use `ImportTypeNode`
48159                     var nonRootParts = chain.length > 1 ? createAccessFromSymbolChain(chain, chain.length - 1, 1) : undefined;
48160                     var typeParameterNodes = overrideTypeArguments || lookupTypeParameterNodes(chain, 0, context);
48161                     var specifier = getSpecifierForModuleSymbol(chain[0], context);
48162                     if (!(context.flags & 67108864 /* AllowNodeModulesRelativePaths */) && ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs && specifier.indexOf("/node_modules/") >= 0) {
48163                         // If ultimately we can only name the symbol with a reference that dives into a `node_modules` folder, we should error
48164                         // since declaration files with these kinds of references are liable to fail when published :(
48165                         context.encounteredError = true;
48166                         if (context.tracker.reportLikelyUnsafeImportRequiredError) {
48167                             context.tracker.reportLikelyUnsafeImportRequiredError(specifier);
48168                         }
48169                     }
48170                     var lit = ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(specifier));
48171                     if (context.tracker.trackExternalModuleSymbolOfImportTypeNode)
48172                         context.tracker.trackExternalModuleSymbolOfImportTypeNode(chain[0]);
48173                     context.approximateLength += specifier.length + 10; // specifier + import("")
48174                     if (!nonRootParts || ts.isEntityName(nonRootParts)) {
48175                         if (nonRootParts) {
48176                             var lastId = ts.isIdentifier(nonRootParts) ? nonRootParts : nonRootParts.right;
48177                             lastId.typeArguments = undefined;
48178                         }
48179                         return ts.factory.createImportTypeNode(lit, nonRootParts, typeParameterNodes, isTypeOf);
48180                     }
48181                     else {
48182                         var splitNode = getTopmostIndexedAccessType(nonRootParts);
48183                         var qualifier = splitNode.objectType.typeName;
48184                         return ts.factory.createIndexedAccessTypeNode(ts.factory.createImportTypeNode(lit, qualifier, typeParameterNodes, isTypeOf), splitNode.indexType);
48185                     }
48186                 }
48187                 var entityName = createAccessFromSymbolChain(chain, chain.length - 1, 0);
48188                 if (ts.isIndexedAccessTypeNode(entityName)) {
48189                     return entityName; // Indexed accesses can never be `typeof`
48190                 }
48191                 if (isTypeOf) {
48192                     return ts.factory.createTypeQueryNode(entityName);
48193                 }
48194                 else {
48195                     var lastId = ts.isIdentifier(entityName) ? entityName : entityName.right;
48196                     var lastTypeArgs = lastId.typeArguments;
48197                     lastId.typeArguments = undefined;
48198                     return ts.factory.createTypeReferenceNode(entityName, lastTypeArgs);
48199                 }
48200                 function createAccessFromSymbolChain(chain, index, stopper) {
48201                     var typeParameterNodes = index === (chain.length - 1) ? overrideTypeArguments : lookupTypeParameterNodes(chain, index, context);
48202                     var symbol = chain[index];
48203                     var parent = chain[index - 1];
48204                     var symbolName;
48205                     if (index === 0) {
48206                         context.flags |= 16777216 /* InInitialEntityName */;
48207                         symbolName = getNameOfSymbolAsWritten(symbol, context);
48208                         context.approximateLength += (symbolName ? symbolName.length : 0) + 1;
48209                         context.flags ^= 16777216 /* InInitialEntityName */;
48210                     }
48211                     else {
48212                         if (parent && getExportsOfSymbol(parent)) {
48213                             var exports_1 = getExportsOfSymbol(parent);
48214                             ts.forEachEntry(exports_1, function (ex, name) {
48215                                 if (getSymbolIfSameReference(ex, symbol) && !isLateBoundName(name) && name !== "export=" /* ExportEquals */) {
48216                                     symbolName = ts.unescapeLeadingUnderscores(name);
48217                                     return true;
48218                                 }
48219                             });
48220                         }
48221                     }
48222                     if (!symbolName) {
48223                         symbolName = getNameOfSymbolAsWritten(symbol, context);
48224                     }
48225                     context.approximateLength += symbolName.length + 1;
48226                     if (!(context.flags & 16 /* ForbidIndexedAccessSymbolReferences */) && parent &&
48227                         getMembersOfSymbol(parent) && getMembersOfSymbol(parent).get(symbol.escapedName) &&
48228                         getSymbolIfSameReference(getMembersOfSymbol(parent).get(symbol.escapedName), symbol)) {
48229                         // Should use an indexed access
48230                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
48231                         if (ts.isIndexedAccessTypeNode(LHS)) {
48232                             return ts.factory.createIndexedAccessTypeNode(LHS, ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
48233                         }
48234                         else {
48235                             return ts.factory.createIndexedAccessTypeNode(ts.factory.createTypeReferenceNode(LHS, typeParameterNodes), ts.factory.createLiteralTypeNode(ts.factory.createStringLiteral(symbolName)));
48236                         }
48237                     }
48238                     var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48239                     identifier.symbol = symbol;
48240                     if (index > stopper) {
48241                         var LHS = createAccessFromSymbolChain(chain, index - 1, stopper);
48242                         if (!ts.isEntityName(LHS)) {
48243                             return ts.Debug.fail("Impossible construct - an export of an indexed access cannot be reachable");
48244                         }
48245                         return ts.factory.createQualifiedName(LHS, identifier);
48246                     }
48247                     return identifier;
48248                 }
48249             }
48250             function typeParameterShadowsNameInScope(escapedName, context, type) {
48251                 var result = resolveName(context.enclosingDeclaration, escapedName, 788968 /* Type */, /*nameNotFoundArg*/ undefined, escapedName, /*isUse*/ false);
48252                 if (result) {
48253                     if (result.flags & 262144 /* TypeParameter */ && result === type.symbol) {
48254                         return false;
48255                     }
48256                     return true;
48257                 }
48258                 return false;
48259             }
48260             function typeParameterToName(type, context) {
48261                 var _a;
48262                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */ && context.typeParameterNames) {
48263                     var cached = context.typeParameterNames.get(getTypeId(type));
48264                     if (cached) {
48265                         return cached;
48266                     }
48267                 }
48268                 var result = symbolToName(type.symbol, context, 788968 /* Type */, /*expectsIdentifier*/ true);
48269                 if (!(result.kind & 78 /* Identifier */)) {
48270                     return ts.factory.createIdentifier("(Missing type parameter)");
48271                 }
48272                 if (context.flags & 4 /* GenerateNamesForShadowedTypeParams */) {
48273                     var rawtext = result.escapedText;
48274                     var i = 0;
48275                     var text = rawtext;
48276                     while (((_a = context.typeParameterNamesByText) === null || _a === void 0 ? void 0 : _a.has(text)) || typeParameterShadowsNameInScope(text, context, type)) {
48277                         i++;
48278                         text = rawtext + "_" + i;
48279                     }
48280                     if (text !== rawtext) {
48281                         result = ts.factory.createIdentifier(text, result.typeArguments);
48282                     }
48283                     (context.typeParameterNames || (context.typeParameterNames = new ts.Map())).set(getTypeId(type), result);
48284                     (context.typeParameterNamesByText || (context.typeParameterNamesByText = new ts.Set())).add(result.escapedText);
48285                 }
48286                 return result;
48287             }
48288             function symbolToName(symbol, context, meaning, expectsIdentifier) {
48289                 var chain = lookupSymbolChain(symbol, context, meaning);
48290                 if (expectsIdentifier && chain.length !== 1
48291                     && !context.encounteredError
48292                     && !(context.flags & 65536 /* AllowQualifedNameInPlaceOfIdentifier */)) {
48293                     context.encounteredError = true;
48294                 }
48295                 return createEntityNameFromSymbolChain(chain, chain.length - 1);
48296                 function createEntityNameFromSymbolChain(chain, index) {
48297                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
48298                     var symbol = chain[index];
48299                     if (index === 0) {
48300                         context.flags |= 16777216 /* InInitialEntityName */;
48301                     }
48302                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
48303                     if (index === 0) {
48304                         context.flags ^= 16777216 /* InInitialEntityName */;
48305                     }
48306                     var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48307                     identifier.symbol = symbol;
48308                     return index > 0 ? ts.factory.createQualifiedName(createEntityNameFromSymbolChain(chain, index - 1), identifier) : identifier;
48309                 }
48310             }
48311             function symbolToExpression(symbol, context, meaning) {
48312                 var chain = lookupSymbolChain(symbol, context, meaning);
48313                 return createExpressionFromSymbolChain(chain, chain.length - 1);
48314                 function createExpressionFromSymbolChain(chain, index) {
48315                     var typeParameterNodes = lookupTypeParameterNodes(chain, index, context);
48316                     var symbol = chain[index];
48317                     if (index === 0) {
48318                         context.flags |= 16777216 /* InInitialEntityName */;
48319                     }
48320                     var symbolName = getNameOfSymbolAsWritten(symbol, context);
48321                     if (index === 0) {
48322                         context.flags ^= 16777216 /* InInitialEntityName */;
48323                     }
48324                     var firstChar = symbolName.charCodeAt(0);
48325                     if (ts.isSingleOrDoubleQuote(firstChar) && ts.some(symbol.declarations, hasNonGlobalAugmentationExternalModuleSymbol)) {
48326                         return ts.factory.createStringLiteral(getSpecifierForModuleSymbol(symbol, context));
48327                     }
48328                     var canUsePropertyAccess = firstChar === 35 /* hash */ ?
48329                         symbolName.length > 1 && ts.isIdentifierStart(symbolName.charCodeAt(1), languageVersion) :
48330                         ts.isIdentifierStart(firstChar, languageVersion);
48331                     if (index === 0 || canUsePropertyAccess) {
48332                         var identifier = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48333                         identifier.symbol = symbol;
48334                         return index > 0 ? ts.factory.createPropertyAccessExpression(createExpressionFromSymbolChain(chain, index - 1), identifier) : identifier;
48335                     }
48336                     else {
48337                         if (firstChar === 91 /* openBracket */) {
48338                             symbolName = symbolName.substring(1, symbolName.length - 1);
48339                             firstChar = symbolName.charCodeAt(0);
48340                         }
48341                         var expression = void 0;
48342                         if (ts.isSingleOrDoubleQuote(firstChar)) {
48343                             expression = ts.factory.createStringLiteral(symbolName
48344                                 .substring(1, symbolName.length - 1)
48345                                 .replace(/\\./g, function (s) { return s.substring(1); }), firstChar === 39 /* singleQuote */);
48346                         }
48347                         else if (("" + +symbolName) === symbolName) {
48348                             expression = ts.factory.createNumericLiteral(+symbolName);
48349                         }
48350                         if (!expression) {
48351                             expression = ts.setEmitFlags(ts.factory.createIdentifier(symbolName, typeParameterNodes), 16777216 /* NoAsciiEscaping */);
48352                             expression.symbol = symbol;
48353                         }
48354                         return ts.factory.createElementAccessExpression(createExpressionFromSymbolChain(chain, index - 1), expression);
48355                     }
48356                 }
48357             }
48358             function isStringNamed(d) {
48359                 var name = ts.getNameOfDeclaration(d);
48360                 return !!name && ts.isStringLiteral(name);
48361             }
48362             function isSingleQuotedStringNamed(d) {
48363                 var name = ts.getNameOfDeclaration(d);
48364                 return !!(name && ts.isStringLiteral(name) && (name.singleQuote || !ts.nodeIsSynthesized(name) && ts.startsWith(ts.getTextOfNode(name, /*includeTrivia*/ false), "'")));
48365             }
48366             function getPropertyNameNodeForSymbol(symbol, context) {
48367                 var singleQuote = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isSingleQuotedStringNamed);
48368                 var fromNameType = getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote);
48369                 if (fromNameType) {
48370                     return fromNameType;
48371                 }
48372                 if (ts.isKnownSymbol(symbol)) {
48373                     return ts.factory.createComputedPropertyName(ts.factory.createPropertyAccessExpression(ts.factory.createIdentifier("Symbol"), symbol.escapedName.substr(3)));
48374                 }
48375                 var rawName = ts.unescapeLeadingUnderscores(symbol.escapedName);
48376                 var stringNamed = !!ts.length(symbol.declarations) && ts.every(symbol.declarations, isStringNamed);
48377                 return createPropertyNameNodeForIdentifierOrLiteral(rawName, stringNamed, singleQuote);
48378             }
48379             // See getNameForSymbolFromNameType for a stringy equivalent
48380             function getPropertyNameNodeForSymbolFromNameType(symbol, context, singleQuote) {
48381                 var nameType = getSymbolLinks(symbol).nameType;
48382                 if (nameType) {
48383                     if (nameType.flags & 384 /* StringOrNumberLiteral */) {
48384                         var name = "" + nameType.value;
48385                         if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
48386                             return ts.factory.createStringLiteral(name, !!singleQuote);
48387                         }
48388                         if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
48389                             return ts.factory.createComputedPropertyName(ts.factory.createNumericLiteral(+name));
48390                         }
48391                         return createPropertyNameNodeForIdentifierOrLiteral(name);
48392                     }
48393                     if (nameType.flags & 8192 /* UniqueESSymbol */) {
48394                         return ts.factory.createComputedPropertyName(symbolToExpression(nameType.symbol, context, 111551 /* Value */));
48395                     }
48396                 }
48397             }
48398             function createPropertyNameNodeForIdentifierOrLiteral(name, stringNamed, singleQuote) {
48399                 return ts.isIdentifierText(name, compilerOptions.target) ? ts.factory.createIdentifier(name) :
48400                     !stringNamed && isNumericLiteralName(name) && +name >= 0 ? ts.factory.createNumericLiteral(+name) :
48401                         ts.factory.createStringLiteral(name, !!singleQuote);
48402             }
48403             function cloneNodeBuilderContext(context) {
48404                 var initial = __assign({}, context);
48405                 // Make type parameters created within this context not consume the name outside this context
48406                 // The symbol serializer ends up creating many sibling scopes that all need "separate" contexts when
48407                 // it comes to naming things - within a normal `typeToTypeNode` call, the node builder only ever descends
48408                 // through the type tree, so the only cases where we could have used distinct sibling scopes was when there
48409                 // were multiple generic overloads with similar generated type parameter names
48410                 // The effect:
48411                 // When we write out
48412                 // export const x: <T>(x: T) => T
48413                 // export const y: <T>(x: T) => T
48414                 // we write it out like that, rather than as
48415                 // export const x: <T>(x: T) => T
48416                 // export const y: <T_1>(x: T_1) => T_1
48417                 if (initial.typeParameterNames) {
48418                     initial.typeParameterNames = new ts.Map(initial.typeParameterNames);
48419                 }
48420                 if (initial.typeParameterNamesByText) {
48421                     initial.typeParameterNamesByText = new ts.Set(initial.typeParameterNamesByText);
48422                 }
48423                 if (initial.typeParameterSymbolList) {
48424                     initial.typeParameterSymbolList = new ts.Set(initial.typeParameterSymbolList);
48425                 }
48426                 return initial;
48427             }
48428             function getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration) {
48429                 return symbol.declarations && ts.find(symbol.declarations, function (s) { return !!ts.getEffectiveTypeAnnotationNode(s) && (!enclosingDeclaration || !!ts.findAncestor(s, function (n) { return n === enclosingDeclaration; })); });
48430             }
48431             function existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type) {
48432                 return !(ts.getObjectFlags(type) & 4 /* Reference */) || !ts.isTypeReferenceNode(existing) || ts.length(existing.typeArguments) >= getMinTypeArgumentCount(type.target.typeParameters);
48433             }
48434             /**
48435              * Unlike `typeToTypeNodeHelper`, this handles setting up the `AllowUniqueESSymbolType` flag
48436              * so a `unique symbol` is returned when appropriate for the input symbol, rather than `typeof sym`
48437              */
48438             function serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled) {
48439                 if (type !== errorType && enclosingDeclaration) {
48440                     var declWithExistingAnnotation = getDeclarationWithTypeAnnotation(symbol, enclosingDeclaration);
48441                     if (declWithExistingAnnotation && !ts.isFunctionLikeDeclaration(declWithExistingAnnotation)) {
48442                         // try to reuse the existing annotation
48443                         var existing = ts.getEffectiveTypeAnnotationNode(declWithExistingAnnotation);
48444                         if (getTypeFromTypeNode(existing) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(existing, type)) {
48445                             var result_5 = serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled);
48446                             if (result_5) {
48447                                 return result_5;
48448                             }
48449                         }
48450                     }
48451                 }
48452                 var oldFlags = context.flags;
48453                 if (type.flags & 8192 /* UniqueESSymbol */ &&
48454                     type.symbol === symbol && (!context.enclosingDeclaration || ts.some(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration); }))) {
48455                     context.flags |= 1048576 /* AllowUniqueESSymbolType */;
48456                 }
48457                 var result = typeToTypeNodeHelper(type, context);
48458                 context.flags = oldFlags;
48459                 return result;
48460             }
48461             function serializeReturnTypeForSignature(context, type, signature, includePrivateSymbol, bundled) {
48462                 if (type !== errorType && context.enclosingDeclaration) {
48463                     var annotation = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
48464                     if (!!ts.findAncestor(annotation, function (n) { return n === context.enclosingDeclaration; }) && annotation && instantiateType(getTypeFromTypeNode(annotation), signature.mapper) === type && existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(annotation, type)) {
48465                         var result = serializeExistingTypeNode(context, annotation, includePrivateSymbol, bundled);
48466                         if (result) {
48467                             return result;
48468                         }
48469                     }
48470                 }
48471                 return typeToTypeNodeHelper(type, context);
48472             }
48473             function serializeExistingTypeNode(context, existing, includePrivateSymbol, bundled) {
48474                 if (cancellationToken && cancellationToken.throwIfCancellationRequested) {
48475                     cancellationToken.throwIfCancellationRequested();
48476                 }
48477                 var hadError = false;
48478                 var file = ts.getSourceFileOfNode(existing);
48479                 var transformed = ts.visitNode(existing, visitExistingNodeTreeSymbols);
48480                 if (hadError) {
48481                     return undefined;
48482                 }
48483                 return transformed === existing ? ts.setTextRange(ts.factory.cloneNode(existing), existing) : transformed;
48484                 function visitExistingNodeTreeSymbols(node) {
48485                     var _a, _b;
48486                     // We don't _actually_ support jsdoc namepath types, emit `any` instead
48487                     if (ts.isJSDocAllType(node) || node.kind === 310 /* JSDocNamepathType */) {
48488                         return ts.factory.createKeywordTypeNode(128 /* AnyKeyword */);
48489                     }
48490                     if (ts.isJSDocUnknownType(node)) {
48491                         return ts.factory.createKeywordTypeNode(152 /* UnknownKeyword */);
48492                     }
48493                     if (ts.isJSDocNullableType(node)) {
48494                         return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createLiteralTypeNode(ts.factory.createNull())]);
48495                     }
48496                     if (ts.isJSDocOptionalType(node)) {
48497                         return ts.factory.createUnionTypeNode([ts.visitNode(node.type, visitExistingNodeTreeSymbols), ts.factory.createKeywordTypeNode(150 /* UndefinedKeyword */)]);
48498                     }
48499                     if (ts.isJSDocNonNullableType(node)) {
48500                         return ts.visitNode(node.type, visitExistingNodeTreeSymbols);
48501                     }
48502                     if (ts.isJSDocVariadicType(node)) {
48503                         return ts.factory.createArrayTypeNode(ts.visitNode(node.type, visitExistingNodeTreeSymbols));
48504                     }
48505                     if (ts.isJSDocTypeLiteral(node)) {
48506                         return ts.factory.createTypeLiteralNode(ts.map(node.jsDocPropertyTags, function (t) {
48507                             var name = ts.isIdentifier(t.name) ? t.name : t.name.right;
48508                             var typeViaParent = getTypeOfPropertyOfType(getTypeFromTypeNode(node), name.escapedText);
48509                             var overrideTypeNode = typeViaParent && t.typeExpression && getTypeFromTypeNode(t.typeExpression.type) !== typeViaParent ? typeToTypeNodeHelper(typeViaParent, context) : undefined;
48510                             return ts.factory.createPropertySignature(
48511                             /*modifiers*/ undefined, name, t.typeExpression && ts.isJSDocOptionalType(t.typeExpression.type) ? ts.factory.createToken(57 /* QuestionToken */) : undefined, overrideTypeNode || (t.typeExpression && ts.visitNode(t.typeExpression.type, visitExistingNodeTreeSymbols)) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
48512                         }));
48513                     }
48514                     if (ts.isTypeReferenceNode(node) && ts.isIdentifier(node.typeName) && node.typeName.escapedText === "") {
48515                         return ts.setOriginalNode(ts.factory.createKeywordTypeNode(128 /* AnyKeyword */), node);
48516                     }
48517                     if ((ts.isExpressionWithTypeArguments(node) || ts.isTypeReferenceNode(node)) && ts.isJSDocIndexSignature(node)) {
48518                         return ts.factory.createTypeLiteralNode([ts.factory.createIndexSignature(
48519                             /*decorators*/ undefined, 
48520                             /*modifiers*/ undefined, [ts.factory.createParameterDeclaration(
48521                                 /*decorators*/ undefined, 
48522                                 /*modifiers*/ undefined, 
48523                                 /*dotdotdotToken*/ undefined, "x", 
48524                                 /*questionToken*/ undefined, ts.visitNode(node.typeArguments[0], visitExistingNodeTreeSymbols))], ts.visitNode(node.typeArguments[1], visitExistingNodeTreeSymbols))]);
48525                     }
48526                     if (ts.isJSDocFunctionType(node)) {
48527                         if (ts.isJSDocConstructSignature(node)) {
48528                             var newTypeNode_1;
48529                             return ts.factory.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.factory.createParameterDeclaration(
48530                             /*decorators*/ undefined, 
48531                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
48532                             /*initializer*/ undefined); }), ts.visitNode(newTypeNode_1 || node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
48533                         }
48534                         else {
48535                             return ts.factory.createFunctionTypeNode(ts.visitNodes(node.typeParameters, visitExistingNodeTreeSymbols), ts.map(node.parameters, function (p, i) { return ts.factory.createParameterDeclaration(
48536                             /*decorators*/ undefined, 
48537                             /*modifiers*/ undefined, getEffectiveDotDotDotForParameter(p), getNameForJSDocFunctionParameter(p, i), p.questionToken, ts.visitNode(p.type, visitExistingNodeTreeSymbols), 
48538                             /*initializer*/ undefined); }), ts.visitNode(node.type, visitExistingNodeTreeSymbols) || ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
48539                         }
48540                     }
48541                     if (ts.isTypeReferenceNode(node) && ts.isInJSDoc(node) && (!existingTypeNodeIsNotReferenceOrIsReferenceWithCompatibleTypeArgumentCount(node, getTypeFromTypeNode(node)) || getIntendedTypeFromJSDocTypeReference(node) || unknownSymbol === resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */, /*ignoreErrors*/ true))) {
48542                         return ts.setOriginalNode(typeToTypeNodeHelper(getTypeFromTypeNode(node), context), node);
48543                     }
48544                     if (ts.isLiteralImportTypeNode(node)) {
48545                         return ts.factory.updateImportTypeNode(node, ts.factory.updateLiteralTypeNode(node.argument, rewriteModuleSpecifier(node, node.argument.literal)), node.qualifier, ts.visitNodes(node.typeArguments, visitExistingNodeTreeSymbols, ts.isTypeNode), node.isTypeOf);
48546                     }
48547                     if (ts.isEntityName(node) || ts.isEntityNameExpression(node)) {
48548                         var leftmost = ts.getFirstIdentifier(node);
48549                         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)))) {
48550                             hadError = true;
48551                             return node;
48552                         }
48553                         var sym = resolveEntityName(leftmost, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveALias*/ true);
48554                         if (sym) {
48555                             if (isSymbolAccessible(sym, context.enclosingDeclaration, 67108863 /* All */, /*shouldComputeAliasesToMakeVisible*/ false).accessibility !== 0 /* Accessible */) {
48556                                 hadError = true;
48557                             }
48558                             else {
48559                                 (_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 */);
48560                                 includePrivateSymbol === null || includePrivateSymbol === void 0 ? void 0 : includePrivateSymbol(sym);
48561                             }
48562                             if (ts.isIdentifier(node)) {
48563                                 var name = sym.flags & 262144 /* TypeParameter */ ? typeParameterToName(getDeclaredTypeOfSymbol(sym), context) : ts.factory.cloneNode(node);
48564                                 name.symbol = sym; // for quickinfo, which uses identifier symbol information
48565                                 return ts.setEmitFlags(ts.setOriginalNode(name, node), 16777216 /* NoAsciiEscaping */);
48566                             }
48567                         }
48568                     }
48569                     if (file && ts.isTupleTypeNode(node) && (ts.getLineAndCharacterOfPosition(file, node.pos).line === ts.getLineAndCharacterOfPosition(file, node.end).line)) {
48570                         ts.setEmitFlags(node, 1 /* SingleLine */);
48571                     }
48572                     return ts.visitEachChild(node, visitExistingNodeTreeSymbols, ts.nullTransformationContext);
48573                     function getEffectiveDotDotDotForParameter(p) {
48574                         return p.dotDotDotToken || (p.type && ts.isJSDocVariadicType(p.type) ? ts.factory.createToken(25 /* DotDotDotToken */) : undefined);
48575                     }
48576                     /** Note that `new:T` parameters are not handled, but should be before calling this function. */
48577                     function getNameForJSDocFunctionParameter(p, index) {
48578                         return p.name && ts.isIdentifier(p.name) && p.name.escapedText === "this" ? "this"
48579                             : getEffectiveDotDotDotForParameter(p) ? "args"
48580                                 : "arg" + index;
48581                     }
48582                     function rewriteModuleSpecifier(parent, lit) {
48583                         if (bundled) {
48584                             if (context.tracker && context.tracker.moduleResolverHost) {
48585                                 var targetFile = getExternalModuleFileFromDeclaration(parent);
48586                                 if (targetFile) {
48587                                     var getCanonicalFileName = ts.createGetCanonicalFileName(!!host.useCaseSensitiveFileNames);
48588                                     var resolverHost = {
48589                                         getCanonicalFileName: getCanonicalFileName,
48590                                         getCurrentDirectory: function () { return context.tracker.moduleResolverHost.getCurrentDirectory(); },
48591                                         getCommonSourceDirectory: function () { return context.tracker.moduleResolverHost.getCommonSourceDirectory(); }
48592                                     };
48593                                     var newName = ts.getResolvedExternalModuleName(resolverHost, targetFile);
48594                                     return ts.factory.createStringLiteral(newName);
48595                                 }
48596                             }
48597                         }
48598                         else {
48599                             if (context.tracker && context.tracker.trackExternalModuleSymbolOfImportTypeNode) {
48600                                 var moduleSym = resolveExternalModuleNameWorker(lit, lit, /*moduleNotFoundError*/ undefined);
48601                                 if (moduleSym) {
48602                                     context.tracker.trackExternalModuleSymbolOfImportTypeNode(moduleSym);
48603                                 }
48604                             }
48605                         }
48606                         return lit;
48607                     }
48608                 }
48609             }
48610             function symbolTableToDeclarationStatements(symbolTable, context, bundled) {
48611                 var serializePropertySymbolForClass = makeSerializePropertySymbol(ts.factory.createPropertyDeclaration, 165 /* MethodDeclaration */, /*useAcessors*/ true);
48612                 var serializePropertySymbolForInterfaceWorker = makeSerializePropertySymbol(function (_decorators, mods, name, question, type) { return ts.factory.createPropertySignature(mods, name, question, type); }, 164 /* MethodSignature */, /*useAcessors*/ false);
48613                 // TODO: Use `setOriginalNode` on original declaration names where possible so these declarations see some kind of
48614                 // declaration mapping
48615                 // We save the enclosing declaration off here so it's not adjusted by well-meaning declaration
48616                 // emit codepaths which want to apply more specific contexts (so we can still refer to the root real declaration
48617                 // we're trying to emit from later on)
48618                 var enclosingDeclaration = context.enclosingDeclaration;
48619                 var results = [];
48620                 var visitedSymbols = new ts.Set();
48621                 var deferredPrivatesStack = [];
48622                 var oldcontext = context;
48623                 context = __assign(__assign({}, oldcontext), { usedSymbolNames: new ts.Set(oldcontext.usedSymbolNames), remappedSymbolNames: new ts.Map(), tracker: __assign(__assign({}, oldcontext.tracker), { trackSymbol: function (sym, decl, meaning) {
48624                             var accessibleResult = isSymbolAccessible(sym, decl, meaning, /*computeALiases*/ false);
48625                             if (accessibleResult.accessibility === 0 /* Accessible */) {
48626                                 // Lookup the root symbol of the chain of refs we'll use to access it and serialize it
48627                                 var chain = lookupSymbolChainWorker(sym, context, meaning);
48628                                 if (!(sym.flags & 4 /* Property */)) {
48629                                     includePrivateSymbol(chain[0]);
48630                                 }
48631                             }
48632                             else if (oldcontext.tracker && oldcontext.tracker.trackSymbol) {
48633                                 oldcontext.tracker.trackSymbol(sym, decl, meaning);
48634                             }
48635                         } }) });
48636                 ts.forEachEntry(symbolTable, function (symbol, name) {
48637                     var baseName = ts.unescapeLeadingUnderscores(name);
48638                     void getInternalSymbolName(symbol, baseName); // Called to cache values into `usedSymbolNames` and `remappedSymbolNames`
48639                 });
48640                 var addingDeclare = !bundled;
48641                 var exportEquals = symbolTable.get("export=" /* ExportEquals */);
48642                 if (exportEquals && symbolTable.size > 1 && exportEquals.flags & 2097152 /* Alias */) {
48643                     symbolTable = ts.createSymbolTable();
48644                     // Remove extraneous elements from root symbol table (they'll be mixed back in when the target of the `export=` is looked up)
48645                     symbolTable.set("export=" /* ExportEquals */, exportEquals);
48646                 }
48647                 visitSymbolTable(symbolTable);
48648                 return mergeRedundantStatements(results);
48649                 function isIdentifierAndNotUndefined(node) {
48650                     return !!node && node.kind === 78 /* Identifier */;
48651                 }
48652                 function getNamesOfDeclaration(statement) {
48653                     if (ts.isVariableStatement(statement)) {
48654                         return ts.filter(ts.map(statement.declarationList.declarations, ts.getNameOfDeclaration), isIdentifierAndNotUndefined);
48655                     }
48656                     return ts.filter([ts.getNameOfDeclaration(statement)], isIdentifierAndNotUndefined);
48657                 }
48658                 function flattenExportAssignedNamespace(statements) {
48659                     var exportAssignment = ts.find(statements, ts.isExportAssignment);
48660                     var nsIndex = ts.findIndex(statements, ts.isModuleDeclaration);
48661                     var ns = nsIndex !== -1 ? statements[nsIndex] : undefined;
48662                     if (ns && exportAssignment && exportAssignment.isExportEquals &&
48663                         ts.isIdentifier(exportAssignment.expression) && ts.isIdentifier(ns.name) && ts.idText(ns.name) === ts.idText(exportAssignment.expression) &&
48664                         ns.body && ts.isModuleBlock(ns.body)) {
48665                         // Pass 0: Correct situations where a module has both an `export = ns` and multiple top-level exports by stripping the export modifiers from
48666                         //  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
48667                         var excessExports = ts.filter(statements, function (s) { return !!(ts.getEffectiveModifierFlags(s) & 1 /* Export */); });
48668                         var name_2 = ns.name;
48669                         var body = ns.body;
48670                         if (ts.length(excessExports)) {
48671                             ns = ts.factory.updateModuleDeclaration(ns, ns.decorators, ns.modifiers, ns.name, body = ts.factory.updateModuleBlock(body, ts.factory.createNodeArray(__spreadArrays(ns.body.statements, [ts.factory.createExportDeclaration(
48672                                 /*decorators*/ undefined, 
48673                                 /*modifiers*/ undefined, 
48674                                 /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.map(ts.flatMap(excessExports, function (e) { return getNamesOfDeclaration(e); }), function (id) { return ts.factory.createExportSpecifier(/*alias*/ undefined, id); })), 
48675                                 /*moduleSpecifier*/ undefined)]))));
48676                             statements = __spreadArrays(statements.slice(0, nsIndex), [ns], statements.slice(nsIndex + 1));
48677                         }
48678                         // Pass 1: Flatten `export namespace _exports {} export = _exports;` so long as the `export=` only points at a single namespace declaration
48679                         if (!ts.find(statements, function (s) { return s !== ns && ts.nodeHasName(s, name_2); })) {
48680                             results = [];
48681                             // If the namespace contains no export assignments or declarations, and no declarations flagged with `export`, then _everything_ is exported -
48682                             // to respect this as the top level, we need to add an `export` modifier to everything
48683                             var mixinExportFlag_1 = !ts.some(body.statements, function (s) { return ts.hasSyntacticModifier(s, 1 /* Export */) || ts.isExportAssignment(s) || ts.isExportDeclaration(s); });
48684                             ts.forEach(body.statements, function (s) {
48685                                 addResult(s, mixinExportFlag_1 ? 1 /* Export */ : 0 /* None */); // Recalculates the ambient (and export, if applicable from above) flag
48686                             });
48687                             statements = __spreadArrays(ts.filter(statements, function (s) { return s !== ns && s !== exportAssignment; }), results);
48688                         }
48689                     }
48690                     return statements;
48691                 }
48692                 function mergeExportDeclarations(statements) {
48693                     // Pass 2: Combine all `export {}` declarations
48694                     var exports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
48695                     if (ts.length(exports) > 1) {
48696                         var nonExports = ts.filter(statements, function (d) { return !ts.isExportDeclaration(d) || !!d.moduleSpecifier || !d.exportClause; });
48697                         statements = __spreadArrays(nonExports, [ts.factory.createExportDeclaration(
48698                             /*decorators*/ undefined, 
48699                             /*modifiers*/ undefined, 
48700                             /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(exports, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), 
48701                             /*moduleSpecifier*/ undefined)]);
48702                     }
48703                     // Pass 2b: Also combine all `export {} from "..."` declarations as needed
48704                     var reexports = ts.filter(statements, function (d) { return ts.isExportDeclaration(d) && !!d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
48705                     if (ts.length(reexports) > 1) {
48706                         var groups = ts.group(reexports, function (decl) { return ts.isStringLiteral(decl.moduleSpecifier) ? ">" + decl.moduleSpecifier.text : ">"; });
48707                         if (groups.length !== reexports.length) {
48708                             var _loop_9 = function (group_1) {
48709                                 if (group_1.length > 1) {
48710                                     // remove group members from statements and then merge group members and add back to statements
48711                                     statements = __spreadArrays(ts.filter(statements, function (s) { return group_1.indexOf(s) === -1; }), [
48712                                         ts.factory.createExportDeclaration(
48713                                         /*decorators*/ undefined, 
48714                                         /*modifiers*/ undefined, 
48715                                         /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.flatMap(group_1, function (e) { return ts.cast(e.exportClause, ts.isNamedExports).elements; })), group_1[0].moduleSpecifier)
48716                                     ]);
48717                                 }
48718                             };
48719                             for (var _i = 0, groups_1 = groups; _i < groups_1.length; _i++) {
48720                                 var group_1 = groups_1[_i];
48721                                 _loop_9(group_1);
48722                             }
48723                         }
48724                     }
48725                     return statements;
48726                 }
48727                 function inlineExportModifiers(statements) {
48728                     // Pass 3: Move all `export {}`'s to `export` modifiers where possible
48729                     var index = ts.findIndex(statements, function (d) { return ts.isExportDeclaration(d) && !d.moduleSpecifier && !!d.exportClause && ts.isNamedExports(d.exportClause); });
48730                     if (index >= 0) {
48731                         var exportDecl = statements[index];
48732                         var replacements = ts.mapDefined(exportDecl.exportClause.elements, function (e) {
48733                             if (!e.propertyName) {
48734                                 // export {name} - look thru `statements` for `name`, and if all results can take an `export` modifier, do so and filter it
48735                                 var indices = ts.indicesOf(statements);
48736                                 var associatedIndices = ts.filter(indices, function (i) { return ts.nodeHasName(statements[i], e.name); });
48737                                 if (ts.length(associatedIndices) && ts.every(associatedIndices, function (i) { return canHaveExportModifier(statements[i]); })) {
48738                                     for (var _i = 0, associatedIndices_1 = associatedIndices; _i < associatedIndices_1.length; _i++) {
48739                                         var index_1 = associatedIndices_1[_i];
48740                                         statements[index_1] = addExportModifier(statements[index_1]);
48741                                     }
48742                                     return undefined;
48743                                 }
48744                             }
48745                             return e;
48746                         });
48747                         if (!ts.length(replacements)) {
48748                             // all clauses removed, remove the export declaration
48749                             ts.orderedRemoveItemAt(statements, index);
48750                         }
48751                         else {
48752                             // some items filtered, others not - update the export declaration
48753                             statements[index] = ts.factory.updateExportDeclaration(exportDecl, exportDecl.decorators, exportDecl.modifiers, exportDecl.isTypeOnly, ts.factory.updateNamedExports(exportDecl.exportClause, replacements), exportDecl.moduleSpecifier);
48754                         }
48755                     }
48756                     return statements;
48757                 }
48758                 function mergeRedundantStatements(statements) {
48759                     statements = flattenExportAssignedNamespace(statements);
48760                     statements = mergeExportDeclarations(statements);
48761                     statements = inlineExportModifiers(statements);
48762                     // 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
48763                     // declaration privacy is respected.
48764                     if (enclosingDeclaration &&
48765                         ((ts.isSourceFile(enclosingDeclaration) && ts.isExternalOrCommonJsModule(enclosingDeclaration)) || ts.isModuleDeclaration(enclosingDeclaration)) &&
48766                         (!ts.some(statements, ts.isExternalModuleIndicator) || (!ts.hasScopeMarker(statements) && ts.some(statements, ts.needsScopeMarker)))) {
48767                         statements.push(ts.createEmptyExports(ts.factory));
48768                     }
48769                     return statements;
48770                 }
48771                 function canHaveExportModifier(node) {
48772                     return ts.isEnumDeclaration(node) ||
48773                         ts.isVariableStatement(node) ||
48774                         ts.isFunctionDeclaration(node) ||
48775                         ts.isClassDeclaration(node) ||
48776                         (ts.isModuleDeclaration(node) && !ts.isExternalModuleAugmentation(node) && !ts.isGlobalScopeAugmentation(node)) ||
48777                         ts.isInterfaceDeclaration(node) ||
48778                         isTypeDeclaration(node);
48779                 }
48780                 function addExportModifier(node) {
48781                     var flags = (ts.getEffectiveModifierFlags(node) | 1 /* Export */) & ~2 /* Ambient */;
48782                     return ts.factory.updateModifiers(node, flags);
48783                 }
48784                 function removeExportModifier(node) {
48785                     var flags = ts.getEffectiveModifierFlags(node) & ~1 /* Export */;
48786                     return ts.factory.updateModifiers(node, flags);
48787                 }
48788                 function visitSymbolTable(symbolTable, suppressNewPrivateContext, propertyAsAlias) {
48789                     if (!suppressNewPrivateContext) {
48790                         deferredPrivatesStack.push(new ts.Map());
48791                     }
48792                     symbolTable.forEach(function (symbol) {
48793                         serializeSymbol(symbol, /*isPrivate*/ false, !!propertyAsAlias);
48794                     });
48795                     if (!suppressNewPrivateContext) {
48796                         // deferredPrivates will be filled up by visiting the symbol table
48797                         // And will continue to iterate as elements are added while visited `deferredPrivates`
48798                         // (As that's how a map iterator is defined to work)
48799                         deferredPrivatesStack[deferredPrivatesStack.length - 1].forEach(function (symbol) {
48800                             serializeSymbol(symbol, /*isPrivate*/ true, !!propertyAsAlias);
48801                         });
48802                         deferredPrivatesStack.pop();
48803                     }
48804                 }
48805                 function serializeSymbol(symbol, isPrivate, propertyAsAlias) {
48806                     // cache visited list based on merged symbol, since we want to use the unmerged top-level symbol, but
48807                     // still skip reserializing it if we encounter the merged product later on
48808                     var visitedSym = getMergedSymbol(symbol);
48809                     if (visitedSymbols.has(getSymbolId(visitedSym))) {
48810                         return; // Already printed
48811                     }
48812                     visitedSymbols.add(getSymbolId(visitedSym));
48813                     // Only actually serialize symbols within the correct enclosing declaration, otherwise do nothing with the out-of-context symbol
48814                     var skipMembershipCheck = !isPrivate; // We only call this on exported symbols when we know they're in the correct scope
48815                     if (skipMembershipCheck || (!!ts.length(symbol.declarations) && ts.some(symbol.declarations, function (d) { return !!ts.findAncestor(d, function (n) { return n === enclosingDeclaration; }); }))) {
48816                         var oldContext = context;
48817                         context = cloneNodeBuilderContext(context);
48818                         var result = serializeSymbolWorker(symbol, isPrivate, propertyAsAlias);
48819                         context = oldContext;
48820                         return result;
48821                     }
48822                 }
48823                 // Synthesize declarations for a symbol - might be an Interface, a Class, a Namespace, a Type, a Variable (const, let, or var), an Alias
48824                 // or a merge of some number of those.
48825                 // An interesting challenge is ensuring that when classes merge with namespaces and interfaces, is keeping
48826                 // each symbol in only one of the representations
48827                 // Also, synthesizing a default export of some kind
48828                 // If it's an alias: emit `export default ref`
48829                 // If it's a property: emit `export default _default` with a `_default` prop
48830                 // If it's a class/interface/function: emit a class/interface/function with a `default` modifier
48831                 // These forms can merge, eg (`export default 12; export default interface A {}`)
48832                 function serializeSymbolWorker(symbol, isPrivate, propertyAsAlias) {
48833                     var symbolName = ts.unescapeLeadingUnderscores(symbol.escapedName);
48834                     var isDefault = symbol.escapedName === "default" /* Default */;
48835                     if (isPrivate && !(context.flags & 131072 /* AllowAnonymousIdentifier */) && ts.isStringANonContextualKeyword(symbolName) && !isDefault) {
48836                         // 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` :(
48837                         context.encounteredError = true;
48838                         // TODO: Issue error via symbol tracker?
48839                         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
48840                     }
48841                     var needsPostExportDefault = isDefault && !!(symbol.flags & -113 /* ExportDoesNotSupportDefaultModifier */
48842                         || (symbol.flags & 16 /* Function */ && ts.length(getPropertiesOfType(getTypeOfSymbol(symbol))))) && !(symbol.flags & 2097152 /* Alias */); // An alias symbol should preclude needing to make an alias ourselves
48843                     var needsExportDeclaration = !needsPostExportDefault && !isPrivate && ts.isStringANonContextualKeyword(symbolName) && !isDefault;
48844                     // `serializeVariableOrProperty` will handle adding the export declaration if it is run (since `getInternalSymbolName` will create the name mapping), so we need to ensuer we unset `needsExportDeclaration` if it is
48845                     if (needsPostExportDefault || needsExportDeclaration) {
48846                         isPrivate = true;
48847                     }
48848                     var modifierFlags = (!isPrivate ? 1 /* Export */ : 0) | (isDefault && !needsPostExportDefault ? 512 /* Default */ : 0);
48849                     var isConstMergedWithNS = symbol.flags & 1536 /* Module */ &&
48850                         symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */) &&
48851                         symbol.escapedName !== "export=" /* ExportEquals */;
48852                     var isConstMergedWithNSPrintableAsSignatureMerge = isConstMergedWithNS && isTypeRepresentableAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol);
48853                     if (symbol.flags & (16 /* Function */ | 8192 /* Method */) || isConstMergedWithNSPrintableAsSignatureMerge) {
48854                         serializeAsFunctionNamespaceMerge(getTypeOfSymbol(symbol), symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
48855                     }
48856                     if (symbol.flags & 524288 /* TypeAlias */) {
48857                         serializeTypeAlias(symbol, symbolName, modifierFlags);
48858                     }
48859                     // Need to skip over export= symbols below - json source files get a single `Property` flagged
48860                     // symbol of name `export=` which needs to be handled like an alias. It's not great, but it is what it is.
48861                     if (symbol.flags & (2 /* BlockScopedVariable */ | 1 /* FunctionScopedVariable */ | 4 /* Property */)
48862                         && symbol.escapedName !== "export=" /* ExportEquals */
48863                         && !(symbol.flags & 4194304 /* Prototype */)
48864                         && !(symbol.flags & 32 /* Class */)
48865                         && !isConstMergedWithNSPrintableAsSignatureMerge) {
48866                         if (propertyAsAlias) {
48867                             var createdExport = serializeMaybeAliasAssignment(symbol);
48868                             if (createdExport) {
48869                                 needsExportDeclaration = false;
48870                                 needsPostExportDefault = false;
48871                             }
48872                         }
48873                         else {
48874                             var type = getTypeOfSymbol(symbol);
48875                             var localName = getInternalSymbolName(symbol, symbolName);
48876                             if (!(symbol.flags & 16 /* Function */) && isTypeRepresentableAsFunctionNamespaceMerge(type, symbol)) {
48877                                 // 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
48878                                 serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags);
48879                             }
48880                             else {
48881                                 // 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!_
48882                                 // `var` is `FunctionScopedVariable`, `const` and `let` are `BlockScopedVariable`, and `module.exports.thing =` is `Property`
48883                                 var flags = !(symbol.flags & 2 /* BlockScopedVariable */) ? undefined
48884                                     : isConstVariable(symbol) ? 2 /* Const */
48885                                         : 1 /* Let */;
48886                                 var name = (needsPostExportDefault || !(symbol.flags & 4 /* Property */)) ? localName : getUnusedName(localName, symbol);
48887                                 var textRange = symbol.declarations && ts.find(symbol.declarations, function (d) { return ts.isVariableDeclaration(d); });
48888                                 if (textRange && ts.isVariableDeclarationList(textRange.parent) && textRange.parent.declarations.length === 1) {
48889                                     textRange = textRange.parent.parent;
48890                                 }
48891                                 var propertyAccessRequire = ts.find(symbol.declarations, ts.isPropertyAccessExpression);
48892                                 if (propertyAccessRequire && ts.isBinaryExpression(propertyAccessRequire.parent) && ts.isIdentifier(propertyAccessRequire.parent.right)
48893                                     && type.symbol && ts.isSourceFile(type.symbol.valueDeclaration)) {
48894                                     var alias = localName === propertyAccessRequire.parent.right.escapedText ? undefined : propertyAccessRequire.parent.right;
48895                                     addResult(ts.factory.createExportDeclaration(
48896                                     /*decorators*/ undefined, 
48897                                     /*modifiers*/ undefined, 
48898                                     /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(alias, localName)])), 0 /* None */);
48899                                     context.tracker.trackSymbol(type.symbol, context.enclosingDeclaration, 111551 /* Value */);
48900                                 }
48901                                 else {
48902                                     var statement = ts.setTextRange(ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
48903                                         ts.factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, type, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
48904                                     ], flags)), textRange);
48905                                     addResult(statement, name !== localName ? modifierFlags & ~1 /* Export */ : modifierFlags);
48906                                     if (name !== localName && !isPrivate) {
48907                                         // We rename the variable declaration we generate for Property symbols since they may have a name which
48908                                         // conflicts with a local declaration. For example, given input:
48909                                         // ```
48910                                         // function g() {}
48911                                         // module.exports.g = g
48912                                         // ```
48913                                         // In such a situation, we have a local variable named `g`, and a separate exported variable named `g`.
48914                                         // Naively, we would emit
48915                                         // ```
48916                                         // function g() {}
48917                                         // export const g: typeof g;
48918                                         // ```
48919                                         // That's obviously incorrect - the `g` in the type annotation needs to refer to the local `g`, but
48920                                         // the export declaration shadows it.
48921                                         // To work around that, we instead write
48922                                         // ```
48923                                         // function g() {}
48924                                         // const g_1: typeof g;
48925                                         // export { g_1 as g };
48926                                         // ```
48927                                         // To create an export named `g` that does _not_ shadow the local `g`
48928                                         addResult(ts.factory.createExportDeclaration(
48929                                         /*decorators*/ undefined, 
48930                                         /*modifiers*/ undefined, 
48931                                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(name, localName)])), 0 /* None */);
48932                                         needsExportDeclaration = false;
48933                                         needsPostExportDefault = false;
48934                                     }
48935                                 }
48936                             }
48937                         }
48938                     }
48939                     if (symbol.flags & 384 /* Enum */) {
48940                         serializeEnum(symbol, symbolName, modifierFlags);
48941                     }
48942                     if (symbol.flags & 32 /* Class */) {
48943                         if (symbol.flags & 4 /* Property */ && ts.isBinaryExpression(symbol.valueDeclaration.parent) && ts.isClassExpression(symbol.valueDeclaration.parent.right)) {
48944                             // Looks like a `module.exports.Sub = class {}` - if we serialize `symbol` as a class, the result will have no members,
48945                             // since the classiness is actually from the target of the effective alias the symbol is. yes. A BlockScopedVariable|Class|Property
48946                             // _really_ acts like an Alias, and none of a BlockScopedVariable, Class, or Property. This is the travesty of JS binding today.
48947                             serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
48948                         }
48949                         else {
48950                             serializeAsClass(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
48951                         }
48952                     }
48953                     if ((symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && (!isConstMergedWithNS || isTypeOnlyNamespace(symbol))) || isConstMergedWithNSPrintableAsSignatureMerge) {
48954                         serializeModule(symbol, symbolName, modifierFlags);
48955                     }
48956                     // The class meaning serialization should handle serializing all interface members
48957                     if (symbol.flags & 64 /* Interface */ && !(symbol.flags & 32 /* Class */)) {
48958                         serializeInterface(symbol, symbolName, modifierFlags);
48959                     }
48960                     if (symbol.flags & 2097152 /* Alias */) {
48961                         serializeAsAlias(symbol, getInternalSymbolName(symbol, symbolName), modifierFlags);
48962                     }
48963                     if (symbol.flags & 4 /* Property */ && symbol.escapedName === "export=" /* ExportEquals */) {
48964                         serializeMaybeAliasAssignment(symbol);
48965                     }
48966                     if (symbol.flags & 8388608 /* ExportStar */) {
48967                         // synthesize export * from "moduleReference"
48968                         // Straightforward - only one thing to do - make an export declaration
48969                         for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
48970                             var node = _a[_i];
48971                             var resolvedModule = resolveExternalModuleName(node, node.moduleSpecifier);
48972                             if (!resolvedModule)
48973                                 continue;
48974                             addResult(ts.factory.createExportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*isTypeOnly*/ false, /*exportClause*/ undefined, ts.factory.createStringLiteral(getSpecifierForModuleSymbol(resolvedModule, context))), 0 /* None */);
48975                         }
48976                     }
48977                     if (needsPostExportDefault) {
48978                         addResult(ts.factory.createExportAssignment(/*decorators*/ undefined, /*modifiers*/ undefined, /*isExportAssignment*/ false, ts.factory.createIdentifier(getInternalSymbolName(symbol, symbolName))), 0 /* None */);
48979                     }
48980                     else if (needsExportDeclaration) {
48981                         addResult(ts.factory.createExportDeclaration(
48982                         /*decorators*/ undefined, 
48983                         /*modifiers*/ undefined, 
48984                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(getInternalSymbolName(symbol, symbolName), symbolName)])), 0 /* None */);
48985                     }
48986                 }
48987                 function includePrivateSymbol(symbol) {
48988                     if (ts.some(symbol.declarations, ts.isParameterDeclaration))
48989                         return;
48990                     ts.Debug.assertIsDefined(deferredPrivatesStack[deferredPrivatesStack.length - 1]);
48991                     getUnusedName(ts.unescapeLeadingUnderscores(symbol.escapedName), symbol); // Call to cache unique name for symbol
48992                     // Blanket moving (import) aliases into the root private context should work, since imports are not valid within namespaces
48993                     // (so they must have been in the root to begin with if they were real imports) cjs `require` aliases (an upcoming feature)
48994                     // will throw a wrench in this, since those may have been nested, but we'll need to synthesize them in the outer scope
48995                     // anyway, as that's the only place the import they translate to is valid. In such a case, we might need to use a unique name
48996                     // for the moved import; which hopefully the above `getUnusedName` call should produce.
48997                     var isExternalImportAlias = !!(symbol.flags & 2097152 /* Alias */) && !ts.some(symbol.declarations, function (d) {
48998                         return !!ts.findAncestor(d, ts.isExportDeclaration) ||
48999                             ts.isNamespaceExport(d) ||
49000                             (ts.isImportEqualsDeclaration(d) && !ts.isExternalModuleReference(d.moduleReference));
49001                     });
49002                     deferredPrivatesStack[isExternalImportAlias ? 0 : (deferredPrivatesStack.length - 1)].set(getSymbolId(symbol), symbol);
49003                 }
49004                 function isExportingScope(enclosingDeclaration) {
49005                     return ((ts.isSourceFile(enclosingDeclaration) && (ts.isExternalOrCommonJsModule(enclosingDeclaration) || ts.isJsonSourceFile(enclosingDeclaration))) ||
49006                         (ts.isAmbientModule(enclosingDeclaration) && !ts.isGlobalScopeAugmentation(enclosingDeclaration)));
49007                 }
49008                 // Prepends a `declare` and/or `export` modifier if the context requires it, and then adds `node` to `result` and returns `node`
49009                 function addResult(node, additionalModifierFlags) {
49010                     if (ts.canHaveModifiers(node)) {
49011                         var newModifierFlags = 0 /* None */;
49012                         if (additionalModifierFlags & 1 /* Export */ &&
49013                             context.enclosingDeclaration &&
49014                             (isExportingScope(context.enclosingDeclaration) || ts.isModuleDeclaration(context.enclosingDeclaration)) &&
49015                             canHaveExportModifier(node)) {
49016                             // Classes, namespaces, variables, functions, interfaces, and types should all be `export`ed in a module context if not private
49017                             newModifierFlags |= 1 /* Export */;
49018                         }
49019                         if (addingDeclare && !(newModifierFlags & 1 /* Export */) &&
49020                             (!context.enclosingDeclaration || !(context.enclosingDeclaration.flags & 8388608 /* Ambient */)) &&
49021                             (ts.isEnumDeclaration(node) || ts.isVariableStatement(node) || ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node) || ts.isModuleDeclaration(node))) {
49022                             // Classes, namespaces, variables, enums, and functions all need `declare` modifiers to be valid in a declaration file top-level scope
49023                             newModifierFlags |= 2 /* Ambient */;
49024                         }
49025                         if ((additionalModifierFlags & 512 /* Default */) && (ts.isClassDeclaration(node) || ts.isInterfaceDeclaration(node) || ts.isFunctionDeclaration(node))) {
49026                             newModifierFlags |= 512 /* Default */;
49027                         }
49028                         if (newModifierFlags) {
49029                             node = ts.factory.updateModifiers(node, newModifierFlags | ts.getEffectiveModifierFlags(node));
49030                         }
49031                     }
49032                     results.push(node);
49033                 }
49034                 function serializeTypeAlias(symbol, symbolName, modifierFlags) {
49035                     var aliasType = getDeclaredTypeOfTypeAlias(symbol);
49036                     var typeParams = getSymbolLinks(symbol).typeParameters;
49037                     var typeParamDecls = ts.map(typeParams, function (p) { return typeParameterToDeclaration(p, context); });
49038                     var jsdocAliasDecl = ts.find(symbol.declarations, ts.isJSDocTypeAlias);
49039                     var commentText = jsdocAliasDecl ? jsdocAliasDecl.comment || jsdocAliasDecl.parent.comment : undefined;
49040                     var oldFlags = context.flags;
49041                     context.flags |= 8388608 /* InTypeAlias */;
49042                     addResult(ts.setSyntheticLeadingComments(ts.factory.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);
49043                     context.flags = oldFlags;
49044                 }
49045                 function serializeInterface(symbol, symbolName, modifierFlags) {
49046                     var interfaceType = getDeclaredTypeOfClassOrInterface(symbol);
49047                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
49048                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
49049                     var baseTypes = getBaseTypes(interfaceType);
49050                     var baseType = ts.length(baseTypes) ? getIntersectionType(baseTypes) : undefined;
49051                     var members = ts.flatMap(getPropertiesOfType(interfaceType), function (p) { return serializePropertySymbolForInterface(p, baseType); });
49052                     var callSignatures = serializeSignatures(0 /* Call */, interfaceType, baseType, 169 /* CallSignature */);
49053                     var constructSignatures = serializeSignatures(1 /* Construct */, interfaceType, baseType, 170 /* ConstructSignature */);
49054                     var indexSignatures = serializeIndexSignatures(interfaceType, baseType);
49055                     var heritageClauses = !ts.length(baseTypes) ? undefined : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.mapDefined(baseTypes, function (b) { return trySerializeAsTypeReference(b, 111551 /* Value */); }))];
49056                     addResult(ts.factory.createInterfaceDeclaration(
49057                     /*decorators*/ undefined, 
49058                     /*modifiers*/ undefined, getInternalSymbolName(symbol, symbolName), typeParamDecls, heritageClauses, __spreadArrays(indexSignatures, constructSignatures, callSignatures, members)), modifierFlags);
49059                 }
49060                 function getNamespaceMembersForSerialization(symbol) {
49061                     return !symbol.exports ? [] : ts.filter(ts.arrayFrom(symbol.exports.values()), isNamespaceMember);
49062                 }
49063                 function isTypeOnlyNamespace(symbol) {
49064                     return ts.every(getNamespaceMembersForSerialization(symbol), function (m) { return !(resolveSymbol(m).flags & 111551 /* Value */); });
49065                 }
49066                 function serializeModule(symbol, symbolName, modifierFlags) {
49067                     var members = getNamespaceMembersForSerialization(symbol);
49068                     // 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)
49069                     var locationMap = ts.arrayToMultiMap(members, function (m) { return m.parent && m.parent === symbol ? "real" : "merged"; });
49070                     var realMembers = locationMap.get("real") || ts.emptyArray;
49071                     var mergedMembers = locationMap.get("merged") || ts.emptyArray;
49072                     // TODO: `suppressNewPrivateContext` is questionable -we need to simply be emitting privates in whatever scope they were declared in, rather
49073                     // 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,
49074                     // so we don't even have placeholders to fill in.
49075                     if (ts.length(realMembers)) {
49076                         var localName = getInternalSymbolName(symbol, symbolName);
49077                         serializeAsNamespaceDeclaration(realMembers, localName, modifierFlags, !!(symbol.flags & (16 /* Function */ | 67108864 /* Assignment */)));
49078                     }
49079                     if (ts.length(mergedMembers)) {
49080                         var containingFile_1 = ts.getSourceFileOfNode(context.enclosingDeclaration);
49081                         var localName = getInternalSymbolName(symbol, symbolName);
49082                         var nsBody = ts.factory.createModuleBlock([ts.factory.createExportDeclaration(
49083                             /*decorators*/ undefined, 
49084                             /*modifiers*/ undefined, 
49085                             /*isTypeOnly*/ false, ts.factory.createNamedExports(ts.mapDefined(ts.filter(mergedMembers, function (n) { return n.escapedName !== "export=" /* ExportEquals */; }), function (s) {
49086                                 var _a, _b;
49087                                 var name = ts.unescapeLeadingUnderscores(s.escapedName);
49088                                 var localName = getInternalSymbolName(s, name);
49089                                 var aliasDecl = s.declarations && getDeclarationOfAliasSymbol(s);
49090                                 if (containingFile_1 && (aliasDecl ? containingFile_1 !== ts.getSourceFileOfNode(aliasDecl) : !ts.some(s.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile_1; }))) {
49091                                     (_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);
49092                                     return undefined;
49093                                 }
49094                                 var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
49095                                 includePrivateSymbol(target || s);
49096                                 var targetName = target ? getInternalSymbolName(target, ts.unescapeLeadingUnderscores(target.escapedName)) : localName;
49097                                 return ts.factory.createExportSpecifier(name === targetName ? undefined : targetName, name);
49098                             })))]);
49099                         addResult(ts.factory.createModuleDeclaration(
49100                         /*decorators*/ undefined, 
49101                         /*modifiers*/ undefined, ts.factory.createIdentifier(localName), nsBody, 16 /* Namespace */), 0 /* None */);
49102                     }
49103                 }
49104                 function serializeEnum(symbol, symbolName, modifierFlags) {
49105                     addResult(ts.factory.createEnumDeclaration(
49106                     /*decorators*/ undefined, ts.factory.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) {
49107                         // TODO: Handle computed names
49108                         // I hate that to get the initialized value we need to walk back to the declarations here; but there's no
49109                         // other way to get the possible const value of an enum member that I'm aware of, as the value is cached
49110                         // _on the declaration_, not on the declaration's symbol...
49111                         var initializedValue = p.declarations && p.declarations[0] && ts.isEnumMember(p.declarations[0]) ? getConstantValue(p.declarations[0]) : undefined;
49112                         return ts.factory.createEnumMember(ts.unescapeLeadingUnderscores(p.escapedName), initializedValue === undefined ? undefined :
49113                             typeof initializedValue === "string" ? ts.factory.createStringLiteral(initializedValue) :
49114                                 ts.factory.createNumericLiteral(initializedValue));
49115                     })), modifierFlags);
49116                 }
49117                 function serializeAsFunctionNamespaceMerge(type, symbol, localName, modifierFlags) {
49118                     var signatures = getSignaturesOfType(type, 0 /* Call */);
49119                     for (var _i = 0, signatures_2 = signatures; _i < signatures_2.length; _i++) {
49120                         var sig = signatures_2[_i];
49121                         // Each overload becomes a separate function declaration, in order
49122                         var decl = signatureToSignatureDeclarationHelper(sig, 251 /* FunctionDeclaration */, context, { name: ts.factory.createIdentifier(localName), privateSymbolVisitor: includePrivateSymbol, bundledImports: bundled });
49123                         // for expressions assigned to `var`s, use the `var` as the text range
49124                         addResult(ts.setTextRange(decl, sig.declaration && ts.isVariableDeclaration(sig.declaration.parent) && sig.declaration.parent.parent || sig.declaration), modifierFlags);
49125                     }
49126                     // Module symbol emit will take care of module-y members, provided it has exports
49127                     if (!(symbol.flags & (512 /* ValueModule */ | 1024 /* NamespaceModule */) && !!symbol.exports && !!symbol.exports.size)) {
49128                         var props = ts.filter(getPropertiesOfType(type), isNamespaceMember);
49129                         serializeAsNamespaceDeclaration(props, localName, modifierFlags, /*suppressNewPrivateContext*/ true);
49130                     }
49131                 }
49132                 function serializeAsNamespaceDeclaration(props, localName, modifierFlags, suppressNewPrivateContext) {
49133                     if (ts.length(props)) {
49134                         var localVsRemoteMap = ts.arrayToMultiMap(props, function (p) {
49135                             return !ts.length(p.declarations) || ts.some(p.declarations, function (d) {
49136                                 return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(context.enclosingDeclaration);
49137                             }) ? "local" : "remote";
49138                         });
49139                         var localProps = localVsRemoteMap.get("local") || ts.emptyArray;
49140                         // handle remote props first - we need to make an `import` declaration that points at the module containing each remote
49141                         // prop in the outermost scope (TODO: a namespace within a namespace would need to be appropriately handled by this)
49142                         // Example:
49143                         // import Foo_1 = require("./exporter");
49144                         // export namespace ns {
49145                         //     import Foo = Foo_1.Foo;
49146                         //     export { Foo };
49147                         //     export const c: number;
49148                         // }
49149                         // This is needed because in JS, statements like `const x = require("./f")` support both type and value lookup, even if they're
49150                         // normally just value lookup (so it functions kinda like an alias even when it's not an alias)
49151                         // _Usually_, we'll simply print the top-level as an alias instead of a `var` in such situations, however is is theoretically
49152                         // possible to encounter a situation where a type has members from both the current file and other files - in those situations,
49153                         // emit akin to the above would be needed.
49154                         // Add a namespace
49155                         // Create namespace as non-synthetic so it is usable as an enclosing declaration
49156                         var fakespace = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createModuleBlock([]), 16 /* Namespace */);
49157                         ts.setParent(fakespace, enclosingDeclaration);
49158                         fakespace.locals = ts.createSymbolTable(props);
49159                         fakespace.symbol = props[0].parent;
49160                         var oldResults = results;
49161                         results = [];
49162                         var oldAddingDeclare = addingDeclare;
49163                         addingDeclare = false;
49164                         var subcontext = __assign(__assign({}, context), { enclosingDeclaration: fakespace });
49165                         var oldContext = context;
49166                         context = subcontext;
49167                         // 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
49168                         visitSymbolTable(ts.createSymbolTable(localProps), suppressNewPrivateContext, /*propertyAsAlias*/ true);
49169                         context = oldContext;
49170                         addingDeclare = oldAddingDeclare;
49171                         var declarations = results;
49172                         results = oldResults;
49173                         // replace namespace with synthetic version
49174                         var defaultReplaced = ts.map(declarations, function (d) { return ts.isExportAssignment(d) && !d.isExportEquals && ts.isIdentifier(d.expression) ? ts.factory.createExportDeclaration(
49175                         /*decorators*/ undefined, 
49176                         /*modifiers*/ undefined, 
49177                         /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(d.expression, ts.factory.createIdentifier("default" /* Default */))])) : d; });
49178                         var exportModifierStripped = ts.every(defaultReplaced, function (d) { return ts.hasSyntacticModifier(d, 1 /* Export */); }) ? ts.map(defaultReplaced, removeExportModifier) : defaultReplaced;
49179                         fakespace = ts.factory.updateModuleDeclaration(fakespace, fakespace.decorators, fakespace.modifiers, fakespace.name, ts.factory.createModuleBlock(exportModifierStripped));
49180                         addResult(fakespace, modifierFlags); // namespaces can never be default exported
49181                     }
49182                 }
49183                 function isNamespaceMember(p) {
49184                     return !!(p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */)) ||
49185                         !(p.flags & 4194304 /* Prototype */ || p.escapedName === "prototype" || p.valueDeclaration && ts.getEffectiveModifierFlags(p.valueDeclaration) & 32 /* Static */ && ts.isClassLike(p.valueDeclaration.parent));
49186                 }
49187                 function serializeAsClass(symbol, localName, modifierFlags) {
49188                     var _a;
49189                     var localParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
49190                     var typeParamDecls = ts.map(localParams, function (p) { return typeParameterToDeclaration(p, context); });
49191                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
49192                     var baseTypes = getBaseTypes(classType);
49193                     var implementsExpressions = ts.mapDefined(getImplementsTypes(classType), serializeImplementedType);
49194                     var staticType = getTypeOfSymbol(symbol);
49195                     var isClass = !!((_a = staticType.symbol) === null || _a === void 0 ? void 0 : _a.valueDeclaration) && ts.isClassLike(staticType.symbol.valueDeclaration);
49196                     var staticBaseType = isClass
49197                         ? getBaseConstructorTypeOfClass(staticType)
49198                         : anyType;
49199                     var heritageClauses = __spreadArrays(!ts.length(baseTypes) ? [] : [ts.factory.createHeritageClause(93 /* ExtendsKeyword */, ts.map(baseTypes, function (b) { return serializeBaseType(b, staticBaseType, localName); }))], !ts.length(implementsExpressions) ? [] : [ts.factory.createHeritageClause(116 /* ImplementsKeyword */, implementsExpressions)]);
49200                     var symbolProps = getNonInterhitedProperties(classType, baseTypes, getPropertiesOfType(classType));
49201                     var publicSymbolProps = ts.filter(symbolProps, function (s) {
49202                         // `valueDeclaration` could be undefined if inherited from
49203                         // a union/intersection base type, but inherited properties
49204                         // don't matter here.
49205                         var valueDecl = s.valueDeclaration;
49206                         return valueDecl && !(ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name));
49207                     });
49208                     var hasPrivateIdentifier = ts.some(symbolProps, function (s) {
49209                         // `valueDeclaration` could be undefined if inherited from
49210                         // a union/intersection base type, but inherited properties
49211                         // don't matter here.
49212                         var valueDecl = s.valueDeclaration;
49213                         return valueDecl && ts.isNamedDeclaration(valueDecl) && ts.isPrivateIdentifier(valueDecl.name);
49214                     });
49215                     // Boil down all private properties into a single one.
49216                     var privateProperties = hasPrivateIdentifier ?
49217                         [ts.factory.createPropertyDeclaration(
49218                             /*decorators*/ undefined, 
49219                             /*modifiers*/ undefined, ts.factory.createPrivateIdentifier("#private"), 
49220                             /*questionOrExclamationToken*/ undefined, 
49221                             /*type*/ undefined, 
49222                             /*initializer*/ undefined)] :
49223                         ts.emptyArray;
49224                     var publicProperties = ts.flatMap(publicSymbolProps, function (p) { return serializePropertySymbolForClass(p, /*isStatic*/ false, baseTypes[0]); });
49225                     // Consider static members empty if symbol also has function or module meaning - function namespacey emit will handle statics
49226                     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); });
49227                     // When we encounter an `X.prototype.y` assignment in a JS file, we bind `X` as a class regardless as to whether
49228                     // the value is ever initialized with a class or function-like value. For cases where `X` could never be
49229                     // created via `new`, we will inject a `private constructor()` declaration to indicate it is not createable.
49230                     var isNonConstructableClassLikeInJsFile = !isClass &&
49231                         !!symbol.valueDeclaration &&
49232                         ts.isInJSFile(symbol.valueDeclaration) &&
49233                         !ts.some(getSignaturesOfType(staticType, 1 /* Construct */));
49234                     var constructors = isNonConstructableClassLikeInJsFile ?
49235                         [ts.factory.createConstructorDeclaration(/*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(8 /* Private */), [], /*body*/ undefined)] :
49236                         serializeSignatures(1 /* Construct */, staticType, baseTypes[0], 166 /* Constructor */);
49237                     var indexSignatures = serializeIndexSignatures(classType, baseTypes[0]);
49238                     addResult(ts.setTextRange(ts.factory.createClassDeclaration(
49239                     /*decorators*/ undefined, 
49240                     /*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);
49241                 }
49242                 function serializeAsAlias(symbol, localName, modifierFlags) {
49243                     var _a, _b, _c, _d, _e;
49244                     // synthesize an alias, eg `export { symbolName as Name }`
49245                     // need to mark the alias `symbol` points at
49246                     // as something we need to serialize as a private declaration as well
49247                     var node = getDeclarationOfAliasSymbol(symbol);
49248                     if (!node)
49249                         return ts.Debug.fail();
49250                     var target = getMergedSymbol(getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true));
49251                     if (!target) {
49252                         return;
49253                     }
49254                     var verbatimTargetName = ts.unescapeLeadingUnderscores(target.escapedName);
49255                     if (verbatimTargetName === "export=" /* ExportEquals */ && (compilerOptions.esModuleInterop || compilerOptions.allowSyntheticDefaultImports)) {
49256                         // target refers to an `export=` symbol that was hoisted into a synthetic default - rename here to match
49257                         verbatimTargetName = "default" /* Default */;
49258                     }
49259                     var targetName = getInternalSymbolName(target, verbatimTargetName);
49260                     includePrivateSymbol(target); // the target may be within the same scope - attempt to serialize it first
49261                     switch (node.kind) {
49262                         case 198 /* BindingElement */:
49263                             if (((_b = (_a = node.parent) === null || _a === void 0 ? void 0 : _a.parent) === null || _b === void 0 ? void 0 : _b.kind) === 249 /* VariableDeclaration */) {
49264                                 // const { SomeClass } = require('./lib');
49265                                 var specifier_1 = getSpecifierForModuleSymbol(target.parent || target, context); // './lib'
49266                                 var propertyName = node.propertyName;
49267                                 addResult(ts.factory.createImportDeclaration(
49268                                 /*decorators*/ undefined, 
49269                                 /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*name*/ undefined, ts.factory.createNamedImports([ts.factory.createImportSpecifier(propertyName && ts.isIdentifier(propertyName) ? ts.factory.createIdentifier(ts.idText(propertyName)) : undefined, ts.factory.createIdentifier(localName))])), ts.factory.createStringLiteral(specifier_1)), 0 /* None */);
49270                                 break;
49271                             }
49272                             // We don't know how to serialize this (nested?) binding element
49273                             ts.Debug.failBadSyntaxKind(((_c = node.parent) === null || _c === void 0 ? void 0 : _c.parent) || node, "Unhandled binding element grandparent kind in declaration serialization");
49274                             break;
49275                         case 289 /* ShorthandPropertyAssignment */:
49276                             if (((_e = (_d = node.parent) === null || _d === void 0 ? void 0 : _d.parent) === null || _e === void 0 ? void 0 : _e.kind) === 216 /* BinaryExpression */) {
49277                                 // module.exports = { SomeClass }
49278                                 serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), targetName);
49279                             }
49280                             break;
49281                         case 249 /* VariableDeclaration */:
49282                             // commonjs require: const x = require('y')
49283                             if (ts.isPropertyAccessExpression(node.initializer)) {
49284                                 // const x = require('y').z
49285                                 var initializer = node.initializer; // require('y').z
49286                                 var uniqueName = ts.factory.createUniqueName(localName); // _x
49287                                 var specifier_2 = getSpecifierForModuleSymbol(target.parent || target, context); // 'y'
49288                                 // import _x = require('y');
49289                                 addResult(ts.factory.createImportEqualsDeclaration(
49290                                 /*decorators*/ undefined, 
49291                                 /*modifiers*/ undefined, uniqueName, ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(specifier_2))), 0 /* None */);
49292                                 // import x = _x.z
49293                                 addResult(ts.factory.createImportEqualsDeclaration(
49294                                 /*decorators*/ undefined, 
49295                                 /*modifiers*/ undefined, ts.factory.createIdentifier(localName), ts.factory.createQualifiedName(uniqueName, initializer.name)), modifierFlags);
49296                                 break;
49297                             }
49298                         // else fall through and treat commonjs require just like import=
49299                         case 260 /* ImportEqualsDeclaration */:
49300                             // This _specifically_ only exists to handle json declarations - where we make aliases, but since
49301                             // we emit no declarations for the json document, must not refer to it in the declarations
49302                             if (target.escapedName === "export=" /* ExportEquals */ && ts.some(target.declarations, ts.isJsonSourceFile)) {
49303                                 serializeMaybeAliasAssignment(symbol);
49304                                 break;
49305                             }
49306                             // Could be a local `import localName = ns.member` or
49307                             // an external `import localName = require("whatever")`
49308                             var isLocalImport = !(target.flags & 512 /* ValueModule */) && !ts.isVariableDeclaration(node);
49309                             addResult(ts.factory.createImportEqualsDeclaration(
49310                             /*decorators*/ undefined, 
49311                             /*modifiers*/ undefined, ts.factory.createIdentifier(localName), isLocalImport
49312                                 ? symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)
49313                                 : ts.factory.createExternalModuleReference(ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context)))), isLocalImport ? modifierFlags : 0 /* None */);
49314                             break;
49315                         case 259 /* NamespaceExportDeclaration */:
49316                             // export as namespace foo
49317                             // TODO: Not part of a file's local or export symbol tables
49318                             // Is bound into file.symbol.globalExports instead, which we don't currently traverse
49319                             addResult(ts.factory.createNamespaceExportDeclaration(ts.idText(node.name)), 0 /* None */);
49320                             break;
49321                         case 262 /* ImportClause */:
49322                             addResult(ts.factory.createImportDeclaration(
49323                             /*decorators*/ undefined, 
49324                             /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, ts.factory.createIdentifier(localName), /*namedBindings*/ undefined), 
49325                             // We use `target.parent || target` below as `target.parent` is unset when the target is a module which has been export assigned
49326                             // And then made into a default by the `esModuleInterop` or `allowSyntheticDefaultImports` flag
49327                             // In such cases, the `target` refers to the module itself already
49328                             ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
49329                             break;
49330                         case 263 /* NamespaceImport */:
49331                             addResult(ts.factory.createImportDeclaration(
49332                             /*decorators*/ undefined, 
49333                             /*modifiers*/ undefined, ts.factory.createImportClause(/*isTypeOnly*/ false, /*importClause*/ undefined, ts.factory.createNamespaceImport(ts.factory.createIdentifier(localName))), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
49334                             break;
49335                         case 269 /* NamespaceExport */:
49336                             addResult(ts.factory.createExportDeclaration(
49337                             /*decorators*/ undefined, 
49338                             /*modifiers*/ undefined, 
49339                             /*isTypeOnly*/ false, ts.factory.createNamespaceExport(ts.factory.createIdentifier(localName)), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target, context))), 0 /* None */);
49340                             break;
49341                         case 265 /* ImportSpecifier */:
49342                             addResult(ts.factory.createImportDeclaration(
49343                             /*decorators*/ undefined, 
49344                             /*modifiers*/ undefined, ts.factory.createImportClause(
49345                             /*isTypeOnly*/ false, 
49346                             /*importClause*/ undefined, ts.factory.createNamedImports([
49347                                 ts.factory.createImportSpecifier(localName !== verbatimTargetName ? ts.factory.createIdentifier(verbatimTargetName) : undefined, ts.factory.createIdentifier(localName))
49348                             ])), ts.factory.createStringLiteral(getSpecifierForModuleSymbol(target.parent || target, context))), 0 /* None */);
49349                             break;
49350                         case 270 /* ExportSpecifier */:
49351                             // does not use localName because the symbol name in this case refers to the name in the exports table,
49352                             // which we must exactly preserve
49353                             var specifier = node.parent.parent.moduleSpecifier;
49354                             // targetName is only used when the target is local, as otherwise the target is an alias that points at
49355                             // another file
49356                             serializeExportSpecifier(ts.unescapeLeadingUnderscores(symbol.escapedName), specifier ? verbatimTargetName : targetName, specifier && ts.isStringLiteralLike(specifier) ? ts.factory.createStringLiteral(specifier.text) : undefined);
49357                             break;
49358                         case 266 /* ExportAssignment */:
49359                             serializeMaybeAliasAssignment(symbol);
49360                             break;
49361                         case 216 /* BinaryExpression */:
49362                         case 201 /* PropertyAccessExpression */:
49363                         case 202 /* ElementAccessExpression */:
49364                             // Could be best encoded as though an export specifier or as though an export assignment
49365                             // If name is default or export=, do an export assignment
49366                             // Otherwise do an export specifier
49367                             if (symbol.escapedName === "default" /* Default */ || symbol.escapedName === "export=" /* ExportEquals */) {
49368                                 serializeMaybeAliasAssignment(symbol);
49369                             }
49370                             else {
49371                                 serializeExportSpecifier(localName, targetName);
49372                             }
49373                             break;
49374                         default:
49375                             return ts.Debug.failBadSyntaxKind(node, "Unhandled alias declaration kind in symbol serializer!");
49376                     }
49377                 }
49378                 function serializeExportSpecifier(localName, targetName, specifier) {
49379                     addResult(ts.factory.createExportDeclaration(
49380                     /*decorators*/ undefined, 
49381                     /*modifiers*/ undefined, 
49382                     /*isTypeOnly*/ false, ts.factory.createNamedExports([ts.factory.createExportSpecifier(localName !== targetName ? targetName : undefined, localName)]), specifier), 0 /* None */);
49383                 }
49384                 /**
49385                  * Returns `true` if an export assignment or declaration was produced for the symbol
49386                  */
49387                 function serializeMaybeAliasAssignment(symbol) {
49388                     if (symbol.flags & 4194304 /* Prototype */) {
49389                         return false;
49390                     }
49391                     var name = ts.unescapeLeadingUnderscores(symbol.escapedName);
49392                     var isExportEquals = name === "export=" /* ExportEquals */;
49393                     var isDefault = name === "default" /* Default */;
49394                     var isExportAssignmentCompatibleSymbolName = isExportEquals || isDefault;
49395                     // synthesize export = ref
49396                     // ref should refer to either be a locally scoped symbol which we need to emit, or
49397                     // a reference to another namespace/module which we may need to emit an `import` statement for
49398                     var aliasDecl = symbol.declarations && getDeclarationOfAliasSymbol(symbol);
49399                     // serialize what the alias points to, preserve the declaration's initializer
49400                     var target = aliasDecl && getTargetOfAliasDeclaration(aliasDecl, /*dontRecursivelyResolve*/ true);
49401                     // If the target resolves and resolves to a thing defined in this file, emit as an alias, otherwise emit as a const
49402                     if (target && ts.length(target.declarations) && ts.some(target.declarations, function (d) { return ts.getSourceFileOfNode(d) === ts.getSourceFileOfNode(enclosingDeclaration); })) {
49403                         // In case `target` refers to a namespace member, look at the declaration and serialize the leftmost symbol in it
49404                         // eg, `namespace A { export class B {} }; exports = A.B;`
49405                         // Technically, this is all that's required in the case where the assignment is an entity name expression
49406                         var expr = aliasDecl && ((ts.isExportAssignment(aliasDecl) || ts.isBinaryExpression(aliasDecl)) ? ts.getExportAssignmentExpression(aliasDecl) : ts.getPropertyAssignmentAliasLikeExpression(aliasDecl));
49407                         var first_1 = expr && ts.isEntityNameExpression(expr) ? getFirstNonModuleExportsIdentifier(expr) : undefined;
49408                         var referenced = first_1 && resolveEntityName(first_1, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, enclosingDeclaration);
49409                         if (referenced || target) {
49410                             includePrivateSymbol(referenced || target);
49411                         }
49412                         // We disable the context's symbol tracker for the duration of this name serialization
49413                         // as, by virtue of being here, the name is required to print something, and we don't want to
49414                         // issue a visibility error on it. Only anonymous classes that an alias points at _would_ issue
49415                         // a visibility error here (as they're not visible within any scope), but we want to hoist them
49416                         // into the containing scope anyway, so we want to skip the visibility checks.
49417                         var oldTrack = context.tracker.trackSymbol;
49418                         context.tracker.trackSymbol = ts.noop;
49419                         if (isExportAssignmentCompatibleSymbolName) {
49420                             results.push(ts.factory.createExportAssignment(
49421                             /*decorators*/ undefined, 
49422                             /*modifiers*/ undefined, isExportEquals, symbolToExpression(target, context, 67108863 /* All */)));
49423                         }
49424                         else {
49425                             if (first_1 === expr && first_1) {
49426                                 // serialize as `export {target as name}`
49427                                 serializeExportSpecifier(name, ts.idText(first_1));
49428                             }
49429                             else if (expr && ts.isClassExpression(expr)) {
49430                                 serializeExportSpecifier(name, getInternalSymbolName(target, ts.symbolName(target)));
49431                             }
49432                             else {
49433                                 // serialize as `import _Ref = t.arg.et; export { _Ref as name }`
49434                                 var varName = getUnusedName(name, symbol);
49435                                 addResult(ts.factory.createImportEqualsDeclaration(
49436                                 /*decorators*/ undefined, 
49437                                 /*modifiers*/ undefined, ts.factory.createIdentifier(varName), symbolToName(target, context, 67108863 /* All */, /*expectsIdentifier*/ false)), 0 /* None */);
49438                                 serializeExportSpecifier(name, varName);
49439                             }
49440                         }
49441                         context.tracker.trackSymbol = oldTrack;
49442                         return true;
49443                     }
49444                     else {
49445                         // serialize as an anonymous property declaration
49446                         var varName = getUnusedName(name, symbol);
49447                         // We have to use `getWidenedType` here since the object within a json file is unwidened within the file
49448                         // (Unwidened types can only exist in expression contexts and should never be serialized)
49449                         var typeToSerialize = getWidenedType(getTypeOfSymbol(getMergedSymbol(symbol)));
49450                         if (isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, symbol)) {
49451                             // If there are no index signatures and `typeToSerialize` is an object type, emit as a namespace instead of a const
49452                             serializeAsFunctionNamespaceMerge(typeToSerialize, symbol, varName, isExportAssignmentCompatibleSymbolName ? 0 /* None */ : 1 /* Export */);
49453                         }
49454                         else {
49455                             var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
49456                                 ts.factory.createVariableDeclaration(varName, /*exclamationToken*/ undefined, serializeTypeForDeclaration(context, typeToSerialize, symbol, enclosingDeclaration, includePrivateSymbol, bundled))
49457                             ], 2 /* Const */));
49458                             // Inlined JSON types exported with [module.]exports= will already emit an export=, so should use `declare`.
49459                             // Otherwise, the type itself should be exported.
49460                             addResult(statement, target && target.flags & 4 /* Property */ && target.escapedName === "export=" /* ExportEquals */ ? 2 /* Ambient */
49461                                 : name === varName ? 1 /* Export */
49462                                     : 0 /* None */);
49463                         }
49464                         if (isExportAssignmentCompatibleSymbolName) {
49465                             results.push(ts.factory.createExportAssignment(
49466                             /*decorators*/ undefined, 
49467                             /*modifiers*/ undefined, isExportEquals, ts.factory.createIdentifier(varName)));
49468                             return true;
49469                         }
49470                         else if (name !== varName) {
49471                             serializeExportSpecifier(name, varName);
49472                             return true;
49473                         }
49474                         return false;
49475                     }
49476                 }
49477                 function isTypeRepresentableAsFunctionNamespaceMerge(typeToSerialize, hostSymbol) {
49478                     // Only object types which are not constructable, or indexable, whose members all come from the
49479                     // context source file, and whose property names are all valid identifiers and not late-bound, _and_
49480                     // whose input is not type annotated (if the input symbol has an annotation we can reuse, we should prefer it)
49481                     var ctxSrc = ts.getSourceFileOfNode(context.enclosingDeclaration);
49482                     return ts.getObjectFlags(typeToSerialize) & (16 /* Anonymous */ | 32 /* Mapped */) &&
49483                         !getIndexInfoOfType(typeToSerialize, 0 /* String */) &&
49484                         !getIndexInfoOfType(typeToSerialize, 1 /* Number */) &&
49485                         !isClassInstanceSide(typeToSerialize) && // While a class instance is potentially representable as a NS, prefer printing a reference to the instance type and serializing the class
49486                         !!(ts.length(ts.filter(getPropertiesOfType(typeToSerialize), isNamespaceMember)) || ts.length(getSignaturesOfType(typeToSerialize, 0 /* Call */))) &&
49487                         !ts.length(getSignaturesOfType(typeToSerialize, 1 /* Construct */)) && // TODO: could probably serialize as function + ns + class, now that that's OK
49488                         !getDeclarationWithTypeAnnotation(hostSymbol, enclosingDeclaration) &&
49489                         !(typeToSerialize.symbol && ts.some(typeToSerialize.symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; })) &&
49490                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return isLateBoundName(p.escapedName); }) &&
49491                         !ts.some(getPropertiesOfType(typeToSerialize), function (p) { return ts.some(p.declarations, function (d) { return ts.getSourceFileOfNode(d) !== ctxSrc; }); }) &&
49492                         ts.every(getPropertiesOfType(typeToSerialize), function (p) { return ts.isIdentifierText(ts.symbolName(p), languageVersion); });
49493                 }
49494                 function makeSerializePropertySymbol(createProperty, methodKind, useAccessors) {
49495                     return function serializePropertySymbol(p, isStatic, baseType) {
49496                         var modifierFlags = ts.getDeclarationModifierFlagsFromSymbol(p);
49497                         var isPrivate = !!(modifierFlags & 8 /* Private */);
49498                         if (isStatic && (p.flags & (788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */))) {
49499                             // Only value-only-meaning symbols can be correctly encoded as class statics, type/namespace/alias meaning symbols
49500                             // need to be merged namespace members
49501                             return [];
49502                         }
49503                         if (p.flags & 4194304 /* Prototype */ ||
49504                             (baseType && getPropertyOfType(baseType, p.escapedName)
49505                                 && isReadonlySymbol(getPropertyOfType(baseType, p.escapedName)) === isReadonlySymbol(p)
49506                                 && (p.flags & 16777216 /* Optional */) === (getPropertyOfType(baseType, p.escapedName).flags & 16777216 /* Optional */)
49507                                 && isTypeIdenticalTo(getTypeOfSymbol(p), getTypeOfPropertyOfType(baseType, p.escapedName)))) {
49508                             return [];
49509                         }
49510                         var flag = (modifierFlags & ~256 /* Async */) | (isStatic ? 32 /* Static */ : 0);
49511                         var name = getPropertyNameNodeForSymbol(p, context);
49512                         var firstPropertyLikeDecl = ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isAccessor, ts.isVariableDeclaration, ts.isPropertySignature, ts.isBinaryExpression, ts.isPropertyAccessExpression));
49513                         if (p.flags & 98304 /* Accessor */ && useAccessors) {
49514                             var result = [];
49515                             if (p.flags & 65536 /* SetAccessor */) {
49516                                 result.push(ts.setTextRange(ts.factory.createSetAccessorDeclaration(
49517                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [ts.factory.createParameterDeclaration(
49518                                     /*decorators*/ undefined, 
49519                                     /*modifiers*/ undefined, 
49520                                     /*dotDotDotToken*/ undefined, "arg", 
49521                                     /*questionToken*/ undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled))], 
49522                                 /*body*/ undefined), ts.find(p.declarations, ts.isSetAccessor) || firstPropertyLikeDecl));
49523                             }
49524                             if (p.flags & 32768 /* GetAccessor */) {
49525                                 var isPrivate_1 = modifierFlags & 8 /* Private */;
49526                                 result.push(ts.setTextRange(ts.factory.createGetAccessorDeclaration(
49527                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(flag), name, [], isPrivate_1 ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
49528                                 /*body*/ undefined), ts.find(p.declarations, ts.isGetAccessor) || firstPropertyLikeDecl));
49529                             }
49530                             return result;
49531                         }
49532                         // This is an else/if as accessors and properties can't merge in TS, but might in JS
49533                         // If this happens, we assume the accessor takes priority, as it imposes more constraints
49534                         else if (p.flags & (4 /* Property */ | 3 /* Variable */ | 98304 /* Accessor */)) {
49535                             return ts.setTextRange(createProperty(
49536                             /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, isPrivate ? undefined : serializeTypeForDeclaration(context, getTypeOfSymbol(p), p, enclosingDeclaration, includePrivateSymbol, bundled), 
49537                             // TODO: https://github.com/microsoft/TypeScript/pull/32372#discussion_r328386357
49538                             // interface members can't have initializers, however class members _can_
49539                             /*initializer*/ undefined), ts.find(p.declarations, ts.or(ts.isPropertyDeclaration, ts.isVariableDeclaration)) || firstPropertyLikeDecl);
49540                         }
49541                         if (p.flags & (8192 /* Method */ | 16 /* Function */)) {
49542                             var type = getTypeOfSymbol(p);
49543                             var signatures = getSignaturesOfType(type, 0 /* Call */);
49544                             if (flag & 8 /* Private */) {
49545                                 return ts.setTextRange(createProperty(
49546                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags((isReadonlySymbol(p) ? 64 /* Readonly */ : 0) | flag), name, p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined, 
49547                                 /*type*/ undefined, 
49548                                 /*initializer*/ undefined), ts.find(p.declarations, ts.isFunctionLikeDeclaration) || signatures[0] && signatures[0].declaration || p.declarations[0]);
49549                             }
49550                             var results_1 = [];
49551                             for (var _i = 0, signatures_3 = signatures; _i < signatures_3.length; _i++) {
49552                                 var sig = signatures_3[_i];
49553                                 // Each overload becomes a separate method declaration, in order
49554                                 var decl = signatureToSignatureDeclarationHelper(sig, methodKind, context, {
49555                                     name: name,
49556                                     questionToken: p.flags & 16777216 /* Optional */ ? ts.factory.createToken(57 /* QuestionToken */) : undefined,
49557                                     modifiers: flag ? ts.factory.createModifiersFromModifierFlags(flag) : undefined
49558                                 });
49559                                 results_1.push(ts.setTextRange(decl, sig.declaration));
49560                             }
49561                             return results_1;
49562                         }
49563                         // The `Constructor`'s symbol isn't in the class's properties lists, obviously, since it's a signature on the static
49564                         return ts.Debug.fail("Unhandled class member kind! " + (p.__debugFlags || p.flags));
49565                     };
49566                 }
49567                 function serializePropertySymbolForInterface(p, baseType) {
49568                     return serializePropertySymbolForInterfaceWorker(p, /*isStatic*/ false, baseType);
49569                 }
49570                 function serializeSignatures(kind, input, baseType, outputKind) {
49571                     var signatures = getSignaturesOfType(input, kind);
49572                     if (kind === 1 /* Construct */) {
49573                         if (!baseType && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
49574                             return []; // No base type, every constructor is empty - elide the extraneous `constructor()`
49575                         }
49576                         if (baseType) {
49577                             // If there is a base type, if every signature in the class is identical to a signature in the baseType, elide all the declarations
49578                             var baseSigs = getSignaturesOfType(baseType, 1 /* Construct */);
49579                             if (!ts.length(baseSigs) && ts.every(signatures, function (s) { return ts.length(s.parameters) === 0; })) {
49580                                 return []; // Base had no explicit signatures, if all our signatures are also implicit, return an empty list
49581                             }
49582                             if (baseSigs.length === signatures.length) {
49583                                 var failed = false;
49584                                 for (var i = 0; i < baseSigs.length; i++) {
49585                                     if (!compareSignaturesIdentical(signatures[i], baseSigs[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
49586                                         failed = true;
49587                                         break;
49588                                     }
49589                                 }
49590                                 if (!failed) {
49591                                     return []; // Every signature was identical - elide constructor list as it is inherited
49592                                 }
49593                             }
49594                         }
49595                         var privateProtected = 0;
49596                         for (var _i = 0, signatures_4 = signatures; _i < signatures_4.length; _i++) {
49597                             var s = signatures_4[_i];
49598                             if (s.declaration) {
49599                                 privateProtected |= ts.getSelectedEffectiveModifierFlags(s.declaration, 8 /* Private */ | 16 /* Protected */);
49600                             }
49601                         }
49602                         if (privateProtected) {
49603                             return [ts.setTextRange(ts.factory.createConstructorDeclaration(
49604                                 /*decorators*/ undefined, ts.factory.createModifiersFromModifierFlags(privateProtected), 
49605                                 /*parameters*/ [], 
49606                                 /*body*/ undefined), signatures[0].declaration)];
49607                         }
49608                     }
49609                     var results = [];
49610                     for (var _a = 0, signatures_5 = signatures; _a < signatures_5.length; _a++) {
49611                         var sig = signatures_5[_a];
49612                         // Each overload becomes a separate constructor declaration, in order
49613                         var decl = signatureToSignatureDeclarationHelper(sig, outputKind, context);
49614                         results.push(ts.setTextRange(decl, sig.declaration));
49615                     }
49616                     return results;
49617                 }
49618                 function serializeIndexSignatures(input, baseType) {
49619                     var results = [];
49620                     for (var _i = 0, _a = [0 /* String */, 1 /* Number */]; _i < _a.length; _i++) {
49621                         var type = _a[_i];
49622                         var info = getIndexInfoOfType(input, type);
49623                         if (info) {
49624                             if (baseType) {
49625                                 var baseInfo = getIndexInfoOfType(baseType, type);
49626                                 if (baseInfo) {
49627                                     if (isTypeIdenticalTo(info.type, baseInfo.type)) {
49628                                         continue; // elide identical index signatures
49629                                     }
49630                                 }
49631                             }
49632                             results.push(indexInfoToIndexSignatureDeclarationHelper(info, type, context, /*typeNode*/ undefined));
49633                         }
49634                     }
49635                     return results;
49636                 }
49637                 function serializeBaseType(t, staticType, rootName) {
49638                     var ref = trySerializeAsTypeReference(t, 111551 /* Value */);
49639                     if (ref) {
49640                         return ref;
49641                     }
49642                     var tempName = getUnusedName(rootName + "_base");
49643                     var statement = ts.factory.createVariableStatement(/*modifiers*/ undefined, ts.factory.createVariableDeclarationList([
49644                         ts.factory.createVariableDeclaration(tempName, /*exclamationToken*/ undefined, typeToTypeNodeHelper(staticType, context))
49645                     ], 2 /* Const */));
49646                     addResult(statement, 0 /* None */);
49647                     return ts.factory.createExpressionWithTypeArguments(ts.factory.createIdentifier(tempName), /*typeArgs*/ undefined);
49648                 }
49649                 function trySerializeAsTypeReference(t, flags) {
49650                     var typeArgs;
49651                     var reference;
49652                     // We don't use `isValueSymbolAccessible` below. since that considers alternative containers (like modules)
49653                     // which we can't write out in a syntactically valid way as an expression
49654                     if (t.target && isSymbolAccessibleByFlags(t.target.symbol, enclosingDeclaration, flags)) {
49655                         typeArgs = ts.map(getTypeArguments(t), function (t) { return typeToTypeNodeHelper(t, context); });
49656                         reference = symbolToExpression(t.target.symbol, context, 788968 /* Type */);
49657                     }
49658                     else if (t.symbol && isSymbolAccessibleByFlags(t.symbol, enclosingDeclaration, flags)) {
49659                         reference = symbolToExpression(t.symbol, context, 788968 /* Type */);
49660                     }
49661                     if (reference) {
49662                         return ts.factory.createExpressionWithTypeArguments(reference, typeArgs);
49663                     }
49664                 }
49665                 function serializeImplementedType(t) {
49666                     var ref = trySerializeAsTypeReference(t, 788968 /* Type */);
49667                     if (ref) {
49668                         return ref;
49669                     }
49670                     if (t.symbol) {
49671                         return ts.factory.createExpressionWithTypeArguments(symbolToExpression(t.symbol, context, 788968 /* Type */), /*typeArgs*/ undefined);
49672                     }
49673                 }
49674                 function getUnusedName(input, symbol) {
49675                     var _a, _b;
49676                     var id = symbol ? getSymbolId(symbol) : undefined;
49677                     if (id) {
49678                         if (context.remappedSymbolNames.has(id)) {
49679                             return context.remappedSymbolNames.get(id);
49680                         }
49681                     }
49682                     if (symbol) {
49683                         input = getNameCandidateWorker(symbol, input);
49684                     }
49685                     var i = 0;
49686                     var original = input;
49687                     while ((_a = context.usedSymbolNames) === null || _a === void 0 ? void 0 : _a.has(input)) {
49688                         i++;
49689                         input = original + "_" + i;
49690                     }
49691                     (_b = context.usedSymbolNames) === null || _b === void 0 ? void 0 : _b.add(input);
49692                     if (id) {
49693                         context.remappedSymbolNames.set(id, input);
49694                     }
49695                     return input;
49696                 }
49697                 function getNameCandidateWorker(symbol, localName) {
49698                     if (localName === "default" /* Default */ || localName === "__class" /* Class */ || localName === "__function" /* Function */) {
49699                         var flags = context.flags;
49700                         context.flags |= 16777216 /* InInitialEntityName */;
49701                         var nameCandidate = getNameOfSymbolAsWritten(symbol, context);
49702                         context.flags = flags;
49703                         localName = nameCandidate.length > 0 && ts.isSingleOrDoubleQuote(nameCandidate.charCodeAt(0)) ? ts.stripQuotes(nameCandidate) : nameCandidate;
49704                     }
49705                     if (localName === "default" /* Default */) {
49706                         localName = "_default";
49707                     }
49708                     else if (localName === "export=" /* ExportEquals */) {
49709                         localName = "_exports";
49710                     }
49711                     localName = ts.isIdentifierText(localName, languageVersion) && !ts.isStringANonContextualKeyword(localName) ? localName : "_" + localName.replace(/[^a-zA-Z0-9]/g, "_");
49712                     return localName;
49713                 }
49714                 function getInternalSymbolName(symbol, localName) {
49715                     var id = getSymbolId(symbol);
49716                     if (context.remappedSymbolNames.has(id)) {
49717                         return context.remappedSymbolNames.get(id);
49718                     }
49719                     localName = getNameCandidateWorker(symbol, localName);
49720                     // The result of this is going to be used as the symbol's name - lock it in, so `getUnusedName` will also pick it up
49721                     context.remappedSymbolNames.set(id, localName);
49722                     return localName;
49723                 }
49724             }
49725         }
49726         function typePredicateToString(typePredicate, enclosingDeclaration, flags, writer) {
49727             if (flags === void 0) { flags = 16384 /* UseAliasDefinedOutsideCurrentScope */; }
49728             return writer ? typePredicateToStringWorker(writer).getText() : ts.usingSingleLineStringWriter(typePredicateToStringWorker);
49729             function typePredicateToStringWorker(writer) {
49730                 var predicate = ts.factory.createTypePredicateNode(typePredicate.kind === 2 /* AssertsThis */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.factory.createToken(127 /* AssertsKeyword */) : undefined, typePredicate.kind === 1 /* Identifier */ || typePredicate.kind === 3 /* AssertsIdentifier */ ? ts.factory.createIdentifier(typePredicate.parameterName) : ts.factory.createThisTypeNode(), typePredicate.type && nodeBuilder.typeToTypeNode(typePredicate.type, enclosingDeclaration, toNodeBuilderFlags(flags) | 70221824 /* IgnoreErrors */ | 512 /* WriteTypeParametersInQualifiedName */) // TODO: GH#18217
49731                 );
49732                 var printer = ts.createPrinter({ removeComments: true });
49733                 var sourceFile = enclosingDeclaration && ts.getSourceFileOfNode(enclosingDeclaration);
49734                 printer.writeNode(4 /* Unspecified */, predicate, /*sourceFile*/ sourceFile, writer);
49735                 return writer;
49736             }
49737         }
49738         function formatUnionTypes(types) {
49739             var result = [];
49740             var flags = 0;
49741             for (var i = 0; i < types.length; i++) {
49742                 var t = types[i];
49743                 flags |= t.flags;
49744                 if (!(t.flags & 98304 /* Nullable */)) {
49745                     if (t.flags & (512 /* BooleanLiteral */ | 1024 /* EnumLiteral */)) {
49746                         var baseType = t.flags & 512 /* BooleanLiteral */ ? booleanType : getBaseTypeOfEnumLiteralType(t);
49747                         if (baseType.flags & 1048576 /* Union */) {
49748                             var count = baseType.types.length;
49749                             if (i + count <= types.length && getRegularTypeOfLiteralType(types[i + count - 1]) === getRegularTypeOfLiteralType(baseType.types[count - 1])) {
49750                                 result.push(baseType);
49751                                 i += count - 1;
49752                                 continue;
49753                             }
49754                         }
49755                     }
49756                     result.push(t);
49757                 }
49758             }
49759             if (flags & 65536 /* Null */)
49760                 result.push(nullType);
49761             if (flags & 32768 /* Undefined */)
49762                 result.push(undefinedType);
49763             return result || types;
49764         }
49765         function visibilityToString(flags) {
49766             if (flags === 8 /* Private */) {
49767                 return "private";
49768             }
49769             if (flags === 16 /* Protected */) {
49770                 return "protected";
49771             }
49772             return "public";
49773         }
49774         function getTypeAliasForTypeLiteral(type) {
49775             if (type.symbol && type.symbol.flags & 2048 /* TypeLiteral */) {
49776                 var node = ts.walkUpParenthesizedTypes(type.symbol.declarations[0].parent);
49777                 if (node.kind === 254 /* TypeAliasDeclaration */) {
49778                     return getSymbolOfNode(node);
49779                 }
49780             }
49781             return undefined;
49782         }
49783         function isTopLevelInExternalModuleAugmentation(node) {
49784             return node && node.parent &&
49785                 node.parent.kind === 257 /* ModuleBlock */ &&
49786                 ts.isExternalModuleAugmentation(node.parent.parent);
49787         }
49788         function isDefaultBindingContext(location) {
49789             return location.kind === 297 /* SourceFile */ || ts.isAmbientModule(location);
49790         }
49791         function getNameOfSymbolFromNameType(symbol, context) {
49792             var nameType = getSymbolLinks(symbol).nameType;
49793             if (nameType) {
49794                 if (nameType.flags & 384 /* StringOrNumberLiteral */) {
49795                     var name = "" + nameType.value;
49796                     if (!ts.isIdentifierText(name, compilerOptions.target) && !isNumericLiteralName(name)) {
49797                         return "\"" + ts.escapeString(name, 34 /* doubleQuote */) + "\"";
49798                     }
49799                     if (isNumericLiteralName(name) && ts.startsWith(name, "-")) {
49800                         return "[" + name + "]";
49801                     }
49802                     return name;
49803                 }
49804                 if (nameType.flags & 8192 /* UniqueESSymbol */) {
49805                     return "[" + getNameOfSymbolAsWritten(nameType.symbol, context) + "]";
49806                 }
49807             }
49808         }
49809         /**
49810          * Gets a human-readable name for a symbol.
49811          * Should *not* be used for the right-hand side of a `.` -- use `symbolName(symbol)` for that instead.
49812          *
49813          * Unlike `symbolName(symbol)`, this will include quotes if the name is from a string literal.
49814          * It will also use a representation of a number as written instead of a decimal form, e.g. `0o11` instead of `9`.
49815          */
49816         function getNameOfSymbolAsWritten(symbol, context) {
49817             if (context && symbol.escapedName === "default" /* Default */ && !(context.flags & 16384 /* UseAliasDefinedOutsideCurrentScope */) &&
49818                 // If it's not the first part of an entity name, it must print as `default`
49819                 (!(context.flags & 16777216 /* InInitialEntityName */) ||
49820                     // if the symbol is synthesized, it will only be referenced externally it must print as `default`
49821                     !symbol.declarations ||
49822                     // if not in the same binding context (source file, module declaration), it must print as `default`
49823                     (context.enclosingDeclaration && ts.findAncestor(symbol.declarations[0], isDefaultBindingContext) !== ts.findAncestor(context.enclosingDeclaration, isDefaultBindingContext)))) {
49824                 return "default";
49825             }
49826             if (symbol.declarations && symbol.declarations.length) {
49827                 var declaration = ts.firstDefined(symbol.declarations, function (d) { return ts.getNameOfDeclaration(d) ? d : undefined; }); // Try using a declaration with a name, first
49828                 var name_3 = declaration && ts.getNameOfDeclaration(declaration);
49829                 if (declaration && name_3) {
49830                     if (ts.isCallExpression(declaration) && ts.isBindableObjectDefinePropertyCall(declaration)) {
49831                         return ts.symbolName(symbol);
49832                     }
49833                     if (ts.isComputedPropertyName(name_3) && !(ts.getCheckFlags(symbol) & 4096 /* Late */)) {
49834                         var nameType = getSymbolLinks(symbol).nameType;
49835                         if (nameType && nameType.flags & 384 /* StringOrNumberLiteral */) {
49836                             // Computed property name isn't late bound, but has a well-known name type - use name type to generate a symbol name
49837                             var result = getNameOfSymbolFromNameType(symbol, context);
49838                             if (result !== undefined) {
49839                                 return result;
49840                             }
49841                         }
49842                     }
49843                     return ts.declarationNameToString(name_3);
49844                 }
49845                 if (!declaration) {
49846                     declaration = symbol.declarations[0]; // Declaration may be nameless, but we'll try anyway
49847                 }
49848                 if (declaration.parent && declaration.parent.kind === 249 /* VariableDeclaration */) {
49849                     return ts.declarationNameToString(declaration.parent.name);
49850                 }
49851                 switch (declaration.kind) {
49852                     case 221 /* ClassExpression */:
49853                     case 208 /* FunctionExpression */:
49854                     case 209 /* ArrowFunction */:
49855                         if (context && !context.encounteredError && !(context.flags & 131072 /* AllowAnonymousIdentifier */)) {
49856                             context.encounteredError = true;
49857                         }
49858                         return declaration.kind === 221 /* ClassExpression */ ? "(Anonymous class)" : "(Anonymous function)";
49859                 }
49860             }
49861             var name = getNameOfSymbolFromNameType(symbol, context);
49862             return name !== undefined ? name : ts.symbolName(symbol);
49863         }
49864         function isDeclarationVisible(node) {
49865             if (node) {
49866                 var links = getNodeLinks(node);
49867                 if (links.isVisible === undefined) {
49868                     links.isVisible = !!determineIfDeclarationIsVisible();
49869                 }
49870                 return links.isVisible;
49871             }
49872             return false;
49873             function determineIfDeclarationIsVisible() {
49874                 switch (node.kind) {
49875                     case 324 /* JSDocCallbackTag */:
49876                     case 331 /* JSDocTypedefTag */:
49877                     case 325 /* JSDocEnumTag */:
49878                         // Top-level jsdoc type aliases are considered exported
49879                         // 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
49880                         return !!(node.parent && node.parent.parent && node.parent.parent.parent && ts.isSourceFile(node.parent.parent.parent));
49881                     case 198 /* BindingElement */:
49882                         return isDeclarationVisible(node.parent.parent);
49883                     case 249 /* VariableDeclaration */:
49884                         if (ts.isBindingPattern(node.name) &&
49885                             !node.name.elements.length) {
49886                             // If the binding pattern is empty, this variable declaration is not visible
49887                             return false;
49888                         }
49889                     // falls through
49890                     case 256 /* ModuleDeclaration */:
49891                     case 252 /* ClassDeclaration */:
49892                     case 253 /* InterfaceDeclaration */:
49893                     case 254 /* TypeAliasDeclaration */:
49894                     case 251 /* FunctionDeclaration */:
49895                     case 255 /* EnumDeclaration */:
49896                     case 260 /* ImportEqualsDeclaration */:
49897                         // external module augmentation is always visible
49898                         if (ts.isExternalModuleAugmentation(node)) {
49899                             return true;
49900                         }
49901                         var parent = getDeclarationContainer(node);
49902                         // If the node is not exported or it is not ambient module element (except import declaration)
49903                         if (!(ts.getCombinedModifierFlags(node) & 1 /* Export */) &&
49904                             !(node.kind !== 260 /* ImportEqualsDeclaration */ && parent.kind !== 297 /* SourceFile */ && parent.flags & 8388608 /* Ambient */)) {
49905                             return isGlobalSourceFile(parent);
49906                         }
49907                         // Exported members/ambient module elements (exception import declaration) are visible if parent is visible
49908                         return isDeclarationVisible(parent);
49909                     case 163 /* PropertyDeclaration */:
49910                     case 162 /* PropertySignature */:
49911                     case 167 /* GetAccessor */:
49912                     case 168 /* SetAccessor */:
49913                     case 165 /* MethodDeclaration */:
49914                     case 164 /* MethodSignature */:
49915                         if (ts.hasEffectiveModifier(node, 8 /* Private */ | 16 /* Protected */)) {
49916                             // Private/protected properties/methods are not visible
49917                             return false;
49918                         }
49919                     // Public properties/methods are visible if its parents are visible, so:
49920                     // falls through
49921                     case 166 /* Constructor */:
49922                     case 170 /* ConstructSignature */:
49923                     case 169 /* CallSignature */:
49924                     case 171 /* IndexSignature */:
49925                     case 160 /* Parameter */:
49926                     case 257 /* ModuleBlock */:
49927                     case 174 /* FunctionType */:
49928                     case 175 /* ConstructorType */:
49929                     case 177 /* TypeLiteral */:
49930                     case 173 /* TypeReference */:
49931                     case 178 /* ArrayType */:
49932                     case 179 /* TupleType */:
49933                     case 182 /* UnionType */:
49934                     case 183 /* IntersectionType */:
49935                     case 186 /* ParenthesizedType */:
49936                     case 192 /* NamedTupleMember */:
49937                         return isDeclarationVisible(node.parent);
49938                     // Default binding, import specifier and namespace import is visible
49939                     // only on demand so by default it is not visible
49940                     case 262 /* ImportClause */:
49941                     case 263 /* NamespaceImport */:
49942                     case 265 /* ImportSpecifier */:
49943                         return false;
49944                     // Type parameters are always visible
49945                     case 159 /* TypeParameter */:
49946                     // Source file and namespace export are always visible
49947                     // falls through
49948                     case 297 /* SourceFile */:
49949                     case 259 /* NamespaceExportDeclaration */:
49950                         return true;
49951                     // Export assignments do not create name bindings outside the module
49952                     case 266 /* ExportAssignment */:
49953                         return false;
49954                     default:
49955                         return false;
49956                 }
49957             }
49958         }
49959         function collectLinkedAliases(node, setVisibility) {
49960             var exportSymbol;
49961             if (node.parent && node.parent.kind === 266 /* ExportAssignment */) {
49962                 exportSymbol = resolveName(node, node.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*nameNotFoundMessage*/ undefined, node, /*isUse*/ false);
49963             }
49964             else if (node.parent.kind === 270 /* ExportSpecifier */) {
49965                 exportSymbol = getTargetOfExportSpecifier(node.parent, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
49966             }
49967             var result;
49968             var visited;
49969             if (exportSymbol) {
49970                 visited = new ts.Set();
49971                 visited.add(getSymbolId(exportSymbol));
49972                 buildVisibleNodeList(exportSymbol.declarations);
49973             }
49974             return result;
49975             function buildVisibleNodeList(declarations) {
49976                 ts.forEach(declarations, function (declaration) {
49977                     var resultNode = getAnyImportSyntax(declaration) || declaration;
49978                     if (setVisibility) {
49979                         getNodeLinks(declaration).isVisible = true;
49980                     }
49981                     else {
49982                         result = result || [];
49983                         ts.pushIfUnique(result, resultNode);
49984                     }
49985                     if (ts.isInternalModuleImportEqualsDeclaration(declaration)) {
49986                         // Add the referenced top container visible
49987                         var internalModuleReference = declaration.moduleReference;
49988                         var firstIdentifier = ts.getFirstIdentifier(internalModuleReference);
49989                         var importSymbol = resolveName(declaration, firstIdentifier.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */, undefined, undefined, /*isUse*/ false);
49990                         if (importSymbol && visited) {
49991                             if (ts.tryAddToSet(visited, getSymbolId(importSymbol))) {
49992                                 buildVisibleNodeList(importSymbol.declarations);
49993                             }
49994                         }
49995                     }
49996                 });
49997             }
49998         }
49999         /**
50000          * Push an entry on the type resolution stack. If an entry with the given target and the given property name
50001          * is already on the stack, and no entries in between already have a type, then a circularity has occurred.
50002          * In this case, the result values of the existing entry and all entries pushed after it are changed to false,
50003          * and the value false is returned. Otherwise, the new entry is just pushed onto the stack, and true is returned.
50004          * In order to see if the same query has already been done before, the target object and the propertyName both
50005          * must match the one passed in.
50006          *
50007          * @param target The symbol, type, or signature whose type is being queried
50008          * @param propertyName The property name that should be used to query the target for its type
50009          */
50010         function pushTypeResolution(target, propertyName) {
50011             var resolutionCycleStartIndex = findResolutionCycleStartIndex(target, propertyName);
50012             if (resolutionCycleStartIndex >= 0) {
50013                 // A cycle was found
50014                 var length_3 = resolutionTargets.length;
50015                 for (var i = resolutionCycleStartIndex; i < length_3; i++) {
50016                     resolutionResults[i] = false;
50017                 }
50018                 return false;
50019             }
50020             resolutionTargets.push(target);
50021             resolutionResults.push(/*items*/ true);
50022             resolutionPropertyNames.push(propertyName);
50023             return true;
50024         }
50025         function findResolutionCycleStartIndex(target, propertyName) {
50026             for (var i = resolutionTargets.length - 1; i >= 0; i--) {
50027                 if (hasType(resolutionTargets[i], resolutionPropertyNames[i])) {
50028                     return -1;
50029                 }
50030                 if (resolutionTargets[i] === target && resolutionPropertyNames[i] === propertyName) {
50031                     return i;
50032                 }
50033             }
50034             return -1;
50035         }
50036         function hasType(target, propertyName) {
50037             switch (propertyName) {
50038                 case 0 /* Type */:
50039                     return !!getSymbolLinks(target).type;
50040                 case 5 /* EnumTagType */:
50041                     return !!(getNodeLinks(target).resolvedEnumType);
50042                 case 2 /* DeclaredType */:
50043                     return !!getSymbolLinks(target).declaredType;
50044                 case 1 /* ResolvedBaseConstructorType */:
50045                     return !!target.resolvedBaseConstructorType;
50046                 case 3 /* ResolvedReturnType */:
50047                     return !!target.resolvedReturnType;
50048                 case 4 /* ImmediateBaseConstraint */:
50049                     return !!target.immediateBaseConstraint;
50050                 case 6 /* ResolvedTypeArguments */:
50051                     return !!target.resolvedTypeArguments;
50052                 case 7 /* ResolvedBaseTypes */:
50053                     return !!target.baseTypesResolved;
50054             }
50055             return ts.Debug.assertNever(propertyName);
50056         }
50057         /**
50058          * Pop an entry from the type resolution stack and return its associated result value. The result value will
50059          * be true if no circularities were detected, or false if a circularity was found.
50060          */
50061         function popTypeResolution() {
50062             resolutionTargets.pop();
50063             resolutionPropertyNames.pop();
50064             return resolutionResults.pop();
50065         }
50066         function getDeclarationContainer(node) {
50067             return ts.findAncestor(ts.getRootDeclaration(node), function (node) {
50068                 switch (node.kind) {
50069                     case 249 /* VariableDeclaration */:
50070                     case 250 /* VariableDeclarationList */:
50071                     case 265 /* ImportSpecifier */:
50072                     case 264 /* NamedImports */:
50073                     case 263 /* NamespaceImport */:
50074                     case 262 /* ImportClause */:
50075                         return false;
50076                     default:
50077                         return true;
50078                 }
50079             }).parent;
50080         }
50081         function getTypeOfPrototypeProperty(prototype) {
50082             // TypeScript 1.0 spec (April 2014): 8.4
50083             // Every class automatically contains a static property member named 'prototype',
50084             // the type of which is an instantiation of the class type with type Any supplied as a type argument for each type parameter.
50085             // It is an error to explicitly declare a static property member with the name 'prototype'.
50086             var classType = getDeclaredTypeOfSymbol(getParentOfSymbol(prototype));
50087             return classType.typeParameters ? createTypeReference(classType, ts.map(classType.typeParameters, function (_) { return anyType; })) : classType;
50088         }
50089         // Return the type of the given property in the given type, or undefined if no such property exists
50090         function getTypeOfPropertyOfType(type, name) {
50091             var prop = getPropertyOfType(type, name);
50092             return prop ? getTypeOfSymbol(prop) : undefined;
50093         }
50094         function getTypeOfPropertyOrIndexSignature(type, name) {
50095             return getTypeOfPropertyOfType(type, name) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || unknownType;
50096         }
50097         function isTypeAny(type) {
50098             return type && (type.flags & 1 /* Any */) !== 0;
50099         }
50100         // Return the type of a binding element parent. We check SymbolLinks first to see if a type has been
50101         // assigned by contextual typing.
50102         function getTypeForBindingElementParent(node) {
50103             var symbol = getSymbolOfNode(node);
50104             return symbol && getSymbolLinks(symbol).type || getTypeForVariableLikeDeclaration(node, /*includeOptionality*/ false);
50105         }
50106         function getRestType(source, properties, symbol) {
50107             source = filterType(source, function (t) { return !(t.flags & 98304 /* Nullable */); });
50108             if (source.flags & 131072 /* Never */) {
50109                 return emptyObjectType;
50110             }
50111             if (source.flags & 1048576 /* Union */) {
50112                 return mapType(source, function (t) { return getRestType(t, properties, symbol); });
50113             }
50114             var omitKeyType = getUnionType(ts.map(properties, getLiteralTypeFromPropertyName));
50115             if (isGenericObjectType(source) || isGenericIndexType(omitKeyType)) {
50116                 if (omitKeyType.flags & 131072 /* Never */) {
50117                     return source;
50118                 }
50119                 var omitTypeAlias = getGlobalOmitSymbol();
50120                 if (!omitTypeAlias) {
50121                     return errorType;
50122                 }
50123                 return getTypeAliasInstantiation(omitTypeAlias, [source, omitKeyType]);
50124             }
50125             var members = ts.createSymbolTable();
50126             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
50127                 var prop = _a[_i];
50128                 if (!isTypeAssignableTo(getLiteralTypeFromProperty(prop, 8576 /* StringOrNumberLiteralOrUnique */), omitKeyType)
50129                     && !(ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */))
50130                     && isSpreadableProperty(prop)) {
50131                     members.set(prop.escapedName, getSpreadSymbol(prop, /*readonly*/ false));
50132                 }
50133             }
50134             var stringIndexInfo = getIndexInfoOfType(source, 0 /* String */);
50135             var numberIndexInfo = getIndexInfoOfType(source, 1 /* Number */);
50136             var result = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
50137             result.objectFlags |= 131072 /* ObjectRestType */;
50138             return result;
50139         }
50140         // Determine the control flow type associated with a destructuring declaration or assignment. The following
50141         // forms of destructuring are possible:
50142         //   let { x } = obj;  // BindingElement
50143         //   let [ x ] = obj;  // BindingElement
50144         //   { x } = obj;      // ShorthandPropertyAssignment
50145         //   { x: v } = obj;   // PropertyAssignment
50146         //   [ x ] = obj;      // Expression
50147         // We construct a synthetic element access expression corresponding to 'obj.x' such that the control
50148         // flow analyzer doesn't have to handle all the different syntactic forms.
50149         function getFlowTypeOfDestructuring(node, declaredType) {
50150             var reference = getSyntheticElementAccess(node);
50151             return reference ? getFlowTypeOfReference(reference, declaredType) : declaredType;
50152         }
50153         function getSyntheticElementAccess(node) {
50154             var parentAccess = getParentElementAccess(node);
50155             if (parentAccess && parentAccess.flowNode) {
50156                 var propName = getDestructuringPropertyName(node);
50157                 if (propName) {
50158                     var literal = ts.setTextRange(ts.parseNodeFactory.createStringLiteral(propName), node);
50159                     var lhsExpr = ts.isLeftHandSideExpression(parentAccess) ? parentAccess : ts.parseNodeFactory.createParenthesizedExpression(parentAccess);
50160                     var result = ts.setTextRange(ts.parseNodeFactory.createElementAccessExpression(lhsExpr, literal), node);
50161                     ts.setParent(literal, result);
50162                     ts.setParent(result, node);
50163                     if (lhsExpr !== parentAccess) {
50164                         ts.setParent(lhsExpr, result);
50165                     }
50166                     result.flowNode = parentAccess.flowNode;
50167                     return result;
50168                 }
50169             }
50170         }
50171         function getParentElementAccess(node) {
50172             var ancestor = node.parent.parent;
50173             switch (ancestor.kind) {
50174                 case 198 /* BindingElement */:
50175                 case 288 /* PropertyAssignment */:
50176                     return getSyntheticElementAccess(ancestor);
50177                 case 199 /* ArrayLiteralExpression */:
50178                     return getSyntheticElementAccess(node.parent);
50179                 case 249 /* VariableDeclaration */:
50180                     return ancestor.initializer;
50181                 case 216 /* BinaryExpression */:
50182                     return ancestor.right;
50183             }
50184         }
50185         function getDestructuringPropertyName(node) {
50186             var parent = node.parent;
50187             if (node.kind === 198 /* BindingElement */ && parent.kind === 196 /* ObjectBindingPattern */) {
50188                 return getLiteralPropertyNameText(node.propertyName || node.name);
50189             }
50190             if (node.kind === 288 /* PropertyAssignment */ || node.kind === 289 /* ShorthandPropertyAssignment */) {
50191                 return getLiteralPropertyNameText(node.name);
50192             }
50193             return "" + parent.elements.indexOf(node);
50194         }
50195         function getLiteralPropertyNameText(name) {
50196             var type = getLiteralTypeFromPropertyName(name);
50197             return type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */) ? "" + type.value : undefined;
50198         }
50199         /** Return the inferred type for a binding element */
50200         function getTypeForBindingElement(declaration) {
50201             var pattern = declaration.parent;
50202             var parentType = getTypeForBindingElementParent(pattern.parent);
50203             // If no type or an any type was inferred for parent, infer that for the binding element
50204             if (!parentType || isTypeAny(parentType)) {
50205                 return parentType;
50206             }
50207             // Relax null check on ambient destructuring parameters, since the parameters have no implementation and are just documentation
50208             if (strictNullChecks && declaration.flags & 8388608 /* Ambient */ && ts.isParameterDeclaration(declaration)) {
50209                 parentType = getNonNullableType(parentType);
50210             }
50211             // Filter `undefined` from the type we check against if the parent has an initializer and that initializer is not possibly `undefined`
50212             else if (strictNullChecks && pattern.parent.initializer && !(getTypeFacts(getTypeOfInitializer(pattern.parent.initializer)) & 65536 /* EQUndefined */)) {
50213                 parentType = getTypeWithFacts(parentType, 524288 /* NEUndefined */);
50214             }
50215             var type;
50216             if (pattern.kind === 196 /* ObjectBindingPattern */) {
50217                 if (declaration.dotDotDotToken) {
50218                     parentType = getReducedType(parentType);
50219                     if (parentType.flags & 2 /* Unknown */ || !isValidSpreadType(parentType)) {
50220                         error(declaration, ts.Diagnostics.Rest_types_may_only_be_created_from_object_types);
50221                         return errorType;
50222                     }
50223                     var literalMembers = [];
50224                     for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
50225                         var element = _a[_i];
50226                         if (!element.dotDotDotToken) {
50227                             literalMembers.push(element.propertyName || element.name);
50228                         }
50229                     }
50230                     type = getRestType(parentType, literalMembers, declaration.symbol);
50231                 }
50232                 else {
50233                     // Use explicitly specified property name ({ p: xxx } form), or otherwise the implied name ({ p } form)
50234                     var name = declaration.propertyName || declaration.name;
50235                     var indexType = getLiteralTypeFromPropertyName(name);
50236                     var declaredType = getConstraintForLocation(getIndexedAccessType(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */), declaration.name);
50237                     type = getFlowTypeOfDestructuring(declaration, declaredType);
50238                 }
50239             }
50240             else {
50241                 // This elementType will be used if the specific property corresponding to this index is not
50242                 // present (aka the tuple element property). This call also checks that the parentType is in
50243                 // fact an iterable or array (depending on target language).
50244                 var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */ | (declaration.dotDotDotToken ? 0 : 128 /* PossiblyOutOfBounds */), parentType, undefinedType, pattern);
50245                 var index_2 = pattern.elements.indexOf(declaration);
50246                 if (declaration.dotDotDotToken) {
50247                     // If the parent is a tuple type, the rest element has a tuple type of the
50248                     // remaining tuple element types. Otherwise, the rest element has an array type with same
50249                     // element type as the parent type.
50250                     type = everyType(parentType, isTupleType) ?
50251                         mapType(parentType, function (t) { return sliceTupleType(t, index_2); }) :
50252                         createArrayType(elementType);
50253                 }
50254                 else if (isArrayLikeType(parentType)) {
50255                     var indexType = getLiteralType(index_2);
50256                     var accessFlags = hasDefaultValue(declaration) ? 8 /* NoTupleBoundsCheck */ : 0;
50257                     var declaredType = getConstraintForLocation(getIndexedAccessTypeOrUndefined(parentType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, declaration.name, accessFlags | 16 /* ExpressionPosition */) || errorType, declaration.name);
50258                     type = getFlowTypeOfDestructuring(declaration, declaredType);
50259                 }
50260                 else {
50261                     type = elementType;
50262                 }
50263             }
50264             if (!declaration.initializer) {
50265                 return type;
50266             }
50267             if (ts.getEffectiveTypeAnnotationNode(ts.walkUpBindingElementsAndPatterns(declaration))) {
50268                 // In strict null checking mode, if a default value of a non-undefined type is specified, remove
50269                 // undefined from the final type.
50270                 return strictNullChecks && !(getFalsyFlags(checkDeclarationInitializer(declaration)) & 32768 /* Undefined */) ?
50271                     getTypeWithFacts(type, 524288 /* NEUndefined */) :
50272                     type;
50273             }
50274             return widenTypeInferredFromInitializer(declaration, getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), checkDeclarationInitializer(declaration)], 2 /* Subtype */));
50275         }
50276         function getTypeForDeclarationFromJSDocComment(declaration) {
50277             var jsdocType = ts.getJSDocType(declaration);
50278             if (jsdocType) {
50279                 return getTypeFromTypeNode(jsdocType);
50280             }
50281             return undefined;
50282         }
50283         function isNullOrUndefined(node) {
50284             var expr = ts.skipParentheses(node);
50285             return expr.kind === 103 /* NullKeyword */ || expr.kind === 78 /* Identifier */ && getResolvedSymbol(expr) === undefinedSymbol;
50286         }
50287         function isEmptyArrayLiteral(node) {
50288             var expr = ts.skipParentheses(node);
50289             return expr.kind === 199 /* ArrayLiteralExpression */ && expr.elements.length === 0;
50290         }
50291         function addOptionality(type, optional) {
50292             if (optional === void 0) { optional = true; }
50293             return strictNullChecks && optional ? getOptionalType(type) : type;
50294         }
50295         // Return the inferred type for a variable, parameter, or property declaration
50296         function getTypeForVariableLikeDeclaration(declaration, includeOptionality) {
50297             // A variable declared in a for..in statement is of type string, or of type keyof T when the
50298             // right hand expression is of a type parameter type.
50299             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 238 /* ForInStatement */) {
50300                 var indexType = getIndexType(getNonNullableTypeIfNeeded(checkExpression(declaration.parent.parent.expression)));
50301                 return indexType.flags & (262144 /* TypeParameter */ | 4194304 /* Index */) ? getExtractStringType(indexType) : stringType;
50302             }
50303             if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) {
50304                 // checkRightHandSideOfForOf will return undefined if the for-of expression type was
50305                 // missing properties/signatures required to get its iteratedType (like
50306                 // [Symbol.iterator] or next). This may be because we accessed properties from anyType,
50307                 // or it may have led to an error inside getElementTypeOfIterable.
50308                 var forOfStatement = declaration.parent.parent;
50309                 return checkRightHandSideOfForOf(forOfStatement) || anyType;
50310             }
50311             if (ts.isBindingPattern(declaration.parent)) {
50312                 return getTypeForBindingElement(declaration);
50313             }
50314             var isOptional = includeOptionality && (ts.isParameter(declaration) && isJSDocOptionalParameter(declaration)
50315                 || isOptionalJSDocPropertyLikeTag(declaration)
50316                 || !ts.isBindingElement(declaration) && !ts.isVariableDeclaration(declaration) && !!declaration.questionToken);
50317             // Use type from type annotation if one is present
50318             var declaredType = tryGetTypeFromEffectiveTypeNode(declaration);
50319             if (declaredType) {
50320                 return addOptionality(declaredType, isOptional);
50321             }
50322             if ((noImplicitAny || ts.isInJSFile(declaration)) &&
50323                 ts.isVariableDeclaration(declaration) && !ts.isBindingPattern(declaration.name) &&
50324                 !(ts.getCombinedModifierFlags(declaration) & 1 /* Export */) && !(declaration.flags & 8388608 /* Ambient */)) {
50325                 // If --noImplicitAny is on or the declaration is in a Javascript file,
50326                 // use control flow tracked 'any' type for non-ambient, non-exported var or let variables with no
50327                 // initializer or a 'null' or 'undefined' initializer.
50328                 if (!(ts.getCombinedNodeFlags(declaration) & 2 /* Const */) && (!declaration.initializer || isNullOrUndefined(declaration.initializer))) {
50329                     return autoType;
50330                 }
50331                 // Use control flow tracked 'any[]' type for non-ambient, non-exported variables with an empty array
50332                 // literal initializer.
50333                 if (declaration.initializer && isEmptyArrayLiteral(declaration.initializer)) {
50334                     return autoArrayType;
50335                 }
50336             }
50337             if (ts.isParameter(declaration)) {
50338                 var func = declaration.parent;
50339                 // For a parameter of a set accessor, use the type of the get accessor if one is present
50340                 if (func.kind === 168 /* SetAccessor */ && !hasNonBindableDynamicName(func)) {
50341                     var getter = ts.getDeclarationOfKind(getSymbolOfNode(declaration.parent), 167 /* GetAccessor */);
50342                     if (getter) {
50343                         var getterSignature = getSignatureFromDeclaration(getter);
50344                         var thisParameter = getAccessorThisParameter(func);
50345                         if (thisParameter && declaration === thisParameter) {
50346                             // Use the type from the *getter*
50347                             ts.Debug.assert(!thisParameter.type);
50348                             return getTypeOfSymbol(getterSignature.thisParameter);
50349                         }
50350                         return getReturnTypeOfSignature(getterSignature);
50351                     }
50352                 }
50353                 if (ts.isInJSFile(declaration)) {
50354                     var typeTag = ts.getJSDocType(func);
50355                     if (typeTag && ts.isFunctionTypeNode(typeTag)) {
50356                         var signature = getSignatureFromDeclaration(typeTag);
50357                         var pos = func.parameters.indexOf(declaration);
50358                         return declaration.dotDotDotToken ? getRestTypeAtPosition(signature, pos) : getTypeAtPosition(signature, pos);
50359                     }
50360                 }
50361                 // Use contextual parameter type if one is available
50362                 var type = declaration.symbol.escapedName === "this" /* This */ ? getContextualThisParameterType(func) : getContextuallyTypedParameterType(declaration);
50363                 if (type) {
50364                     return addOptionality(type, isOptional);
50365                 }
50366             }
50367             // Use the type of the initializer expression if one is present and the declaration is
50368             // not a parameter of a contextually typed function
50369             if (ts.hasOnlyExpressionInitializer(declaration) && !!declaration.initializer) {
50370                 if (ts.isInJSFile(declaration) && !ts.isParameter(declaration)) {
50371                     var containerObjectType = getJSContainerObjectType(declaration, getSymbolOfNode(declaration), ts.getDeclaredExpandoInitializer(declaration));
50372                     if (containerObjectType) {
50373                         return containerObjectType;
50374                     }
50375                 }
50376                 var type = widenTypeInferredFromInitializer(declaration, checkDeclarationInitializer(declaration));
50377                 return addOptionality(type, isOptional);
50378             }
50379             if (ts.isPropertyDeclaration(declaration) && !ts.hasStaticModifier(declaration) && (noImplicitAny || ts.isInJSFile(declaration))) {
50380                 // We have a property declaration with no type annotation or initializer, in noImplicitAny mode or a .js file.
50381                 // Use control flow analysis of this.xxx assignments in the constructor to determine the type of the property.
50382                 var constructor = findConstructorDeclaration(declaration.parent);
50383                 var type = constructor ? getFlowTypeInConstructor(declaration.symbol, constructor) :
50384                     ts.getEffectiveModifierFlags(declaration) & 2 /* Ambient */ ? getTypeOfPropertyInBaseClass(declaration.symbol) :
50385                         undefined;
50386                 return type && addOptionality(type, isOptional);
50387             }
50388             if (ts.isJsxAttribute(declaration)) {
50389                 // if JSX attribute doesn't have initializer, by default the attribute will have boolean value of true.
50390                 // I.e <Elem attr /> is sugar for <Elem attr={true} />
50391                 return trueType;
50392             }
50393             // If the declaration specifies a binding pattern and is not a parameter of a contextually
50394             // typed function, use the type implied by the binding pattern
50395             if (ts.isBindingPattern(declaration.name)) {
50396                 return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ false, /*reportErrors*/ true);
50397             }
50398             // No type specified and nothing can be inferred
50399             return undefined;
50400         }
50401         function isConstructorDeclaredProperty(symbol) {
50402             // A property is considered a constructor declared property when all declaration sites are this.xxx assignments,
50403             // when no declaration sites have JSDoc type annotations, and when at least one declaration site is in the body of
50404             // a class constructor.
50405             if (symbol.valueDeclaration && ts.isBinaryExpression(symbol.valueDeclaration)) {
50406                 var links = getSymbolLinks(symbol);
50407                 if (links.isConstructorDeclaredProperty === undefined) {
50408                     links.isConstructorDeclaredProperty = false;
50409                     links.isConstructorDeclaredProperty = !!getDeclaringConstructor(symbol) && ts.every(symbol.declarations, function (declaration) {
50410                         return ts.isBinaryExpression(declaration) &&
50411                             isPossiblyAliasedThisProperty(declaration) &&
50412                             (declaration.left.kind !== 202 /* ElementAccessExpression */ || ts.isStringOrNumericLiteralLike(declaration.left.argumentExpression)) &&
50413                             !getAnnotatedTypeForAssignmentDeclaration(/*declaredType*/ undefined, declaration, symbol, declaration);
50414                     });
50415                 }
50416                 return links.isConstructorDeclaredProperty;
50417             }
50418             return false;
50419         }
50420         function isAutoTypedProperty(symbol) {
50421             // A property is auto-typed when its declaration has no type annotation or initializer and we're in
50422             // noImplicitAny mode or a .js file.
50423             var declaration = symbol.valueDeclaration;
50424             return declaration && ts.isPropertyDeclaration(declaration) && !ts.getEffectiveTypeAnnotationNode(declaration) &&
50425                 !declaration.initializer && (noImplicitAny || ts.isInJSFile(declaration));
50426         }
50427         function getDeclaringConstructor(symbol) {
50428             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50429                 var declaration = _a[_i];
50430                 var container = ts.getThisContainer(declaration, /*includeArrowFunctions*/ false);
50431                 if (container && (container.kind === 166 /* Constructor */ || isJSConstructor(container))) {
50432                     return container;
50433                 }
50434             }
50435         }
50436         function getFlowTypeInConstructor(symbol, constructor) {
50437             var accessName = ts.startsWith(symbol.escapedName, "__#")
50438                 ? ts.factory.createPrivateIdentifier(symbol.escapedName.split("@")[1])
50439                 : ts.unescapeLeadingUnderscores(symbol.escapedName);
50440             var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), accessName);
50441             ts.setParent(reference.expression, reference);
50442             ts.setParent(reference, constructor);
50443             reference.flowNode = constructor.returnFlowNode;
50444             var flowType = getFlowTypeOfProperty(reference, symbol);
50445             if (noImplicitAny && (flowType === autoType || flowType === autoArrayType)) {
50446                 error(symbol.valueDeclaration, ts.Diagnostics.Member_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
50447             }
50448             // We don't infer a type if assignments are only null or undefined.
50449             return everyType(flowType, isNullableType) ? undefined : convertAutoToAny(flowType);
50450         }
50451         function getFlowTypeOfProperty(reference, prop) {
50452             var initialType = prop && (!isAutoTypedProperty(prop) || ts.getEffectiveModifierFlags(prop.valueDeclaration) & 2 /* Ambient */) && getTypeOfPropertyInBaseClass(prop) || undefinedType;
50453             return getFlowTypeOfReference(reference, autoType, initialType);
50454         }
50455         function getWidenedTypeForAssignmentDeclaration(symbol, resolvedSymbol) {
50456             // function/class/{} initializers are themselves containers, so they won't merge in the same way as other initializers
50457             var container = ts.getAssignedExpandoInitializer(symbol.valueDeclaration);
50458             if (container) {
50459                 var tag = ts.getJSDocTypeTag(container);
50460                 if (tag && tag.typeExpression) {
50461                     return getTypeFromTypeNode(tag.typeExpression);
50462                 }
50463                 var containerObjectType = getJSContainerObjectType(symbol.valueDeclaration, symbol, container);
50464                 return containerObjectType || getWidenedLiteralType(checkExpressionCached(container));
50465             }
50466             var type;
50467             var definedInConstructor = false;
50468             var definedInMethod = false;
50469             // We use control flow analysis to determine the type of the property if the property qualifies as a constructor
50470             // declared property and the resulting control flow type isn't just undefined or null.
50471             if (isConstructorDeclaredProperty(symbol)) {
50472                 type = getFlowTypeInConstructor(symbol, getDeclaringConstructor(symbol));
50473             }
50474             if (!type) {
50475                 var jsdocType = void 0;
50476                 var types = void 0;
50477                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
50478                     var declaration = _a[_i];
50479                     var expression = (ts.isBinaryExpression(declaration) || ts.isCallExpression(declaration)) ? declaration :
50480                         ts.isAccessExpression(declaration) ? ts.isBinaryExpression(declaration.parent) ? declaration.parent : declaration :
50481                             undefined;
50482                     if (!expression) {
50483                         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
50484                     }
50485                     var kind = ts.isAccessExpression(expression)
50486                         ? ts.getAssignmentDeclarationPropertyAccessKind(expression)
50487                         : ts.getAssignmentDeclarationKind(expression);
50488                     if (kind === 4 /* ThisProperty */ || ts.isBinaryExpression(expression) && isPossiblyAliasedThisProperty(expression, kind)) {
50489                         if (isDeclarationInConstructor(expression)) {
50490                             definedInConstructor = true;
50491                         }
50492                         else {
50493                             definedInMethod = true;
50494                         }
50495                     }
50496                     if (!ts.isCallExpression(expression)) {
50497                         jsdocType = getAnnotatedTypeForAssignmentDeclaration(jsdocType, expression, symbol, declaration);
50498                     }
50499                     if (!jsdocType) {
50500                         (types || (types = [])).push((ts.isBinaryExpression(expression) || ts.isCallExpression(expression)) ? getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) : neverType);
50501                     }
50502                 }
50503                 type = jsdocType;
50504                 if (!type) {
50505                     if (!ts.length(types)) {
50506                         return errorType; // No types from any declarations :(
50507                     }
50508                     var constructorTypes = definedInConstructor ? getConstructorDefinedThisAssignmentTypes(types, symbol.declarations) : undefined;
50509                     // use only the constructor types unless they were only assigned null | undefined (including widening variants)
50510                     if (definedInMethod) {
50511                         var propType = getTypeOfPropertyInBaseClass(symbol);
50512                         if (propType) {
50513                             (constructorTypes || (constructorTypes = [])).push(propType);
50514                             definedInConstructor = true;
50515                         }
50516                     }
50517                     var sourceTypes = ts.some(constructorTypes, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) ? constructorTypes : types; // TODO: GH#18217
50518                     type = getUnionType(sourceTypes, 2 /* Subtype */);
50519                 }
50520             }
50521             var widened = getWidenedType(addOptionality(type, definedInMethod && !definedInConstructor));
50522             if (filterType(widened, function (t) { return !!(t.flags & ~98304 /* Nullable */); }) === neverType) {
50523                 reportImplicitAny(symbol.valueDeclaration, anyType);
50524                 return anyType;
50525             }
50526             return widened;
50527         }
50528         function getJSContainerObjectType(decl, symbol, init) {
50529             var _a, _b;
50530             if (!ts.isInJSFile(decl) || !init || !ts.isObjectLiteralExpression(init) || init.properties.length) {
50531                 return undefined;
50532             }
50533             var exports = ts.createSymbolTable();
50534             while (ts.isBinaryExpression(decl) || ts.isPropertyAccessExpression(decl)) {
50535                 var s_2 = getSymbolOfNode(decl);
50536                 if ((_a = s_2 === null || s_2 === void 0 ? void 0 : s_2.exports) === null || _a === void 0 ? void 0 : _a.size) {
50537                     mergeSymbolTable(exports, s_2.exports);
50538                 }
50539                 decl = ts.isBinaryExpression(decl) ? decl.parent : decl.parent.parent;
50540             }
50541             var s = getSymbolOfNode(decl);
50542             if ((_b = s === null || s === void 0 ? void 0 : s.exports) === null || _b === void 0 ? void 0 : _b.size) {
50543                 mergeSymbolTable(exports, s.exports);
50544             }
50545             var type = createAnonymousType(symbol, exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
50546             type.objectFlags |= 16384 /* JSLiteral */;
50547             return type;
50548         }
50549         function getAnnotatedTypeForAssignmentDeclaration(declaredType, expression, symbol, declaration) {
50550             var typeNode = ts.getEffectiveTypeAnnotationNode(expression.parent);
50551             if (typeNode) {
50552                 var type = getWidenedType(getTypeFromTypeNode(typeNode));
50553                 if (!declaredType) {
50554                     return type;
50555                 }
50556                 else if (declaredType !== errorType && type !== errorType && !isTypeIdenticalTo(declaredType, type)) {
50557                     errorNextVariableOrPropertyDeclarationMustHaveSameType(/*firstDeclaration*/ undefined, declaredType, declaration, type);
50558                 }
50559             }
50560             if (symbol.parent) {
50561                 var typeNode_2 = ts.getEffectiveTypeAnnotationNode(symbol.parent.valueDeclaration);
50562                 if (typeNode_2) {
50563                     return getTypeOfPropertyOfType(getTypeFromTypeNode(typeNode_2), symbol.escapedName);
50564                 }
50565             }
50566             return declaredType;
50567         }
50568         /** If we don't have an explicit JSDoc type, get the type from the initializer. */
50569         function getInitializerTypeFromAssignmentDeclaration(symbol, resolvedSymbol, expression, kind) {
50570             if (ts.isCallExpression(expression)) {
50571                 if (resolvedSymbol) {
50572                     return getTypeOfSymbol(resolvedSymbol); // This shouldn't happen except under some hopefully forbidden merges of export assignments and object define assignments
50573                 }
50574                 var objectLitType = checkExpressionCached(expression.arguments[2]);
50575                 var valueType = getTypeOfPropertyOfType(objectLitType, "value");
50576                 if (valueType) {
50577                     return valueType;
50578                 }
50579                 var getFunc = getTypeOfPropertyOfType(objectLitType, "get");
50580                 if (getFunc) {
50581                     var getSig = getSingleCallSignature(getFunc);
50582                     if (getSig) {
50583                         return getReturnTypeOfSignature(getSig);
50584                     }
50585                 }
50586                 var setFunc = getTypeOfPropertyOfType(objectLitType, "set");
50587                 if (setFunc) {
50588                     var setSig = getSingleCallSignature(setFunc);
50589                     if (setSig) {
50590                         return getTypeOfFirstParameterOfSignature(setSig);
50591                     }
50592                 }
50593                 return anyType;
50594             }
50595             if (containsSameNamedThisProperty(expression.left, expression.right)) {
50596                 return anyType;
50597             }
50598             var type = resolvedSymbol ? getTypeOfSymbol(resolvedSymbol) : getWidenedLiteralType(checkExpressionCached(expression.right));
50599             if (type.flags & 524288 /* Object */ &&
50600                 kind === 2 /* ModuleExports */ &&
50601                 symbol.escapedName === "export=" /* ExportEquals */) {
50602                 var exportedType = resolveStructuredTypeMembers(type);
50603                 var members_4 = ts.createSymbolTable();
50604                 ts.copyEntries(exportedType.members, members_4);
50605                 var initialSize = members_4.size;
50606                 if (resolvedSymbol && !resolvedSymbol.exports) {
50607                     resolvedSymbol.exports = ts.createSymbolTable();
50608                 }
50609                 (resolvedSymbol || symbol).exports.forEach(function (s, name) {
50610                     var _a;
50611                     var exportedMember = members_4.get(name);
50612                     if (exportedMember && exportedMember !== s) {
50613                         if (s.flags & 111551 /* Value */ && exportedMember.flags & 111551 /* Value */) {
50614                             // If the member has an additional value-like declaration, union the types from the two declarations,
50615                             // but issue an error if they occurred in two different files. The purpose is to support a JS file with
50616                             // a pattern like:
50617                             //
50618                             // module.exports = { a: true };
50619                             // module.exports.a = 3;
50620                             //
50621                             // but we may have a JS file with `module.exports = { a: true }` along with a TypeScript module augmentation
50622                             // declaring an `export const a: number`. In that case, we issue a duplicate identifier error, because
50623                             // it's unclear what that's supposed to mean, so it's probably a mistake.
50624                             if (ts.getSourceFileOfNode(s.valueDeclaration) !== ts.getSourceFileOfNode(exportedMember.valueDeclaration)) {
50625                                 var unescapedName = ts.unescapeLeadingUnderscores(s.escapedName);
50626                                 var exportedMemberName = ((_a = ts.tryCast(exportedMember.valueDeclaration, ts.isNamedDeclaration)) === null || _a === void 0 ? void 0 : _a.name) || exportedMember.valueDeclaration;
50627                                 ts.addRelatedInfo(error(s.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(exportedMemberName, ts.Diagnostics._0_was_also_declared_here, unescapedName));
50628                                 ts.addRelatedInfo(error(exportedMemberName, ts.Diagnostics.Duplicate_identifier_0, unescapedName), ts.createDiagnosticForNode(s.valueDeclaration, ts.Diagnostics._0_was_also_declared_here, unescapedName));
50629                             }
50630                             var union = createSymbol(s.flags | exportedMember.flags, name);
50631                             union.type = getUnionType([getTypeOfSymbol(s), getTypeOfSymbol(exportedMember)]);
50632                             union.valueDeclaration = exportedMember.valueDeclaration;
50633                             union.declarations = ts.concatenate(exportedMember.declarations, s.declarations);
50634                             members_4.set(name, union);
50635                         }
50636                         else {
50637                             members_4.set(name, mergeSymbol(s, exportedMember));
50638                         }
50639                     }
50640                     else {
50641                         members_4.set(name, s);
50642                     }
50643                 });
50644                 var result = createAnonymousType(initialSize !== members_4.size ? undefined : exportedType.symbol, // Only set the type's symbol if it looks to be the same as the original type
50645                 members_4, exportedType.callSignatures, exportedType.constructSignatures, exportedType.stringIndexInfo, exportedType.numberIndexInfo);
50646                 result.objectFlags |= (ts.getObjectFlags(type) & 16384 /* JSLiteral */); // Propagate JSLiteral flag
50647                 if (result.symbol && result.symbol.flags & 32 /* Class */ && type === getDeclaredTypeOfClassOrInterface(result.symbol)) {
50648                     result.objectFlags |= 1073741824 /* IsClassInstanceClone */; // Propagate the knowledge that this type is equivalent to the symbol's class instance type
50649                 }
50650                 return result;
50651             }
50652             if (isEmptyArrayLiteralType(type)) {
50653                 reportImplicitAny(expression, anyArrayType);
50654                 return anyArrayType;
50655             }
50656             return type;
50657         }
50658         function containsSameNamedThisProperty(thisProperty, expression) {
50659             return ts.isPropertyAccessExpression(thisProperty)
50660                 && thisProperty.expression.kind === 107 /* ThisKeyword */
50661                 && ts.forEachChildRecursively(expression, function (n) { return isMatchingReference(thisProperty, n); });
50662         }
50663         function isDeclarationInConstructor(expression) {
50664             var thisContainer = ts.getThisContainer(expression, /*includeArrowFunctions*/ false);
50665             // Properties defined in a constructor (or base constructor, or javascript constructor function) don't get undefined added.
50666             // Function expressions that are assigned to the prototype count as methods.
50667             return thisContainer.kind === 166 /* Constructor */ ||
50668                 thisContainer.kind === 251 /* FunctionDeclaration */ ||
50669                 (thisContainer.kind === 208 /* FunctionExpression */ && !ts.isPrototypePropertyAssignment(thisContainer.parent));
50670         }
50671         function getConstructorDefinedThisAssignmentTypes(types, declarations) {
50672             ts.Debug.assert(types.length === declarations.length);
50673             return types.filter(function (_, i) {
50674                 var declaration = declarations[i];
50675                 var expression = ts.isBinaryExpression(declaration) ? declaration :
50676                     ts.isBinaryExpression(declaration.parent) ? declaration.parent : undefined;
50677                 return expression && isDeclarationInConstructor(expression);
50678             });
50679         }
50680         // Return the type implied by a binding pattern element. This is the type of the initializer of the element if
50681         // one is present. Otherwise, if the element is itself a binding pattern, it is the type implied by the binding
50682         // pattern. Otherwise, it is the type any.
50683         function getTypeFromBindingElement(element, includePatternInType, reportErrors) {
50684             if (element.initializer) {
50685                 // The type implied by a binding pattern is independent of context, so we check the initializer with no
50686                 // contextual type or, if the element itself is a binding pattern, with the type implied by that binding
50687                 // pattern.
50688                 var contextualType = ts.isBindingPattern(element.name) ? getTypeFromBindingPattern(element.name, /*includePatternInType*/ true, /*reportErrors*/ false) : unknownType;
50689                 return addOptionality(widenTypeInferredFromInitializer(element, checkDeclarationInitializer(element, contextualType)));
50690             }
50691             if (ts.isBindingPattern(element.name)) {
50692                 return getTypeFromBindingPattern(element.name, includePatternInType, reportErrors);
50693             }
50694             if (reportErrors && !declarationBelongsToPrivateAmbientMember(element)) {
50695                 reportImplicitAny(element, anyType);
50696             }
50697             // When we're including the pattern in the type (an indication we're obtaining a contextual type), we
50698             // use the non-inferrable any type. Inference will never directly infer this type, but it is possible
50699             // to infer a type that contains it, e.g. for a binding pattern like [foo] or { foo }. In such cases,
50700             // widening of the binding pattern type substitutes a regular any for the non-inferrable any.
50701             return includePatternInType ? nonInferrableAnyType : anyType;
50702         }
50703         // Return the type implied by an object binding pattern
50704         function getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors) {
50705             var members = ts.createSymbolTable();
50706             var stringIndexInfo;
50707             var objectFlags = 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
50708             ts.forEach(pattern.elements, function (e) {
50709                 var name = e.propertyName || e.name;
50710                 if (e.dotDotDotToken) {
50711                     stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
50712                     return;
50713                 }
50714                 var exprType = getLiteralTypeFromPropertyName(name);
50715                 if (!isTypeUsableAsPropertyName(exprType)) {
50716                     // do not include computed properties in the implied type
50717                     objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
50718                     return;
50719                 }
50720                 var text = getPropertyNameFromType(exprType);
50721                 var flags = 4 /* Property */ | (e.initializer ? 16777216 /* Optional */ : 0);
50722                 var symbol = createSymbol(flags, text);
50723                 symbol.type = getTypeFromBindingElement(e, includePatternInType, reportErrors);
50724                 symbol.bindingElement = e;
50725                 members.set(symbol.escapedName, symbol);
50726             });
50727             var result = createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
50728             result.objectFlags |= objectFlags;
50729             if (includePatternInType) {
50730                 result.pattern = pattern;
50731                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
50732             }
50733             return result;
50734         }
50735         // Return the type implied by an array binding pattern
50736         function getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors) {
50737             var elements = pattern.elements;
50738             var lastElement = ts.lastOrUndefined(elements);
50739             var restElement = lastElement && lastElement.kind === 198 /* BindingElement */ && lastElement.dotDotDotToken ? lastElement : undefined;
50740             if (elements.length === 0 || elements.length === 1 && restElement) {
50741                 return languageVersion >= 2 /* ES2015 */ ? createIterableType(anyType) : anyArrayType;
50742             }
50743             var elementTypes = ts.map(elements, function (e) { return ts.isOmittedExpression(e) ? anyType : getTypeFromBindingElement(e, includePatternInType, reportErrors); });
50744             var minLength = ts.findLastIndex(elements, function (e) { return !(e === restElement || ts.isOmittedExpression(e) || hasDefaultValue(e)); }, elements.length - 1) + 1;
50745             var elementFlags = ts.map(elements, function (e, i) { return e === restElement ? 4 /* Rest */ : i >= minLength ? 2 /* Optional */ : 1 /* Required */; });
50746             var result = createTupleType(elementTypes, elementFlags);
50747             if (includePatternInType) {
50748                 result = cloneTypeReference(result);
50749                 result.pattern = pattern;
50750                 result.objectFlags |= 1048576 /* ContainsObjectOrArrayLiteral */;
50751             }
50752             return result;
50753         }
50754         // Return the type implied by a binding pattern. This is the type implied purely by the binding pattern itself
50755         // and without regard to its context (i.e. without regard any type annotation or initializer associated with the
50756         // declaration in which the binding pattern is contained). For example, the implied type of [x, y] is [any, any]
50757         // and the implied type of { x, y: z = 1 } is { x: any; y: number; }. The type implied by a binding pattern is
50758         // used as the contextual type of an initializer associated with the binding pattern. Also, for a destructuring
50759         // parameter with no type annotation or initializer, the type implied by the binding pattern becomes the type of
50760         // the parameter.
50761         function getTypeFromBindingPattern(pattern, includePatternInType, reportErrors) {
50762             if (includePatternInType === void 0) { includePatternInType = false; }
50763             if (reportErrors === void 0) { reportErrors = false; }
50764             return pattern.kind === 196 /* ObjectBindingPattern */
50765                 ? getTypeFromObjectBindingPattern(pattern, includePatternInType, reportErrors)
50766                 : getTypeFromArrayBindingPattern(pattern, includePatternInType, reportErrors);
50767         }
50768         // Return the type associated with a variable, parameter, or property declaration. In the simple case this is the type
50769         // specified in a type annotation or inferred from an initializer. However, in the case of a destructuring declaration it
50770         // is a bit more involved. For example:
50771         //
50772         //   var [x, s = ""] = [1, "one"];
50773         //
50774         // Here, the array literal [1, "one"] is contextually typed by the type [any, string], which is the implied type of the
50775         // binding pattern [x, s = ""]. Because the contextual type is a tuple type, the resulting type of [1, "one"] is the
50776         // tuple type [number, string]. Thus, the type inferred for 'x' is number and the type inferred for 's' is string.
50777         function getWidenedTypeForVariableLikeDeclaration(declaration, reportErrors) {
50778             return widenTypeForVariableLikeDeclaration(getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true), declaration, reportErrors);
50779         }
50780         function widenTypeForVariableLikeDeclaration(type, declaration, reportErrors) {
50781             if (type) {
50782                 if (reportErrors) {
50783                     reportErrorsFromWidening(declaration, type);
50784                 }
50785                 // always widen a 'unique symbol' type if the type was created for a different declaration.
50786                 if (type.flags & 8192 /* UniqueESSymbol */ && (ts.isBindingElement(declaration) || !declaration.type) && type.symbol !== getSymbolOfNode(declaration)) {
50787                     type = esSymbolType;
50788                 }
50789                 return getWidenedType(type);
50790             }
50791             // Rest parameters default to type any[], other parameters default to type any
50792             type = ts.isParameter(declaration) && declaration.dotDotDotToken ? anyArrayType : anyType;
50793             // Report implicit any errors unless this is a private property within an ambient declaration
50794             if (reportErrors) {
50795                 if (!declarationBelongsToPrivateAmbientMember(declaration)) {
50796                     reportImplicitAny(declaration, type);
50797                 }
50798             }
50799             return type;
50800         }
50801         function declarationBelongsToPrivateAmbientMember(declaration) {
50802             var root = ts.getRootDeclaration(declaration);
50803             var memberDeclaration = root.kind === 160 /* Parameter */ ? root.parent : root;
50804             return isPrivateWithinAmbient(memberDeclaration);
50805         }
50806         function tryGetTypeFromEffectiveTypeNode(declaration) {
50807             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
50808             if (typeNode) {
50809                 return getTypeFromTypeNode(typeNode);
50810             }
50811         }
50812         function getTypeOfVariableOrParameterOrProperty(symbol) {
50813             var links = getSymbolLinks(symbol);
50814             if (!links.type) {
50815                 var type = getTypeOfVariableOrParameterOrPropertyWorker(symbol);
50816                 // For a contextually typed parameter it is possible that a type has already
50817                 // been assigned (in assignTypeToParameterAndFixTypeParameters), and we want
50818                 // to preserve this type.
50819                 if (!links.type) {
50820                     links.type = type;
50821                 }
50822             }
50823             return links.type;
50824         }
50825         function getTypeOfVariableOrParameterOrPropertyWorker(symbol) {
50826             // Handle prototype property
50827             if (symbol.flags & 4194304 /* Prototype */) {
50828                 return getTypeOfPrototypeProperty(symbol);
50829             }
50830             // CommonsJS require and module both have type any.
50831             if (symbol === requireSymbol) {
50832                 return anyType;
50833             }
50834             if (symbol.flags & 134217728 /* ModuleExports */) {
50835                 var fileSymbol = getSymbolOfNode(ts.getSourceFileOfNode(symbol.valueDeclaration));
50836                 var members = ts.createSymbolTable();
50837                 members.set("exports", fileSymbol);
50838                 return createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
50839             }
50840             // Handle catch clause variables
50841             var declaration = symbol.valueDeclaration;
50842             if (ts.isCatchClauseVariableDeclarationOrBindingElement(declaration)) {
50843                 var decl = declaration;
50844                 if (!decl.type)
50845                     return anyType;
50846                 var type_1 = getTypeOfNode(decl.type);
50847                 // an errorType will make `checkTryStatement` issue an error
50848                 return isTypeAny(type_1) || type_1 === unknownType ? type_1 : errorType;
50849             }
50850             // Handle export default expressions
50851             if (ts.isSourceFile(declaration) && ts.isJsonSourceFile(declaration)) {
50852                 if (!declaration.statements.length) {
50853                     return emptyObjectType;
50854                 }
50855                 return getWidenedType(getWidenedLiteralType(checkExpression(declaration.statements[0].expression)));
50856             }
50857             // Handle variable, parameter or property
50858             if (!pushTypeResolution(symbol, 0 /* Type */)) {
50859                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
50860                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
50861                     return getTypeOfFuncClassEnumModule(symbol);
50862                 }
50863                 return reportCircularityError(symbol);
50864             }
50865             var type;
50866             if (declaration.kind === 266 /* ExportAssignment */) {
50867                 type = widenTypeForVariableLikeDeclaration(checkExpressionCached(declaration.expression), declaration);
50868             }
50869             else if (ts.isBinaryExpression(declaration) ||
50870                 (ts.isInJSFile(declaration) &&
50871                     (ts.isCallExpression(declaration) || (ts.isPropertyAccessExpression(declaration) || ts.isBindableStaticElementAccessExpression(declaration)) && ts.isBinaryExpression(declaration.parent)))) {
50872                 type = getWidenedTypeForAssignmentDeclaration(symbol);
50873             }
50874             else if (ts.isPropertyAccessExpression(declaration)
50875                 || ts.isElementAccessExpression(declaration)
50876                 || ts.isIdentifier(declaration)
50877                 || ts.isStringLiteralLike(declaration)
50878                 || ts.isNumericLiteral(declaration)
50879                 || ts.isClassDeclaration(declaration)
50880                 || ts.isFunctionDeclaration(declaration)
50881                 || (ts.isMethodDeclaration(declaration) && !ts.isObjectLiteralMethod(declaration))
50882                 || ts.isMethodSignature(declaration)
50883                 || ts.isSourceFile(declaration)) {
50884                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
50885                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
50886                     return getTypeOfFuncClassEnumModule(symbol);
50887                 }
50888                 type = ts.isBinaryExpression(declaration.parent) ?
50889                     getWidenedTypeForAssignmentDeclaration(symbol) :
50890                     tryGetTypeFromEffectiveTypeNode(declaration) || anyType;
50891             }
50892             else if (ts.isPropertyAssignment(declaration)) {
50893                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkPropertyAssignment(declaration);
50894             }
50895             else if (ts.isJsxAttribute(declaration)) {
50896                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkJsxAttribute(declaration);
50897             }
50898             else if (ts.isShorthandPropertyAssignment(declaration)) {
50899                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkExpressionForMutableLocation(declaration.name, 0 /* Normal */);
50900             }
50901             else if (ts.isObjectLiteralMethod(declaration)) {
50902                 type = tryGetTypeFromEffectiveTypeNode(declaration) || checkObjectLiteralMethod(declaration, 0 /* Normal */);
50903             }
50904             else if (ts.isParameter(declaration)
50905                 || ts.isPropertyDeclaration(declaration)
50906                 || ts.isPropertySignature(declaration)
50907                 || ts.isVariableDeclaration(declaration)
50908                 || ts.isBindingElement(declaration)
50909                 || ts.isJSDocPropertyLikeTag(declaration)) {
50910                 type = getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
50911             }
50912             // getTypeOfSymbol dispatches some JS merges incorrectly because their symbol flags are not mutually exclusive.
50913             // Re-dispatch based on valueDeclaration.kind instead.
50914             else if (ts.isEnumDeclaration(declaration)) {
50915                 type = getTypeOfFuncClassEnumModule(symbol);
50916             }
50917             else if (ts.isEnumMember(declaration)) {
50918                 type = getTypeOfEnumMember(symbol);
50919             }
50920             else if (ts.isAccessor(declaration)) {
50921                 type = resolveTypeOfAccessors(symbol);
50922             }
50923             else {
50924                 return ts.Debug.fail("Unhandled declaration kind! " + ts.Debug.formatSyntaxKind(declaration.kind) + " for " + ts.Debug.formatSymbol(symbol));
50925             }
50926             if (!popTypeResolution()) {
50927                 // Symbol is property of some kind that is merged with something - should use `getTypeOfFuncClassEnumModule` and not `getTypeOfVariableOrParameterOrProperty`
50928                 if (symbol.flags & 512 /* ValueModule */ && !(symbol.flags & 67108864 /* Assignment */)) {
50929                     return getTypeOfFuncClassEnumModule(symbol);
50930                 }
50931                 return reportCircularityError(symbol);
50932             }
50933             return type;
50934         }
50935         function getAnnotatedAccessorTypeNode(accessor) {
50936             if (accessor) {
50937                 if (accessor.kind === 167 /* GetAccessor */) {
50938                     var getterTypeAnnotation = ts.getEffectiveReturnTypeNode(accessor);
50939                     return getterTypeAnnotation;
50940                 }
50941                 else {
50942                     var setterTypeAnnotation = ts.getEffectiveSetAccessorTypeAnnotationNode(accessor);
50943                     return setterTypeAnnotation;
50944                 }
50945             }
50946             return undefined;
50947         }
50948         function getAnnotatedAccessorType(accessor) {
50949             var node = getAnnotatedAccessorTypeNode(accessor);
50950             return node && getTypeFromTypeNode(node);
50951         }
50952         function getAnnotatedAccessorThisParameter(accessor) {
50953             var parameter = getAccessorThisParameter(accessor);
50954             return parameter && parameter.symbol;
50955         }
50956         function getThisTypeOfDeclaration(declaration) {
50957             return getThisTypeOfSignature(getSignatureFromDeclaration(declaration));
50958         }
50959         function getTypeOfAccessors(symbol) {
50960             var links = getSymbolLinks(symbol);
50961             return links.type || (links.type = getTypeOfAccessorsWorker(symbol));
50962         }
50963         function getTypeOfAccessorsWorker(symbol) {
50964             if (!pushTypeResolution(symbol, 0 /* Type */)) {
50965                 return errorType;
50966             }
50967             var type = resolveTypeOfAccessors(symbol);
50968             if (!popTypeResolution()) {
50969                 type = anyType;
50970                 if (noImplicitAny) {
50971                     var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */);
50972                     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));
50973                 }
50974             }
50975             return type;
50976         }
50977         function resolveTypeOfAccessors(symbol) {
50978             var getter = ts.getDeclarationOfKind(symbol, 167 /* GetAccessor */);
50979             var setter = ts.getDeclarationOfKind(symbol, 168 /* SetAccessor */);
50980             if (getter && ts.isInJSFile(getter)) {
50981                 var jsDocType = getTypeForDeclarationFromJSDocComment(getter);
50982                 if (jsDocType) {
50983                     return jsDocType;
50984                 }
50985             }
50986             // First try to see if the user specified a return type on the get-accessor.
50987             var getterReturnType = getAnnotatedAccessorType(getter);
50988             if (getterReturnType) {
50989                 return getterReturnType;
50990             }
50991             else {
50992                 // If the user didn't specify a return type, try to use the set-accessor's parameter type.
50993                 var setterParameterType = getAnnotatedAccessorType(setter);
50994                 if (setterParameterType) {
50995                     return setterParameterType;
50996                 }
50997                 else {
50998                     // If there are no specified types, try to infer it from the body of the get accessor if it exists.
50999                     if (getter && getter.body) {
51000                         return getReturnTypeFromBody(getter);
51001                     }
51002                     // Otherwise, fall back to 'any'.
51003                     else {
51004                         if (setter) {
51005                             if (!isPrivateWithinAmbient(setter)) {
51006                                 errorOrSuggestion(noImplicitAny, setter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_set_accessor_lacks_a_parameter_type_annotation, symbolToString(symbol));
51007                             }
51008                         }
51009                         else {
51010                             ts.Debug.assert(!!getter, "there must exist a getter as we are current checking either setter or getter in this function");
51011                             if (!isPrivateWithinAmbient(getter)) {
51012                                 errorOrSuggestion(noImplicitAny, getter, ts.Diagnostics.Property_0_implicitly_has_type_any_because_its_get_accessor_lacks_a_return_type_annotation, symbolToString(symbol));
51013                             }
51014                         }
51015                         return anyType;
51016                     }
51017                 }
51018             }
51019         }
51020         function getBaseTypeVariableOfClass(symbol) {
51021             var baseConstructorType = getBaseConstructorTypeOfClass(getDeclaredTypeOfClassOrInterface(symbol));
51022             return baseConstructorType.flags & 8650752 /* TypeVariable */ ? baseConstructorType :
51023                 baseConstructorType.flags & 2097152 /* Intersection */ ? ts.find(baseConstructorType.types, function (t) { return !!(t.flags & 8650752 /* TypeVariable */); }) :
51024                     undefined;
51025         }
51026         function getTypeOfFuncClassEnumModule(symbol) {
51027             var links = getSymbolLinks(symbol);
51028             var originalLinks = links;
51029             if (!links.type) {
51030                 var expando = symbol.valueDeclaration && getSymbolOfExpando(symbol.valueDeclaration, /*allowDeclaration*/ false);
51031                 if (expando) {
51032                     var merged = mergeJSSymbols(symbol, expando);
51033                     if (merged) {
51034                         // note:we overwrite links because we just cloned the symbol
51035                         symbol = links = merged;
51036                     }
51037                 }
51038                 originalLinks.type = links.type = getTypeOfFuncClassEnumModuleWorker(symbol);
51039             }
51040             return links.type;
51041         }
51042         function getTypeOfFuncClassEnumModuleWorker(symbol) {
51043             var declaration = symbol.valueDeclaration;
51044             if (symbol.flags & 1536 /* Module */ && ts.isShorthandAmbientModuleSymbol(symbol)) {
51045                 return anyType;
51046             }
51047             else if (declaration && (declaration.kind === 216 /* BinaryExpression */ ||
51048                 ts.isAccessExpression(declaration) &&
51049                     declaration.parent.kind === 216 /* BinaryExpression */)) {
51050                 return getWidenedTypeForAssignmentDeclaration(symbol);
51051             }
51052             else if (symbol.flags & 512 /* ValueModule */ && declaration && ts.isSourceFile(declaration) && declaration.commonJsModuleIndicator) {
51053                 var resolvedModule = resolveExternalModuleSymbol(symbol);
51054                 if (resolvedModule !== symbol) {
51055                     if (!pushTypeResolution(symbol, 0 /* Type */)) {
51056                         return errorType;
51057                     }
51058                     var exportEquals = getMergedSymbol(symbol.exports.get("export=" /* ExportEquals */));
51059                     var type_2 = getWidenedTypeForAssignmentDeclaration(exportEquals, exportEquals === resolvedModule ? undefined : resolvedModule);
51060                     if (!popTypeResolution()) {
51061                         return reportCircularityError(symbol);
51062                     }
51063                     return type_2;
51064                 }
51065             }
51066             var type = createObjectType(16 /* Anonymous */, symbol);
51067             if (symbol.flags & 32 /* Class */) {
51068                 var baseTypeVariable = getBaseTypeVariableOfClass(symbol);
51069                 return baseTypeVariable ? getIntersectionType([type, baseTypeVariable]) : type;
51070             }
51071             else {
51072                 return strictNullChecks && symbol.flags & 16777216 /* Optional */ ? getOptionalType(type) : type;
51073             }
51074         }
51075         function getTypeOfEnumMember(symbol) {
51076             var links = getSymbolLinks(symbol);
51077             return links.type || (links.type = getDeclaredTypeOfEnumMember(symbol));
51078         }
51079         function getTypeOfAlias(symbol) {
51080             var links = getSymbolLinks(symbol);
51081             if (!links.type) {
51082                 var targetSymbol = resolveAlias(symbol);
51083                 // It only makes sense to get the type of a value symbol. If the result of resolving
51084                 // the alias is not a value, then it has no type. To get the type associated with a
51085                 // type symbol, call getDeclaredTypeOfSymbol.
51086                 // This check is important because without it, a call to getTypeOfSymbol could end
51087                 // up recursively calling getTypeOfAlias, causing a stack overflow.
51088                 links.type = targetSymbol.flags & 111551 /* Value */
51089                     ? getTypeOfSymbol(targetSymbol)
51090                     : errorType;
51091             }
51092             return links.type;
51093         }
51094         function getTypeOfInstantiatedSymbol(symbol) {
51095             var links = getSymbolLinks(symbol);
51096             if (!links.type) {
51097                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
51098                     return links.type = errorType;
51099                 }
51100                 var type = instantiateType(getTypeOfSymbol(links.target), links.mapper);
51101                 if (!popTypeResolution()) {
51102                     type = reportCircularityError(symbol);
51103                 }
51104                 links.type = type;
51105             }
51106             return links.type;
51107         }
51108         function reportCircularityError(symbol) {
51109             var declaration = symbol.valueDeclaration;
51110             // Check if variable has type annotation that circularly references the variable itself
51111             if (ts.getEffectiveTypeAnnotationNode(declaration)) {
51112                 error(symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_type_annotation, symbolToString(symbol));
51113                 return errorType;
51114             }
51115             // Check if variable has initializer that circularly references the variable itself
51116             if (noImplicitAny && (declaration.kind !== 160 /* Parameter */ || declaration.initializer)) {
51117                 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));
51118             }
51119             // Circularities could also result from parameters in function expressions that end up
51120             // having themselves as contextual types following type argument inference. In those cases
51121             // we have already reported an implicit any error so we don't report anything here.
51122             return anyType;
51123         }
51124         function getTypeOfSymbolWithDeferredType(symbol) {
51125             var links = getSymbolLinks(symbol);
51126             if (!links.type) {
51127                 ts.Debug.assertIsDefined(links.deferralParent);
51128                 ts.Debug.assertIsDefined(links.deferralConstituents);
51129                 links.type = links.deferralParent.flags & 1048576 /* Union */ ? getUnionType(links.deferralConstituents) : getIntersectionType(links.deferralConstituents);
51130             }
51131             return links.type;
51132         }
51133         function getTypeOfSymbol(symbol) {
51134             var checkFlags = ts.getCheckFlags(symbol);
51135             if (checkFlags & 65536 /* DeferredType */) {
51136                 return getTypeOfSymbolWithDeferredType(symbol);
51137             }
51138             if (checkFlags & 1 /* Instantiated */) {
51139                 return getTypeOfInstantiatedSymbol(symbol);
51140             }
51141             if (checkFlags & 262144 /* Mapped */) {
51142                 return getTypeOfMappedSymbol(symbol);
51143             }
51144             if (checkFlags & 8192 /* ReverseMapped */) {
51145                 return getTypeOfReverseMappedSymbol(symbol);
51146             }
51147             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
51148                 return getTypeOfVariableOrParameterOrProperty(symbol);
51149             }
51150             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 384 /* Enum */ | 512 /* ValueModule */)) {
51151                 return getTypeOfFuncClassEnumModule(symbol);
51152             }
51153             if (symbol.flags & 8 /* EnumMember */) {
51154                 return getTypeOfEnumMember(symbol);
51155             }
51156             if (symbol.flags & 98304 /* Accessor */) {
51157                 return getTypeOfAccessors(symbol);
51158             }
51159             if (symbol.flags & 2097152 /* Alias */) {
51160                 return getTypeOfAlias(symbol);
51161             }
51162             return errorType;
51163         }
51164         function isReferenceToType(type, target) {
51165             return type !== undefined
51166                 && target !== undefined
51167                 && (ts.getObjectFlags(type) & 4 /* Reference */) !== 0
51168                 && type.target === target;
51169         }
51170         function getTargetType(type) {
51171             return ts.getObjectFlags(type) & 4 /* Reference */ ? type.target : type;
51172         }
51173         // TODO: GH#18217 If `checkBase` is undefined, we should not call this because this will always return false.
51174         function hasBaseType(type, checkBase) {
51175             return check(type);
51176             function check(type) {
51177                 if (ts.getObjectFlags(type) & (3 /* ClassOrInterface */ | 4 /* Reference */)) {
51178                     var target = getTargetType(type);
51179                     return target === checkBase || ts.some(getBaseTypes(target), check);
51180                 }
51181                 else if (type.flags & 2097152 /* Intersection */) {
51182                     return ts.some(type.types, check);
51183                 }
51184                 return false;
51185             }
51186         }
51187         // Appends the type parameters given by a list of declarations to a set of type parameters and returns the resulting set.
51188         // The function allocates a new array if the input type parameter set is undefined, but otherwise it modifies the set
51189         // in-place and returns the same array.
51190         function appendTypeParameters(typeParameters, declarations) {
51191             for (var _i = 0, declarations_2 = declarations; _i < declarations_2.length; _i++) {
51192                 var declaration = declarations_2[_i];
51193                 typeParameters = ts.appendIfUnique(typeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(declaration)));
51194             }
51195             return typeParameters;
51196         }
51197         // Return the outer type parameters of a node or undefined if the node has no outer type parameters.
51198         function getOuterTypeParameters(node, includeThisTypes) {
51199             while (true) {
51200                 node = node.parent; // TODO: GH#18217 Use SourceFile kind check instead
51201                 if (node && ts.isBinaryExpression(node)) {
51202                     // prototype assignments get the outer type parameters of their constructor function
51203                     var assignmentKind = ts.getAssignmentDeclarationKind(node);
51204                     if (assignmentKind === 6 /* Prototype */ || assignmentKind === 3 /* PrototypeProperty */) {
51205                         var symbol = getSymbolOfNode(node.left);
51206                         if (symbol && symbol.parent && !ts.findAncestor(symbol.parent.valueDeclaration, function (d) { return node === d; })) {
51207                             node = symbol.parent.valueDeclaration;
51208                         }
51209                     }
51210                 }
51211                 if (!node) {
51212                     return undefined;
51213                 }
51214                 switch (node.kind) {
51215                     case 232 /* VariableStatement */:
51216                     case 252 /* ClassDeclaration */:
51217                     case 221 /* ClassExpression */:
51218                     case 253 /* InterfaceDeclaration */:
51219                     case 169 /* CallSignature */:
51220                     case 170 /* ConstructSignature */:
51221                     case 164 /* MethodSignature */:
51222                     case 174 /* FunctionType */:
51223                     case 175 /* ConstructorType */:
51224                     case 308 /* JSDocFunctionType */:
51225                     case 251 /* FunctionDeclaration */:
51226                     case 165 /* MethodDeclaration */:
51227                     case 208 /* FunctionExpression */:
51228                     case 209 /* ArrowFunction */:
51229                     case 254 /* TypeAliasDeclaration */:
51230                     case 330 /* JSDocTemplateTag */:
51231                     case 331 /* JSDocTypedefTag */:
51232                     case 325 /* JSDocEnumTag */:
51233                     case 324 /* JSDocCallbackTag */:
51234                     case 190 /* MappedType */:
51235                     case 184 /* ConditionalType */:
51236                         var outerTypeParameters = getOuterTypeParameters(node, includeThisTypes);
51237                         if (node.kind === 190 /* MappedType */) {
51238                             return ts.append(outerTypeParameters, getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter)));
51239                         }
51240                         else if (node.kind === 184 /* ConditionalType */) {
51241                             return ts.concatenate(outerTypeParameters, getInferTypeParameters(node));
51242                         }
51243                         else if (node.kind === 232 /* VariableStatement */ && !ts.isInJSFile(node)) {
51244                             break;
51245                         }
51246                         var outerAndOwnTypeParameters = appendTypeParameters(outerTypeParameters, ts.getEffectiveTypeParameterDeclarations(node));
51247                         var thisType = includeThisTypes &&
51248                             (node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */ || node.kind === 253 /* InterfaceDeclaration */ || isJSConstructor(node)) &&
51249                             getDeclaredTypeOfClassOrInterface(getSymbolOfNode(node)).thisType;
51250                         return thisType ? ts.append(outerAndOwnTypeParameters, thisType) : outerAndOwnTypeParameters;
51251                     case 326 /* JSDocParameterTag */:
51252                         var paramSymbol = ts.getParameterSymbolFromJSDoc(node);
51253                         if (paramSymbol) {
51254                             node = paramSymbol.valueDeclaration;
51255                         }
51256                         break;
51257                 }
51258             }
51259         }
51260         // The outer type parameters are those defined by enclosing generic classes, methods, or functions.
51261         function getOuterTypeParametersOfClassOrInterface(symbol) {
51262             var declaration = symbol.flags & 32 /* Class */ ? symbol.valueDeclaration : ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */);
51263             ts.Debug.assert(!!declaration, "Class was missing valueDeclaration -OR- non-class had no interface declarations");
51264             return getOuterTypeParameters(declaration);
51265         }
51266         // The local type parameters are the combined set of type parameters from all declarations of the class,
51267         // interface, or type alias.
51268         function getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) {
51269             var result;
51270             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51271                 var node = _a[_i];
51272                 if (node.kind === 253 /* InterfaceDeclaration */ ||
51273                     node.kind === 252 /* ClassDeclaration */ ||
51274                     node.kind === 221 /* ClassExpression */ ||
51275                     isJSConstructor(node) ||
51276                     ts.isTypeAlias(node)) {
51277                     var declaration = node;
51278                     result = appendTypeParameters(result, ts.getEffectiveTypeParameterDeclarations(declaration));
51279                 }
51280             }
51281             return result;
51282         }
51283         // The full set of type parameters for a generic class or interface type consists of its outer type parameters plus
51284         // its locally declared type parameters.
51285         function getTypeParametersOfClassOrInterface(symbol) {
51286             return ts.concatenate(getOuterTypeParametersOfClassOrInterface(symbol), getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol));
51287         }
51288         // A type is a mixin constructor if it has a single construct signature taking no type parameters and a single
51289         // rest parameter of type any[].
51290         function isMixinConstructorType(type) {
51291             var signatures = getSignaturesOfType(type, 1 /* Construct */);
51292             if (signatures.length === 1) {
51293                 var s = signatures[0];
51294                 return !s.typeParameters && s.parameters.length === 1 && signatureHasRestParameter(s) && getElementTypeOfArrayType(getTypeOfParameter(s.parameters[0])) === anyType;
51295             }
51296             return false;
51297         }
51298         function isConstructorType(type) {
51299             if (getSignaturesOfType(type, 1 /* Construct */).length > 0) {
51300                 return true;
51301             }
51302             if (type.flags & 8650752 /* TypeVariable */) {
51303                 var constraint = getBaseConstraintOfType(type);
51304                 return !!constraint && isMixinConstructorType(constraint);
51305             }
51306             return false;
51307         }
51308         function getBaseTypeNodeOfClass(type) {
51309             return ts.getEffectiveBaseTypeNode(type.symbol.valueDeclaration);
51310         }
51311         function getConstructorsForTypeArguments(type, typeArgumentNodes, location) {
51312             var typeArgCount = ts.length(typeArgumentNodes);
51313             var isJavascript = ts.isInJSFile(location);
51314             return ts.filter(getSignaturesOfType(type, 1 /* Construct */), function (sig) { return (isJavascript || typeArgCount >= getMinTypeArgumentCount(sig.typeParameters)) && typeArgCount <= ts.length(sig.typeParameters); });
51315         }
51316         function getInstantiatedConstructorsForTypeArguments(type, typeArgumentNodes, location) {
51317             var signatures = getConstructorsForTypeArguments(type, typeArgumentNodes, location);
51318             var typeArguments = ts.map(typeArgumentNodes, getTypeFromTypeNode);
51319             return ts.sameMap(signatures, function (sig) { return ts.some(sig.typeParameters) ? getSignatureInstantiation(sig, typeArguments, ts.isInJSFile(location)) : sig; });
51320         }
51321         /**
51322          * The base constructor of a class can resolve to
51323          * * undefinedType if the class has no extends clause,
51324          * * unknownType if an error occurred during resolution of the extends expression,
51325          * * nullType if the extends expression is the null value,
51326          * * anyType if the extends expression has type any, or
51327          * * an object type with at least one construct signature.
51328          */
51329         function getBaseConstructorTypeOfClass(type) {
51330             if (!type.resolvedBaseConstructorType) {
51331                 var decl = type.symbol.valueDeclaration;
51332                 var extended = ts.getEffectiveBaseTypeNode(decl);
51333                 var baseTypeNode = getBaseTypeNodeOfClass(type);
51334                 if (!baseTypeNode) {
51335                     return type.resolvedBaseConstructorType = undefinedType;
51336                 }
51337                 if (!pushTypeResolution(type, 1 /* ResolvedBaseConstructorType */)) {
51338                     return errorType;
51339                 }
51340                 var baseConstructorType = checkExpression(baseTypeNode.expression);
51341                 if (extended && baseTypeNode !== extended) {
51342                     ts.Debug.assert(!extended.typeArguments); // Because this is in a JS file, and baseTypeNode is in an @extends tag
51343                     checkExpression(extended.expression);
51344                 }
51345                 if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
51346                     // Resolving the members of a class requires us to resolve the base class of that class.
51347                     // We force resolution here such that we catch circularities now.
51348                     resolveStructuredTypeMembers(baseConstructorType);
51349                 }
51350                 if (!popTypeResolution()) {
51351                     error(type.symbol.valueDeclaration, ts.Diagnostics._0_is_referenced_directly_or_indirectly_in_its_own_base_expression, symbolToString(type.symbol));
51352                     return type.resolvedBaseConstructorType = errorType;
51353                 }
51354                 if (!(baseConstructorType.flags & 1 /* Any */) && baseConstructorType !== nullWideningType && !isConstructorType(baseConstructorType)) {
51355                     var err = error(baseTypeNode.expression, ts.Diagnostics.Type_0_is_not_a_constructor_function_type, typeToString(baseConstructorType));
51356                     if (baseConstructorType.flags & 262144 /* TypeParameter */) {
51357                         var constraint = getConstraintFromTypeParameter(baseConstructorType);
51358                         var ctorReturn = unknownType;
51359                         if (constraint) {
51360                             var ctorSig = getSignaturesOfType(constraint, 1 /* Construct */);
51361                             if (ctorSig[0]) {
51362                                 ctorReturn = getReturnTypeOfSignature(ctorSig[0]);
51363                             }
51364                         }
51365                         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)));
51366                     }
51367                     return type.resolvedBaseConstructorType = errorType;
51368                 }
51369                 type.resolvedBaseConstructorType = baseConstructorType;
51370             }
51371             return type.resolvedBaseConstructorType;
51372         }
51373         function getImplementsTypes(type) {
51374             var resolvedImplementsTypes = ts.emptyArray;
51375             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
51376                 var declaration = _a[_i];
51377                 var implementsTypeNodes = ts.getEffectiveImplementsTypeNodes(declaration);
51378                 if (!implementsTypeNodes)
51379                     continue;
51380                 for (var _b = 0, implementsTypeNodes_1 = implementsTypeNodes; _b < implementsTypeNodes_1.length; _b++) {
51381                     var node = implementsTypeNodes_1[_b];
51382                     var implementsType = getTypeFromTypeNode(node);
51383                     if (implementsType !== errorType) {
51384                         if (resolvedImplementsTypes === ts.emptyArray) {
51385                             resolvedImplementsTypes = [implementsType];
51386                         }
51387                         else {
51388                             resolvedImplementsTypes.push(implementsType);
51389                         }
51390                     }
51391                 }
51392             }
51393             return resolvedImplementsTypes;
51394         }
51395         function reportCircularBaseType(node, type) {
51396             error(node, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
51397         }
51398         function getBaseTypes(type) {
51399             if (!type.baseTypesResolved) {
51400                 if (pushTypeResolution(type, 7 /* ResolvedBaseTypes */)) {
51401                     if (type.objectFlags & 8 /* Tuple */) {
51402                         type.resolvedBaseTypes = [getTupleBaseType(type)];
51403                     }
51404                     else if (type.symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
51405                         if (type.symbol.flags & 32 /* Class */) {
51406                             resolveBaseTypesOfClass(type);
51407                         }
51408                         if (type.symbol.flags & 64 /* Interface */) {
51409                             resolveBaseTypesOfInterface(type);
51410                         }
51411                     }
51412                     else {
51413                         ts.Debug.fail("type must be class or interface");
51414                     }
51415                     if (!popTypeResolution()) {
51416                         for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
51417                             var declaration = _a[_i];
51418                             if (declaration.kind === 252 /* ClassDeclaration */ || declaration.kind === 253 /* InterfaceDeclaration */) {
51419                                 reportCircularBaseType(declaration, type);
51420                             }
51421                         }
51422                     }
51423                 }
51424                 type.baseTypesResolved = true;
51425             }
51426             return type.resolvedBaseTypes;
51427         }
51428         function getTupleBaseType(type) {
51429             var elementTypes = ts.sameMap(type.typeParameters, function (t, i) { return type.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t; });
51430             return createArrayType(getUnionType(elementTypes || ts.emptyArray), type.readonly);
51431         }
51432         function resolveBaseTypesOfClass(type) {
51433             type.resolvedBaseTypes = ts.resolvingEmptyArray;
51434             var baseConstructorType = getApparentType(getBaseConstructorTypeOfClass(type));
51435             if (!(baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 1 /* Any */))) {
51436                 return type.resolvedBaseTypes = ts.emptyArray;
51437             }
51438             var baseTypeNode = getBaseTypeNodeOfClass(type);
51439             var baseType;
51440             var originalBaseType = baseConstructorType.symbol ? getDeclaredTypeOfSymbol(baseConstructorType.symbol) : undefined;
51441             if (baseConstructorType.symbol && baseConstructorType.symbol.flags & 32 /* Class */ &&
51442                 areAllOuterTypeParametersApplied(originalBaseType)) {
51443                 // 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
51444                 // class and all return the instance type of the class. There is no need for further checks and we can apply the
51445                 // type arguments in the same manner as a type reference to get the same error reporting experience.
51446                 baseType = getTypeFromClassOrInterfaceReference(baseTypeNode, baseConstructorType.symbol);
51447             }
51448             else if (baseConstructorType.flags & 1 /* Any */) {
51449                 baseType = baseConstructorType;
51450             }
51451             else {
51452                 // The class derives from a "class-like" constructor function, check that we have at least one construct signature
51453                 // with a matching number of type parameters and use the return type of the first instantiated signature. Elsewhere
51454                 // we check that all instantiated signatures return the same type.
51455                 var constructors = getInstantiatedConstructorsForTypeArguments(baseConstructorType, baseTypeNode.typeArguments, baseTypeNode);
51456                 if (!constructors.length) {
51457                     error(baseTypeNode.expression, ts.Diagnostics.No_base_constructor_has_the_specified_number_of_type_arguments);
51458                     return type.resolvedBaseTypes = ts.emptyArray;
51459                 }
51460                 baseType = getReturnTypeOfSignature(constructors[0]);
51461             }
51462             if (baseType === errorType) {
51463                 return type.resolvedBaseTypes = ts.emptyArray;
51464             }
51465             var reducedBaseType = getReducedType(baseType);
51466             if (!isValidBaseType(reducedBaseType)) {
51467                 var elaboration = elaborateNeverIntersection(/*errorInfo*/ undefined, baseType);
51468                 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));
51469                 diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(baseTypeNode.expression, diagnostic));
51470                 return type.resolvedBaseTypes = ts.emptyArray;
51471             }
51472             if (type === reducedBaseType || hasBaseType(reducedBaseType, type)) {
51473                 error(type.symbol.valueDeclaration, ts.Diagnostics.Type_0_recursively_references_itself_as_a_base_type, typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */));
51474                 return type.resolvedBaseTypes = ts.emptyArray;
51475             }
51476             if (type.resolvedBaseTypes === ts.resolvingEmptyArray) {
51477                 // Circular reference, likely through instantiation of default parameters
51478                 // (otherwise there'd be an error from hasBaseType) - this is fine, but `.members` should be reset
51479                 // as `getIndexedAccessType` via `instantiateType` via `getTypeFromClassOrInterfaceReference` forces a
51480                 // partial instantiation of the members without the base types fully resolved
51481                 type.members = undefined;
51482             }
51483             return type.resolvedBaseTypes = [reducedBaseType];
51484         }
51485         function areAllOuterTypeParametersApplied(type) {
51486             // An unapplied type parameter has its symbol still the same as the matching argument symbol.
51487             // Since parameters are applied outer-to-inner, only the last outer parameter needs to be checked.
51488             var outerTypeParameters = type.outerTypeParameters;
51489             if (outerTypeParameters) {
51490                 var last_1 = outerTypeParameters.length - 1;
51491                 var typeArguments = getTypeArguments(type);
51492                 return outerTypeParameters[last_1].symbol !== typeArguments[last_1].symbol;
51493             }
51494             return true;
51495         }
51496         // A valid base type is `any`, an object type or intersection of object types.
51497         function isValidBaseType(type) {
51498             if (type.flags & 262144 /* TypeParameter */) {
51499                 var constraint = getBaseConstraintOfType(type);
51500                 if (constraint) {
51501                     return isValidBaseType(constraint);
51502                 }
51503             }
51504             // TODO: Given that we allow type parmeters here now, is this `!isGenericMappedType(type)` check really needed?
51505             // There's no reason a `T` should be allowed while a `Readonly<T>` should not.
51506             return !!(type.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 1 /* Any */) && !isGenericMappedType(type) ||
51507                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isValidBaseType));
51508         }
51509         function resolveBaseTypesOfInterface(type) {
51510             type.resolvedBaseTypes = type.resolvedBaseTypes || ts.emptyArray;
51511             for (var _i = 0, _a = type.symbol.declarations; _i < _a.length; _i++) {
51512                 var declaration = _a[_i];
51513                 if (declaration.kind === 253 /* InterfaceDeclaration */ && ts.getInterfaceBaseTypeNodes(declaration)) {
51514                     for (var _b = 0, _c = ts.getInterfaceBaseTypeNodes(declaration); _b < _c.length; _b++) {
51515                         var node = _c[_b];
51516                         var baseType = getReducedType(getTypeFromTypeNode(node));
51517                         if (baseType !== errorType) {
51518                             if (isValidBaseType(baseType)) {
51519                                 if (type !== baseType && !hasBaseType(baseType, type)) {
51520                                     if (type.resolvedBaseTypes === ts.emptyArray) {
51521                                         type.resolvedBaseTypes = [baseType];
51522                                     }
51523                                     else {
51524                                         type.resolvedBaseTypes.push(baseType);
51525                                     }
51526                                 }
51527                                 else {
51528                                     reportCircularBaseType(declaration, type);
51529                                 }
51530                             }
51531                             else {
51532                                 error(node, ts.Diagnostics.An_interface_can_only_extend_an_object_type_or_intersection_of_object_types_with_statically_known_members);
51533                             }
51534                         }
51535                     }
51536                 }
51537             }
51538         }
51539         /**
51540          * Returns true if the interface given by the symbol is free of "this" references.
51541          *
51542          * Specifically, the result is true if the interface itself contains no references
51543          * to "this" in its body, if all base types are interfaces,
51544          * and if none of the base interfaces have a "this" type.
51545          */
51546         function isThislessInterface(symbol) {
51547             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51548                 var declaration = _a[_i];
51549                 if (declaration.kind === 253 /* InterfaceDeclaration */) {
51550                     if (declaration.flags & 128 /* ContainsThis */) {
51551                         return false;
51552                     }
51553                     var baseTypeNodes = ts.getInterfaceBaseTypeNodes(declaration);
51554                     if (baseTypeNodes) {
51555                         for (var _b = 0, baseTypeNodes_1 = baseTypeNodes; _b < baseTypeNodes_1.length; _b++) {
51556                             var node = baseTypeNodes_1[_b];
51557                             if (ts.isEntityNameExpression(node.expression)) {
51558                                 var baseSymbol = resolveEntityName(node.expression, 788968 /* Type */, /*ignoreErrors*/ true);
51559                                 if (!baseSymbol || !(baseSymbol.flags & 64 /* Interface */) || getDeclaredTypeOfClassOrInterface(baseSymbol).thisType) {
51560                                     return false;
51561                                 }
51562                             }
51563                         }
51564                     }
51565                 }
51566             }
51567             return true;
51568         }
51569         function getDeclaredTypeOfClassOrInterface(symbol) {
51570             var links = getSymbolLinks(symbol);
51571             var originalLinks = links;
51572             if (!links.declaredType) {
51573                 var kind = symbol.flags & 32 /* Class */ ? 1 /* Class */ : 2 /* Interface */;
51574                 var merged = mergeJSSymbols(symbol, getAssignedClassSymbol(symbol.valueDeclaration));
51575                 if (merged) {
51576                     // note:we overwrite links because we just cloned the symbol
51577                     symbol = links = merged;
51578                 }
51579                 var type = originalLinks.declaredType = links.declaredType = createObjectType(kind, symbol);
51580                 var outerTypeParameters = getOuterTypeParametersOfClassOrInterface(symbol);
51581                 var localTypeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
51582                 // A class or interface is generic if it has type parameters or a "this" type. We always give classes a "this" type
51583                 // because it is not feasible to analyze all members to determine if the "this" type escapes the class (in particular,
51584                 // property types inferred from initializers and method return types inferred from return statements are very hard
51585                 // to exhaustively analyze). We give interfaces a "this" type if we can't definitely determine that they are free of
51586                 // "this" references.
51587                 if (outerTypeParameters || localTypeParameters || kind === 1 /* Class */ || !isThislessInterface(symbol)) {
51588                     type.objectFlags |= 4 /* Reference */;
51589                     type.typeParameters = ts.concatenate(outerTypeParameters, localTypeParameters);
51590                     type.outerTypeParameters = outerTypeParameters;
51591                     type.localTypeParameters = localTypeParameters;
51592                     type.instantiations = new ts.Map();
51593                     type.instantiations.set(getTypeListId(type.typeParameters), type);
51594                     type.target = type;
51595                     type.resolvedTypeArguments = type.typeParameters;
51596                     type.thisType = createTypeParameter(symbol);
51597                     type.thisType.isThisType = true;
51598                     type.thisType.constraint = type;
51599                 }
51600             }
51601             return links.declaredType;
51602         }
51603         function getDeclaredTypeOfTypeAlias(symbol) {
51604             var links = getSymbolLinks(symbol);
51605             if (!links.declaredType) {
51606                 // Note that we use the links object as the target here because the symbol object is used as the unique
51607                 // identity for resolution of the 'type' property in SymbolLinks.
51608                 if (!pushTypeResolution(symbol, 2 /* DeclaredType */)) {
51609                     return errorType;
51610                 }
51611                 var declaration = ts.Debug.checkDefined(ts.find(symbol.declarations, ts.isTypeAlias), "Type alias symbol with no valid declaration found");
51612                 var typeNode = ts.isJSDocTypeAlias(declaration) ? declaration.typeExpression : declaration.type;
51613                 // If typeNode is missing, we will error in checkJSDocTypedefTag.
51614                 var type = typeNode ? getTypeFromTypeNode(typeNode) : errorType;
51615                 if (popTypeResolution()) {
51616                     var typeParameters = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol);
51617                     if (typeParameters) {
51618                         // Initialize the instantiation cache for generic type aliases. The declared type corresponds to
51619                         // an instantiation of the type alias with the type parameters supplied as type arguments.
51620                         links.typeParameters = typeParameters;
51621                         links.instantiations = new ts.Map();
51622                         links.instantiations.set(getTypeListId(typeParameters), type);
51623                     }
51624                 }
51625                 else {
51626                     type = errorType;
51627                     error(ts.isNamedDeclaration(declaration) ? declaration.name : declaration || declaration, ts.Diagnostics.Type_alias_0_circularly_references_itself, symbolToString(symbol));
51628                 }
51629                 links.declaredType = type;
51630             }
51631             return links.declaredType;
51632         }
51633         function isStringConcatExpression(expr) {
51634             if (ts.isStringLiteralLike(expr)) {
51635                 return true;
51636             }
51637             else if (expr.kind === 216 /* BinaryExpression */) {
51638                 return isStringConcatExpression(expr.left) && isStringConcatExpression(expr.right);
51639             }
51640             return false;
51641         }
51642         function isLiteralEnumMember(member) {
51643             var expr = member.initializer;
51644             if (!expr) {
51645                 return !(member.flags & 8388608 /* Ambient */);
51646             }
51647             switch (expr.kind) {
51648                 case 10 /* StringLiteral */:
51649                 case 8 /* NumericLiteral */:
51650                 case 14 /* NoSubstitutionTemplateLiteral */:
51651                     return true;
51652                 case 214 /* PrefixUnaryExpression */:
51653                     return expr.operator === 40 /* MinusToken */ &&
51654                         expr.operand.kind === 8 /* NumericLiteral */;
51655                 case 78 /* Identifier */:
51656                     return ts.nodeIsMissing(expr) || !!getSymbolOfNode(member.parent).exports.get(expr.escapedText);
51657                 case 216 /* BinaryExpression */:
51658                     return isStringConcatExpression(expr);
51659                 default:
51660                     return false;
51661             }
51662         }
51663         function getEnumKind(symbol) {
51664             var links = getSymbolLinks(symbol);
51665             if (links.enumKind !== undefined) {
51666                 return links.enumKind;
51667             }
51668             var hasNonLiteralMember = false;
51669             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51670                 var declaration = _a[_i];
51671                 if (declaration.kind === 255 /* EnumDeclaration */) {
51672                     for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
51673                         var member = _c[_b];
51674                         if (member.initializer && ts.isStringLiteralLike(member.initializer)) {
51675                             return links.enumKind = 1 /* Literal */;
51676                         }
51677                         if (!isLiteralEnumMember(member)) {
51678                             hasNonLiteralMember = true;
51679                         }
51680                     }
51681                 }
51682             }
51683             return links.enumKind = hasNonLiteralMember ? 0 /* Numeric */ : 1 /* Literal */;
51684         }
51685         function getBaseTypeOfEnumLiteralType(type) {
51686             return type.flags & 1024 /* EnumLiteral */ && !(type.flags & 1048576 /* Union */) ? getDeclaredTypeOfSymbol(getParentOfSymbol(type.symbol)) : type;
51687         }
51688         function getDeclaredTypeOfEnum(symbol) {
51689             var links = getSymbolLinks(symbol);
51690             if (links.declaredType) {
51691                 return links.declaredType;
51692             }
51693             if (getEnumKind(symbol) === 1 /* Literal */) {
51694                 enumCount++;
51695                 var memberTypeList = [];
51696                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
51697                     var declaration = _a[_i];
51698                     if (declaration.kind === 255 /* EnumDeclaration */) {
51699                         for (var _b = 0, _c = declaration.members; _b < _c.length; _b++) {
51700                             var member = _c[_b];
51701                             var value = getEnumMemberValue(member);
51702                             var memberType = getFreshTypeOfLiteralType(getLiteralType(value !== undefined ? value : 0, enumCount, getSymbolOfNode(member)));
51703                             getSymbolLinks(getSymbolOfNode(member)).declaredType = memberType;
51704                             memberTypeList.push(getRegularTypeOfLiteralType(memberType));
51705                         }
51706                     }
51707                 }
51708                 if (memberTypeList.length) {
51709                     var enumType_1 = getUnionType(memberTypeList, 1 /* Literal */, symbol, /*aliasTypeArguments*/ undefined);
51710                     if (enumType_1.flags & 1048576 /* Union */) {
51711                         enumType_1.flags |= 1024 /* EnumLiteral */;
51712                         enumType_1.symbol = symbol;
51713                     }
51714                     return links.declaredType = enumType_1;
51715                 }
51716             }
51717             var enumType = createType(32 /* Enum */);
51718             enumType.symbol = symbol;
51719             return links.declaredType = enumType;
51720         }
51721         function getDeclaredTypeOfEnumMember(symbol) {
51722             var links = getSymbolLinks(symbol);
51723             if (!links.declaredType) {
51724                 var enumType = getDeclaredTypeOfEnum(getParentOfSymbol(symbol));
51725                 if (!links.declaredType) {
51726                     links.declaredType = enumType;
51727                 }
51728             }
51729             return links.declaredType;
51730         }
51731         function getDeclaredTypeOfTypeParameter(symbol) {
51732             var links = getSymbolLinks(symbol);
51733             return links.declaredType || (links.declaredType = createTypeParameter(symbol));
51734         }
51735         function getDeclaredTypeOfAlias(symbol) {
51736             var links = getSymbolLinks(symbol);
51737             return links.declaredType || (links.declaredType = getDeclaredTypeOfSymbol(resolveAlias(symbol)));
51738         }
51739         function getDeclaredTypeOfSymbol(symbol) {
51740             return tryGetDeclaredTypeOfSymbol(symbol) || errorType;
51741         }
51742         function tryGetDeclaredTypeOfSymbol(symbol) {
51743             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
51744                 return getDeclaredTypeOfClassOrInterface(symbol);
51745             }
51746             if (symbol.flags & 524288 /* TypeAlias */) {
51747                 return getDeclaredTypeOfTypeAlias(symbol);
51748             }
51749             if (symbol.flags & 262144 /* TypeParameter */) {
51750                 return getDeclaredTypeOfTypeParameter(symbol);
51751             }
51752             if (symbol.flags & 384 /* Enum */) {
51753                 return getDeclaredTypeOfEnum(symbol);
51754             }
51755             if (symbol.flags & 8 /* EnumMember */) {
51756                 return getDeclaredTypeOfEnumMember(symbol);
51757             }
51758             if (symbol.flags & 2097152 /* Alias */) {
51759                 return getDeclaredTypeOfAlias(symbol);
51760             }
51761             return undefined;
51762         }
51763         /**
51764          * A type is free of this references if it's the any, string, number, boolean, symbol, or void keyword, a string
51765          * literal type, an array with an element type that is free of this references, or a type reference that is
51766          * free of this references.
51767          */
51768         function isThislessType(node) {
51769             switch (node.kind) {
51770                 case 128 /* AnyKeyword */:
51771                 case 152 /* UnknownKeyword */:
51772                 case 147 /* StringKeyword */:
51773                 case 144 /* NumberKeyword */:
51774                 case 155 /* BigIntKeyword */:
51775                 case 131 /* BooleanKeyword */:
51776                 case 148 /* SymbolKeyword */:
51777                 case 145 /* ObjectKeyword */:
51778                 case 113 /* VoidKeyword */:
51779                 case 150 /* UndefinedKeyword */:
51780                 case 141 /* NeverKeyword */:
51781                 case 191 /* LiteralType */:
51782                     return true;
51783                 case 178 /* ArrayType */:
51784                     return isThislessType(node.elementType);
51785                 case 173 /* TypeReference */:
51786                     return !node.typeArguments || node.typeArguments.every(isThislessType);
51787             }
51788             return false;
51789         }
51790         /** A type parameter is thisless if its constraint is thisless, or if it has no constraint. */
51791         function isThislessTypeParameter(node) {
51792             var constraint = ts.getEffectiveConstraintOfTypeParameter(node);
51793             return !constraint || isThislessType(constraint);
51794         }
51795         /**
51796          * A variable-like declaration is free of this references if it has a type annotation
51797          * that is thisless, or if it has no type annotation and no initializer (and is thus of type any).
51798          */
51799         function isThislessVariableLikeDeclaration(node) {
51800             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
51801             return typeNode ? isThislessType(typeNode) : !ts.hasInitializer(node);
51802         }
51803         /**
51804          * A function-like declaration is considered free of `this` references if it has a return type
51805          * annotation that is free of this references and if each parameter is thisless and if
51806          * each type parameter (if present) is thisless.
51807          */
51808         function isThislessFunctionLikeDeclaration(node) {
51809             var returnType = ts.getEffectiveReturnTypeNode(node);
51810             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
51811             return (node.kind === 166 /* Constructor */ || (!!returnType && isThislessType(returnType))) &&
51812                 node.parameters.every(isThislessVariableLikeDeclaration) &&
51813                 typeParameters.every(isThislessTypeParameter);
51814         }
51815         /**
51816          * Returns true if the class or interface member given by the symbol is free of "this" references. The
51817          * function may return false for symbols that are actually free of "this" references because it is not
51818          * feasible to perform a complete analysis in all cases. In particular, property members with types
51819          * inferred from their initializers and function members with inferred return types are conservatively
51820          * assumed not to be free of "this" references.
51821          */
51822         function isThisless(symbol) {
51823             if (symbol.declarations && symbol.declarations.length === 1) {
51824                 var declaration = symbol.declarations[0];
51825                 if (declaration) {
51826                     switch (declaration.kind) {
51827                         case 163 /* PropertyDeclaration */:
51828                         case 162 /* PropertySignature */:
51829                             return isThislessVariableLikeDeclaration(declaration);
51830                         case 165 /* MethodDeclaration */:
51831                         case 164 /* MethodSignature */:
51832                         case 166 /* Constructor */:
51833                         case 167 /* GetAccessor */:
51834                         case 168 /* SetAccessor */:
51835                             return isThislessFunctionLikeDeclaration(declaration);
51836                     }
51837                 }
51838             }
51839             return false;
51840         }
51841         // The mappingThisOnly flag indicates that the only type parameter being mapped is "this". When the flag is true,
51842         // we check symbols to see if we can quickly conclude they are free of "this" references, thus needing no instantiation.
51843         function createInstantiatedSymbolTable(symbols, mapper, mappingThisOnly) {
51844             var result = ts.createSymbolTable();
51845             for (var _i = 0, symbols_2 = symbols; _i < symbols_2.length; _i++) {
51846                 var symbol = symbols_2[_i];
51847                 result.set(symbol.escapedName, mappingThisOnly && isThisless(symbol) ? symbol : instantiateSymbol(symbol, mapper));
51848             }
51849             return result;
51850         }
51851         function addInheritedMembers(symbols, baseSymbols) {
51852             for (var _i = 0, baseSymbols_1 = baseSymbols; _i < baseSymbols_1.length; _i++) {
51853                 var s = baseSymbols_1[_i];
51854                 if (!symbols.has(s.escapedName) && !isStaticPrivateIdentifierProperty(s)) {
51855                     symbols.set(s.escapedName, s);
51856                 }
51857             }
51858         }
51859         function isStaticPrivateIdentifierProperty(s) {
51860             return !!s.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(s.valueDeclaration) && ts.hasSyntacticModifier(s.valueDeclaration, 32 /* Static */);
51861         }
51862         function resolveDeclaredMembers(type) {
51863             if (!type.declaredProperties) {
51864                 var symbol = type.symbol;
51865                 var members = getMembersOfSymbol(symbol);
51866                 type.declaredProperties = getNamedMembers(members);
51867                 // Start with signatures at empty array in case of recursive types
51868                 type.declaredCallSignatures = ts.emptyArray;
51869                 type.declaredConstructSignatures = ts.emptyArray;
51870                 type.declaredCallSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
51871                 type.declaredConstructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
51872                 type.declaredStringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
51873                 type.declaredNumberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
51874             }
51875             return type;
51876         }
51877         /**
51878          * Indicates whether a type can be used as a property name.
51879          */
51880         function isTypeUsableAsPropertyName(type) {
51881             return !!(type.flags & 8576 /* StringOrNumberLiteralOrUnique */);
51882         }
51883         /**
51884          * Indicates whether a declaration name is definitely late-bindable.
51885          * A declaration name is only late-bindable if:
51886          * - It is a `ComputedPropertyName`.
51887          * - Its expression is an `Identifier` or either a `PropertyAccessExpression` an
51888          * `ElementAccessExpression` consisting only of these same three types of nodes.
51889          * - The type of its expression is a string or numeric literal type, or is a `unique symbol` type.
51890          */
51891         function isLateBindableName(node) {
51892             if (!ts.isComputedPropertyName(node) && !ts.isElementAccessExpression(node)) {
51893                 return false;
51894             }
51895             var expr = ts.isComputedPropertyName(node) ? node.expression : node.argumentExpression;
51896             return ts.isEntityNameExpression(expr)
51897                 && isTypeUsableAsPropertyName(ts.isComputedPropertyName(node) ? checkComputedPropertyName(node) : checkExpressionCached(expr));
51898         }
51899         function isLateBoundName(name) {
51900             return name.charCodeAt(0) === 95 /* _ */ &&
51901                 name.charCodeAt(1) === 95 /* _ */ &&
51902                 name.charCodeAt(2) === 64 /* at */;
51903         }
51904         /**
51905          * Indicates whether a declaration has a late-bindable dynamic name.
51906          */
51907         function hasLateBindableName(node) {
51908             var name = ts.getNameOfDeclaration(node);
51909             return !!name && isLateBindableName(name);
51910         }
51911         /**
51912          * Indicates whether a declaration has a dynamic name that cannot be late-bound.
51913          */
51914         function hasNonBindableDynamicName(node) {
51915             return ts.hasDynamicName(node) && !hasLateBindableName(node);
51916         }
51917         /**
51918          * Indicates whether a declaration name is a dynamic name that cannot be late-bound.
51919          */
51920         function isNonBindableDynamicName(node) {
51921             return ts.isDynamicName(node) && !isLateBindableName(node);
51922         }
51923         /**
51924          * Gets the symbolic name for a member from its type.
51925          */
51926         function getPropertyNameFromType(type) {
51927             if (type.flags & 8192 /* UniqueESSymbol */) {
51928                 return type.escapedName;
51929             }
51930             if (type.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
51931                 return ts.escapeLeadingUnderscores("" + type.value);
51932             }
51933             return ts.Debug.fail();
51934         }
51935         /**
51936          * Adds a declaration to a late-bound dynamic member. This performs the same function for
51937          * late-bound members that `addDeclarationToSymbol` in binder.ts performs for early-bound
51938          * members.
51939          */
51940         function addDeclarationToLateBoundSymbol(symbol, member, symbolFlags) {
51941             ts.Debug.assert(!!(ts.getCheckFlags(symbol) & 4096 /* Late */), "Expected a late-bound symbol.");
51942             symbol.flags |= symbolFlags;
51943             getSymbolLinks(member.symbol).lateSymbol = symbol;
51944             if (!symbol.declarations) {
51945                 symbol.declarations = [member];
51946             }
51947             else {
51948                 symbol.declarations.push(member);
51949             }
51950             if (symbolFlags & 111551 /* Value */) {
51951                 if (!symbol.valueDeclaration || symbol.valueDeclaration.kind !== member.kind) {
51952                     symbol.valueDeclaration = member;
51953                 }
51954             }
51955         }
51956         /**
51957          * Performs late-binding of a dynamic member. This performs the same function for
51958          * late-bound members that `declareSymbol` in binder.ts performs for early-bound
51959          * members.
51960          *
51961          * If a symbol is a dynamic name from a computed property, we perform an additional "late"
51962          * binding phase to attempt to resolve the name for the symbol from the type of the computed
51963          * property's expression. If the type of the expression is a string-literal, numeric-literal,
51964          * or unique symbol type, we can use that type as the name of the symbol.
51965          *
51966          * For example, given:
51967          *
51968          *   const x = Symbol();
51969          *
51970          *   interface I {
51971          *     [x]: number;
51972          *   }
51973          *
51974          * The binder gives the property `[x]: number` a special symbol with the name "__computed".
51975          * In the late-binding phase we can type-check the expression `x` and see that it has a
51976          * unique symbol type which we can then use as the name of the member. This allows users
51977          * to define custom symbols that can be used in the members of an object type.
51978          *
51979          * @param parent The containing symbol for the member.
51980          * @param earlySymbols The early-bound symbols of the parent.
51981          * @param lateSymbols The late-bound symbols of the parent.
51982          * @param decl The member to bind.
51983          */
51984         function lateBindMember(parent, earlySymbols, lateSymbols, decl) {
51985             ts.Debug.assert(!!decl.symbol, "The member is expected to have a symbol.");
51986             var links = getNodeLinks(decl);
51987             if (!links.resolvedSymbol) {
51988                 // In the event we attempt to resolve the late-bound name of this member recursively,
51989                 // fall back to the early-bound name of this member.
51990                 links.resolvedSymbol = decl.symbol;
51991                 var declName = ts.isBinaryExpression(decl) ? decl.left : decl.name;
51992                 var type = ts.isElementAccessExpression(declName) ? checkExpressionCached(declName.argumentExpression) : checkComputedPropertyName(declName);
51993                 if (isTypeUsableAsPropertyName(type)) {
51994                     var memberName = getPropertyNameFromType(type);
51995                     var symbolFlags = decl.symbol.flags;
51996                     // Get or add a late-bound symbol for the member. This allows us to merge late-bound accessor declarations.
51997                     var lateSymbol = lateSymbols.get(memberName);
51998                     if (!lateSymbol)
51999                         lateSymbols.set(memberName, lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */));
52000                     // Report an error if a late-bound member has the same name as an early-bound member,
52001                     // or if we have another early-bound symbol declaration with the same name and
52002                     // conflicting flags.
52003                     var earlySymbol = earlySymbols && earlySymbols.get(memberName);
52004                     if (lateSymbol.flags & getExcludedSymbolFlags(symbolFlags) || earlySymbol) {
52005                         // If we have an existing early-bound member, combine its declarations so that we can
52006                         // report an error at each declaration.
52007                         var declarations = earlySymbol ? ts.concatenate(earlySymbol.declarations, lateSymbol.declarations) : lateSymbol.declarations;
52008                         var name_4 = !(type.flags & 8192 /* UniqueESSymbol */) && ts.unescapeLeadingUnderscores(memberName) || ts.declarationNameToString(declName);
52009                         ts.forEach(declarations, function (declaration) { return error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Property_0_was_also_declared_here, name_4); });
52010                         error(declName || decl, ts.Diagnostics.Duplicate_property_0, name_4);
52011                         lateSymbol = createSymbol(0 /* None */, memberName, 4096 /* Late */);
52012                     }
52013                     lateSymbol.nameType = type;
52014                     addDeclarationToLateBoundSymbol(lateSymbol, decl, symbolFlags);
52015                     if (lateSymbol.parent) {
52016                         ts.Debug.assert(lateSymbol.parent === parent, "Existing symbol parent should match new one");
52017                     }
52018                     else {
52019                         lateSymbol.parent = parent;
52020                     }
52021                     return links.resolvedSymbol = lateSymbol;
52022                 }
52023             }
52024             return links.resolvedSymbol;
52025         }
52026         function getResolvedMembersOrExportsOfSymbol(symbol, resolutionKind) {
52027             var links = getSymbolLinks(symbol);
52028             if (!links[resolutionKind]) {
52029                 var isStatic = resolutionKind === "resolvedExports" /* resolvedExports */;
52030                 var earlySymbols = !isStatic ? symbol.members :
52031                     symbol.flags & 1536 /* Module */ ? getExportsOfModuleWorker(symbol) :
52032                         symbol.exports;
52033                 // In the event we recursively resolve the members/exports of the symbol, we
52034                 // set the initial value of resolvedMembers/resolvedExports to the early-bound
52035                 // members/exports of the symbol.
52036                 links[resolutionKind] = earlySymbols || emptySymbols;
52037                 // fill in any as-yet-unresolved late-bound members.
52038                 var lateSymbols = ts.createSymbolTable();
52039                 for (var _i = 0, _a = symbol.declarations || ts.emptyArray; _i < _a.length; _i++) {
52040                     var decl = _a[_i];
52041                     var members = ts.getMembersOfDeclaration(decl);
52042                     if (members) {
52043                         for (var _b = 0, members_5 = members; _b < members_5.length; _b++) {
52044                             var member = members_5[_b];
52045                             if (isStatic === ts.hasStaticModifier(member) && hasLateBindableName(member)) {
52046                                 lateBindMember(symbol, earlySymbols, lateSymbols, member);
52047                             }
52048                         }
52049                     }
52050                 }
52051                 var assignments = symbol.assignmentDeclarationMembers;
52052                 if (assignments) {
52053                     var decls = ts.arrayFrom(assignments.values());
52054                     for (var _c = 0, decls_1 = decls; _c < decls_1.length; _c++) {
52055                         var member = decls_1[_c];
52056                         var assignmentKind = ts.getAssignmentDeclarationKind(member);
52057                         var isInstanceMember = assignmentKind === 3 /* PrototypeProperty */
52058                             || ts.isBinaryExpression(member) && isPossiblyAliasedThisProperty(member, assignmentKind)
52059                             || assignmentKind === 9 /* ObjectDefinePrototypeProperty */
52060                             || assignmentKind === 6 /* Prototype */; // A straight `Prototype` assignment probably can never have a computed name
52061                         if (isStatic === !isInstanceMember && hasLateBindableName(member)) {
52062                             lateBindMember(symbol, earlySymbols, lateSymbols, member);
52063                         }
52064                     }
52065                 }
52066                 links[resolutionKind] = combineSymbolTables(earlySymbols, lateSymbols) || emptySymbols;
52067             }
52068             return links[resolutionKind];
52069         }
52070         /**
52071          * Gets a SymbolTable containing both the early- and late-bound members of a symbol.
52072          *
52073          * For a description of late-binding, see `lateBindMember`.
52074          */
52075         function getMembersOfSymbol(symbol) {
52076             return symbol.flags & 6256 /* LateBindingContainer */
52077                 ? getResolvedMembersOrExportsOfSymbol(symbol, "resolvedMembers" /* resolvedMembers */)
52078                 : symbol.members || emptySymbols;
52079         }
52080         /**
52081          * If a symbol is the dynamic name of the member of an object type, get the late-bound
52082          * symbol of the member.
52083          *
52084          * For a description of late-binding, see `lateBindMember`.
52085          */
52086         function getLateBoundSymbol(symbol) {
52087             if (symbol.flags & 106500 /* ClassMember */ && symbol.escapedName === "__computed" /* Computed */) {
52088                 var links = getSymbolLinks(symbol);
52089                 if (!links.lateSymbol && ts.some(symbol.declarations, hasLateBindableName)) {
52090                     // force late binding of members/exports. This will set the late-bound symbol
52091                     var parent = getMergedSymbol(symbol.parent);
52092                     if (ts.some(symbol.declarations, ts.hasStaticModifier)) {
52093                         getExportsOfSymbol(parent);
52094                     }
52095                     else {
52096                         getMembersOfSymbol(parent);
52097                     }
52098                 }
52099                 return links.lateSymbol || (links.lateSymbol = symbol);
52100             }
52101             return symbol;
52102         }
52103         function getTypeWithThisArgument(type, thisArgument, needApparentType) {
52104             if (ts.getObjectFlags(type) & 4 /* Reference */) {
52105                 var target = type.target;
52106                 var typeArguments = getTypeArguments(type);
52107                 if (ts.length(target.typeParameters) === ts.length(typeArguments)) {
52108                     var ref = createTypeReference(target, ts.concatenate(typeArguments, [thisArgument || target.thisType]));
52109                     return needApparentType ? getApparentType(ref) : ref;
52110                 }
52111             }
52112             else if (type.flags & 2097152 /* Intersection */) {
52113                 return getIntersectionType(ts.map(type.types, function (t) { return getTypeWithThisArgument(t, thisArgument, needApparentType); }));
52114             }
52115             return needApparentType ? getApparentType(type) : type;
52116         }
52117         function resolveObjectTypeMembers(type, source, typeParameters, typeArguments) {
52118             var mapper;
52119             var members;
52120             var callSignatures;
52121             var constructSignatures;
52122             var stringIndexInfo;
52123             var numberIndexInfo;
52124             if (ts.rangeEquals(typeParameters, typeArguments, 0, typeParameters.length)) {
52125                 members = source.symbol ? getMembersOfSymbol(source.symbol) : ts.createSymbolTable(source.declaredProperties);
52126                 callSignatures = source.declaredCallSignatures;
52127                 constructSignatures = source.declaredConstructSignatures;
52128                 stringIndexInfo = source.declaredStringIndexInfo;
52129                 numberIndexInfo = source.declaredNumberIndexInfo;
52130             }
52131             else {
52132                 mapper = createTypeMapper(typeParameters, typeArguments);
52133                 members = createInstantiatedSymbolTable(source.declaredProperties, mapper, /*mappingThisOnly*/ typeParameters.length === 1);
52134                 callSignatures = instantiateSignatures(source.declaredCallSignatures, mapper);
52135                 constructSignatures = instantiateSignatures(source.declaredConstructSignatures, mapper);
52136                 stringIndexInfo = instantiateIndexInfo(source.declaredStringIndexInfo, mapper);
52137                 numberIndexInfo = instantiateIndexInfo(source.declaredNumberIndexInfo, mapper);
52138             }
52139             var baseTypes = getBaseTypes(source);
52140             if (baseTypes.length) {
52141                 if (source.symbol && members === getMembersOfSymbol(source.symbol)) {
52142                     members = ts.createSymbolTable(source.declaredProperties);
52143                 }
52144                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52145                 var thisArgument = ts.lastOrUndefined(typeArguments);
52146                 for (var _i = 0, baseTypes_1 = baseTypes; _i < baseTypes_1.length; _i++) {
52147                     var baseType = baseTypes_1[_i];
52148                     var instantiatedBaseType = thisArgument ? getTypeWithThisArgument(instantiateType(baseType, mapper), thisArgument) : baseType;
52149                     addInheritedMembers(members, getPropertiesOfType(instantiatedBaseType));
52150                     callSignatures = ts.concatenate(callSignatures, getSignaturesOfType(instantiatedBaseType, 0 /* Call */));
52151                     constructSignatures = ts.concatenate(constructSignatures, getSignaturesOfType(instantiatedBaseType, 1 /* Construct */));
52152                     if (!stringIndexInfo) {
52153                         stringIndexInfo = instantiatedBaseType === anyType ?
52154                             createIndexInfo(anyType, /*isReadonly*/ false) :
52155                             getIndexInfoOfType(instantiatedBaseType, 0 /* String */);
52156                     }
52157                     numberIndexInfo = numberIndexInfo || getIndexInfoOfType(instantiatedBaseType, 1 /* Number */);
52158                 }
52159             }
52160             setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52161         }
52162         function resolveClassOrInterfaceMembers(type) {
52163             resolveObjectTypeMembers(type, resolveDeclaredMembers(type), ts.emptyArray, ts.emptyArray);
52164         }
52165         function resolveTypeReferenceMembers(type) {
52166             var source = resolveDeclaredMembers(type.target);
52167             var typeParameters = ts.concatenate(source.typeParameters, [source.thisType]);
52168             var typeArguments = getTypeArguments(type);
52169             var paddedTypeArguments = typeArguments.length === typeParameters.length ? typeArguments : ts.concatenate(typeArguments, [type]);
52170             resolveObjectTypeMembers(type, source, typeParameters, paddedTypeArguments);
52171         }
52172         function createSignature(declaration, typeParameters, thisParameter, parameters, resolvedReturnType, resolvedTypePredicate, minArgumentCount, flags) {
52173             var sig = new Signature(checker, flags);
52174             sig.declaration = declaration;
52175             sig.typeParameters = typeParameters;
52176             sig.parameters = parameters;
52177             sig.thisParameter = thisParameter;
52178             sig.resolvedReturnType = resolvedReturnType;
52179             sig.resolvedTypePredicate = resolvedTypePredicate;
52180             sig.minArgumentCount = minArgumentCount;
52181             sig.resolvedMinArgumentCount = undefined;
52182             sig.target = undefined;
52183             sig.mapper = undefined;
52184             sig.unionSignatures = undefined;
52185             return sig;
52186         }
52187         function cloneSignature(sig) {
52188             var result = createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, /*resolvedReturnType*/ undefined, 
52189             /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 19 /* PropagatingFlags */);
52190             result.target = sig.target;
52191             result.mapper = sig.mapper;
52192             result.unionSignatures = sig.unionSignatures;
52193             return result;
52194         }
52195         function createUnionSignature(signature, unionSignatures) {
52196             var result = cloneSignature(signature);
52197             result.unionSignatures = unionSignatures;
52198             result.target = undefined;
52199             result.mapper = undefined;
52200             return result;
52201         }
52202         function getOptionalCallSignature(signature, callChainFlags) {
52203             if ((signature.flags & 12 /* CallChainFlags */) === callChainFlags) {
52204                 return signature;
52205             }
52206             if (!signature.optionalCallSignatureCache) {
52207                 signature.optionalCallSignatureCache = {};
52208             }
52209             var key = callChainFlags === 4 /* IsInnerCallChain */ ? "inner" : "outer";
52210             return signature.optionalCallSignatureCache[key]
52211                 || (signature.optionalCallSignatureCache[key] = createOptionalCallSignature(signature, callChainFlags));
52212         }
52213         function createOptionalCallSignature(signature, callChainFlags) {
52214             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.");
52215             var result = cloneSignature(signature);
52216             result.flags |= callChainFlags;
52217             return result;
52218         }
52219         function getExpandedParameters(sig, skipUnionExpanding) {
52220             if (signatureHasRestParameter(sig)) {
52221                 var restIndex_1 = sig.parameters.length - 1;
52222                 var restType = getTypeOfSymbol(sig.parameters[restIndex_1]);
52223                 if (isTupleType(restType)) {
52224                     return [expandSignatureParametersWithTupleMembers(restType, restIndex_1)];
52225                 }
52226                 else if (!skipUnionExpanding && restType.flags & 1048576 /* Union */ && ts.every(restType.types, isTupleType)) {
52227                     return ts.map(restType.types, function (t) { return expandSignatureParametersWithTupleMembers(t, restIndex_1); });
52228                 }
52229             }
52230             return [sig.parameters];
52231             function expandSignatureParametersWithTupleMembers(restType, restIndex) {
52232                 var elementTypes = getTypeArguments(restType);
52233                 var associatedNames = restType.target.labeledElementDeclarations;
52234                 var restParams = ts.map(elementTypes, function (t, i) {
52235                     // Lookup the label from the individual tuple passed in before falling back to the signature `rest` parameter name
52236                     var tupleLabelName = !!associatedNames && getTupleElementLabel(associatedNames[i]);
52237                     var name = tupleLabelName || getParameterNameAtPosition(sig, restIndex + i, restType);
52238                     var flags = restType.target.elementFlags[i];
52239                     var checkFlags = flags & 12 /* Variable */ ? 32768 /* RestParameter */ :
52240                         flags & 2 /* Optional */ ? 16384 /* OptionalParameter */ : 0;
52241                     var symbol = createSymbol(1 /* FunctionScopedVariable */, name, checkFlags);
52242                     symbol.type = flags & 4 /* Rest */ ? createArrayType(t) : t;
52243                     return symbol;
52244                 });
52245                 return ts.concatenate(sig.parameters.slice(0, restIndex), restParams);
52246             }
52247         }
52248         function getDefaultConstructSignatures(classType) {
52249             var baseConstructorType = getBaseConstructorTypeOfClass(classType);
52250             var baseSignatures = getSignaturesOfType(baseConstructorType, 1 /* Construct */);
52251             if (baseSignatures.length === 0) {
52252                 return [createSignature(undefined, classType.localTypeParameters, undefined, ts.emptyArray, classType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */)];
52253             }
52254             var baseTypeNode = getBaseTypeNodeOfClass(classType);
52255             var isJavaScript = ts.isInJSFile(baseTypeNode);
52256             var typeArguments = typeArgumentsFromTypeReferenceNode(baseTypeNode);
52257             var typeArgCount = ts.length(typeArguments);
52258             var result = [];
52259             for (var _i = 0, baseSignatures_1 = baseSignatures; _i < baseSignatures_1.length; _i++) {
52260                 var baseSig = baseSignatures_1[_i];
52261                 var minTypeArgumentCount = getMinTypeArgumentCount(baseSig.typeParameters);
52262                 var typeParamCount = ts.length(baseSig.typeParameters);
52263                 if (isJavaScript || typeArgCount >= minTypeArgumentCount && typeArgCount <= typeParamCount) {
52264                     var sig = typeParamCount ? createSignatureInstantiation(baseSig, fillMissingTypeArguments(typeArguments, baseSig.typeParameters, minTypeArgumentCount, isJavaScript)) : cloneSignature(baseSig);
52265                     sig.typeParameters = classType.localTypeParameters;
52266                     sig.resolvedReturnType = classType;
52267                     result.push(sig);
52268                 }
52269             }
52270             return result;
52271         }
52272         function findMatchingSignature(signatureList, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes) {
52273             for (var _i = 0, signatureList_1 = signatureList; _i < signatureList_1.length; _i++) {
52274                 var s = signatureList_1[_i];
52275                 if (compareSignaturesIdentical(s, signature, partialMatch, ignoreThisTypes, ignoreReturnTypes, partialMatch ? compareTypesSubtypeOf : compareTypesIdentical)) {
52276                     return s;
52277                 }
52278             }
52279         }
52280         function findMatchingSignatures(signatureLists, signature, listIndex) {
52281             if (signature.typeParameters) {
52282                 // We require an exact match for generic signatures, so we only return signatures from the first
52283                 // signature list and only if they have exact matches in the other signature lists.
52284                 if (listIndex > 0) {
52285                     return undefined;
52286                 }
52287                 for (var i = 1; i < signatureLists.length; i++) {
52288                     if (!findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false)) {
52289                         return undefined;
52290                     }
52291                 }
52292                 return [signature];
52293             }
52294             var result;
52295             for (var i = 0; i < signatureLists.length; i++) {
52296                 // Allow matching non-generic signatures to have excess parameters and different return types.
52297                 // Prefer matching this types if possible.
52298                 var match = i === listIndex ? signature : findMatchingSignature(signatureLists[i], signature, /*partialMatch*/ true, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true);
52299                 if (!match) {
52300                     return undefined;
52301                 }
52302                 result = ts.appendIfUnique(result, match);
52303             }
52304             return result;
52305         }
52306         // The signatures of a union type are those signatures that are present in each of the constituent types.
52307         // Generic signatures must match exactly, but non-generic signatures are allowed to have extra optional
52308         // parameters and may differ in return types. When signatures differ in return types, the resulting return
52309         // type is the union of the constituent return types.
52310         function getUnionSignatures(signatureLists) {
52311             var result;
52312             var indexWithLengthOverOne;
52313             for (var i = 0; i < signatureLists.length; i++) {
52314                 if (signatureLists[i].length === 0)
52315                     return ts.emptyArray;
52316                 if (signatureLists[i].length > 1) {
52317                     indexWithLengthOverOne = indexWithLengthOverOne === undefined ? i : -1; // -1 is a signal there are multiple overload sets
52318                 }
52319                 for (var _i = 0, _a = signatureLists[i]; _i < _a.length; _i++) {
52320                     var signature = _a[_i];
52321                     // Only process signatures with parameter lists that aren't already in the result list
52322                     if (!result || !findMatchingSignature(result, signature, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ true)) {
52323                         var unionSignatures = findMatchingSignatures(signatureLists, signature, i);
52324                         if (unionSignatures) {
52325                             var s = signature;
52326                             // Union the result types when more than one signature matches
52327                             if (unionSignatures.length > 1) {
52328                                 var thisParameter = signature.thisParameter;
52329                                 var firstThisParameterOfUnionSignatures = ts.forEach(unionSignatures, function (sig) { return sig.thisParameter; });
52330                                 if (firstThisParameterOfUnionSignatures) {
52331                                     var thisType = getIntersectionType(ts.mapDefined(unionSignatures, function (sig) { return sig.thisParameter && getTypeOfSymbol(sig.thisParameter); }));
52332                                     thisParameter = createSymbolWithType(firstThisParameterOfUnionSignatures, thisType);
52333                                 }
52334                                 s = createUnionSignature(signature, unionSignatures);
52335                                 s.thisParameter = thisParameter;
52336                             }
52337                             (result || (result = [])).push(s);
52338                         }
52339                     }
52340                 }
52341             }
52342             if (!ts.length(result) && indexWithLengthOverOne !== -1) {
52343                 // No sufficiently similar signature existed to subsume all the other signatures in the union - time to see if we can make a single
52344                 // signature that handles all over them. We only do this when there are overloads in only one constituent.
52345                 // (Overloads are conditional in nature and having overloads in multiple constituents would necessitate making a power set of
52346                 // signatures from the type, whose ordering would be non-obvious)
52347                 var masterList = signatureLists[indexWithLengthOverOne !== undefined ? indexWithLengthOverOne : 0];
52348                 var results = masterList.slice();
52349                 var _loop_10 = function (signatures) {
52350                     if (signatures !== masterList) {
52351                         var signature_1 = signatures[0];
52352                         ts.Debug.assert(!!signature_1, "getUnionSignatures bails early on empty signature lists and should not have empty lists on second pass");
52353                         results = signature_1.typeParameters && ts.some(results, function (s) { return !!s.typeParameters; }) ? undefined : ts.map(results, function (sig) { return combineSignaturesOfUnionMembers(sig, signature_1); });
52354                         if (!results) {
52355                             return "break";
52356                         }
52357                     }
52358                 };
52359                 for (var _b = 0, signatureLists_1 = signatureLists; _b < signatureLists_1.length; _b++) {
52360                     var signatures = signatureLists_1[_b];
52361                     var state_3 = _loop_10(signatures);
52362                     if (state_3 === "break")
52363                         break;
52364                 }
52365                 result = results;
52366             }
52367             return result || ts.emptyArray;
52368         }
52369         function combineUnionThisParam(left, right) {
52370             if (!left || !right) {
52371                 return left || right;
52372             }
52373             // A signature `this` type might be a read or a write position... It's very possible that it should be invariant
52374             // and we should refuse to merge signatures if there are `this` types and they do not match. However, so as to be
52375             // permissive when calling, for now, we'll intersect the `this` types just like we do for param types in union signatures.
52376             var thisType = getIntersectionType([getTypeOfSymbol(left), getTypeOfSymbol(right)]);
52377             return createSymbolWithType(left, thisType);
52378         }
52379         function combineUnionParameters(left, right) {
52380             var leftCount = getParameterCount(left);
52381             var rightCount = getParameterCount(right);
52382             var longest = leftCount >= rightCount ? left : right;
52383             var shorter = longest === left ? right : left;
52384             var longestCount = longest === left ? leftCount : rightCount;
52385             var eitherHasEffectiveRest = (hasEffectiveRestParameter(left) || hasEffectiveRestParameter(right));
52386             var needsExtraRestElement = eitherHasEffectiveRest && !hasEffectiveRestParameter(longest);
52387             var params = new Array(longestCount + (needsExtraRestElement ? 1 : 0));
52388             for (var i = 0; i < longestCount; i++) {
52389                 var longestParamType = tryGetTypeAtPosition(longest, i);
52390                 var shorterParamType = tryGetTypeAtPosition(shorter, i) || unknownType;
52391                 var unionParamType = getIntersectionType([longestParamType, shorterParamType]);
52392                 var isRestParam = eitherHasEffectiveRest && !needsExtraRestElement && i === (longestCount - 1);
52393                 var isOptional = i >= getMinArgumentCount(longest) && i >= getMinArgumentCount(shorter);
52394                 var leftName = i >= leftCount ? undefined : getParameterNameAtPosition(left, i);
52395                 var rightName = i >= rightCount ? undefined : getParameterNameAtPosition(right, i);
52396                 var paramName = leftName === rightName ? leftName :
52397                     !leftName ? rightName :
52398                         !rightName ? leftName :
52399                             undefined;
52400                 var paramSymbol = createSymbol(1 /* FunctionScopedVariable */ | (isOptional && !isRestParam ? 16777216 /* Optional */ : 0), paramName || "arg" + i);
52401                 paramSymbol.type = isRestParam ? createArrayType(unionParamType) : unionParamType;
52402                 params[i] = paramSymbol;
52403             }
52404             if (needsExtraRestElement) {
52405                 var restParamSymbol = createSymbol(1 /* FunctionScopedVariable */, "args");
52406                 restParamSymbol.type = createArrayType(getTypeAtPosition(shorter, longestCount));
52407                 params[longestCount] = restParamSymbol;
52408             }
52409             return params;
52410         }
52411         function combineSignaturesOfUnionMembers(left, right) {
52412             var declaration = left.declaration;
52413             var params = combineUnionParameters(left, right);
52414             var thisParam = combineUnionThisParam(left.thisParameter, right.thisParameter);
52415             var minArgCount = Math.max(left.minArgumentCount, right.minArgumentCount);
52416             var result = createSignature(declaration, left.typeParameters || right.typeParameters, thisParam, params, 
52417             /*resolvedReturnType*/ undefined, 
52418             /*resolvedTypePredicate*/ undefined, minArgCount, (left.flags | right.flags) & 19 /* PropagatingFlags */);
52419             result.unionSignatures = ts.concatenate(left.unionSignatures || [left], [right]);
52420             return result;
52421         }
52422         function getUnionIndexInfo(types, kind) {
52423             var indexTypes = [];
52424             var isAnyReadonly = false;
52425             for (var _i = 0, types_4 = types; _i < types_4.length; _i++) {
52426                 var type = types_4[_i];
52427                 var indexInfo = getIndexInfoOfType(getApparentType(type), kind);
52428                 if (!indexInfo) {
52429                     return undefined;
52430                 }
52431                 indexTypes.push(indexInfo.type);
52432                 isAnyReadonly = isAnyReadonly || indexInfo.isReadonly;
52433             }
52434             return createIndexInfo(getUnionType(indexTypes, 2 /* Subtype */), isAnyReadonly);
52435         }
52436         function resolveUnionTypeMembers(type) {
52437             // The members and properties collections are empty for union types. To get all properties of a union
52438             // type use getPropertiesOfType (only the language service uses this).
52439             var callSignatures = getUnionSignatures(ts.map(type.types, function (t) { return t === globalFunctionType ? [unknownSignature] : getSignaturesOfType(t, 0 /* Call */); }));
52440             var constructSignatures = getUnionSignatures(ts.map(type.types, function (t) { return getSignaturesOfType(t, 1 /* Construct */); }));
52441             var stringIndexInfo = getUnionIndexInfo(type.types, 0 /* String */);
52442             var numberIndexInfo = getUnionIndexInfo(type.types, 1 /* Number */);
52443             setStructuredTypeMembers(type, emptySymbols, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52444         }
52445         function intersectTypes(type1, type2) {
52446             return !type1 ? type2 : !type2 ? type1 : getIntersectionType([type1, type2]);
52447         }
52448         function intersectIndexInfos(info1, info2) {
52449             return !info1 ? info2 : !info2 ? info1 : createIndexInfo(getIntersectionType([info1.type, info2.type]), info1.isReadonly && info2.isReadonly);
52450         }
52451         function unionSpreadIndexInfos(info1, info2) {
52452             return info1 && info2 && createIndexInfo(getUnionType([info1.type, info2.type]), info1.isReadonly || info2.isReadonly);
52453         }
52454         function findMixins(types) {
52455             var constructorTypeCount = ts.countWhere(types, function (t) { return getSignaturesOfType(t, 1 /* Construct */).length > 0; });
52456             var mixinFlags = ts.map(types, isMixinConstructorType);
52457             if (constructorTypeCount > 0 && constructorTypeCount === ts.countWhere(mixinFlags, function (b) { return b; })) {
52458                 var firstMixinIndex = mixinFlags.indexOf(/*searchElement*/ true);
52459                 mixinFlags[firstMixinIndex] = false;
52460             }
52461             return mixinFlags;
52462         }
52463         function includeMixinType(type, types, mixinFlags, index) {
52464             var mixedTypes = [];
52465             for (var i = 0; i < types.length; i++) {
52466                 if (i === index) {
52467                     mixedTypes.push(type);
52468                 }
52469                 else if (mixinFlags[i]) {
52470                     mixedTypes.push(getReturnTypeOfSignature(getSignaturesOfType(types[i], 1 /* Construct */)[0]));
52471                 }
52472             }
52473             return getIntersectionType(mixedTypes);
52474         }
52475         function resolveIntersectionTypeMembers(type) {
52476             // The members and properties collections are empty for intersection types. To get all properties of an
52477             // intersection type use getPropertiesOfType (only the language service uses this).
52478             var callSignatures;
52479             var constructSignatures;
52480             var stringIndexInfo;
52481             var numberIndexInfo;
52482             var types = type.types;
52483             var mixinFlags = findMixins(types);
52484             var mixinCount = ts.countWhere(mixinFlags, function (b) { return b; });
52485             var _loop_11 = function (i) {
52486                 var t = type.types[i];
52487                 // When an intersection type contains mixin constructor types, the construct signatures from
52488                 // those types are discarded and their return types are mixed into the return types of all
52489                 // other construct signatures in the intersection type. For example, the intersection type
52490                 // '{ new(...args: any[]) => A } & { new(s: string) => B }' has a single construct signature
52491                 // 'new(s: string) => A & B'.
52492                 if (!mixinFlags[i]) {
52493                     var signatures = getSignaturesOfType(t, 1 /* Construct */);
52494                     if (signatures.length && mixinCount > 0) {
52495                         signatures = ts.map(signatures, function (s) {
52496                             var clone = cloneSignature(s);
52497                             clone.resolvedReturnType = includeMixinType(getReturnTypeOfSignature(s), types, mixinFlags, i);
52498                             return clone;
52499                         });
52500                     }
52501                     constructSignatures = appendSignatures(constructSignatures, signatures);
52502                 }
52503                 callSignatures = appendSignatures(callSignatures, getSignaturesOfType(t, 0 /* Call */));
52504                 stringIndexInfo = intersectIndexInfos(stringIndexInfo, getIndexInfoOfType(t, 0 /* String */));
52505                 numberIndexInfo = intersectIndexInfos(numberIndexInfo, getIndexInfoOfType(t, 1 /* Number */));
52506             };
52507             for (var i = 0; i < types.length; i++) {
52508                 _loop_11(i);
52509             }
52510             setStructuredTypeMembers(type, emptySymbols, callSignatures || ts.emptyArray, constructSignatures || ts.emptyArray, stringIndexInfo, numberIndexInfo);
52511         }
52512         function appendSignatures(signatures, newSignatures) {
52513             var _loop_12 = function (sig) {
52514                 if (!signatures || ts.every(signatures, function (s) { return !compareSignaturesIdentical(s, sig, /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, compareTypesIdentical); })) {
52515                     signatures = ts.append(signatures, sig);
52516                 }
52517             };
52518             for (var _i = 0, newSignatures_1 = newSignatures; _i < newSignatures_1.length; _i++) {
52519                 var sig = newSignatures_1[_i];
52520                 _loop_12(sig);
52521             }
52522             return signatures;
52523         }
52524         /**
52525          * Converts an AnonymousType to a ResolvedType.
52526          */
52527         function resolveAnonymousTypeMembers(type) {
52528             var symbol = getMergedSymbol(type.symbol);
52529             if (type.target) {
52530                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
52531                 var members = createInstantiatedSymbolTable(getPropertiesOfObjectType(type.target), type.mapper, /*mappingThisOnly*/ false);
52532                 var callSignatures = instantiateSignatures(getSignaturesOfType(type.target, 0 /* Call */), type.mapper);
52533                 var constructSignatures = instantiateSignatures(getSignaturesOfType(type.target, 1 /* Construct */), type.mapper);
52534                 var stringIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 0 /* String */), type.mapper);
52535                 var numberIndexInfo = instantiateIndexInfo(getIndexInfoOfType(type.target, 1 /* Number */), type.mapper);
52536                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52537             }
52538             else if (symbol.flags & 2048 /* TypeLiteral */) {
52539                 setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
52540                 var members = getMembersOfSymbol(symbol);
52541                 var callSignatures = getSignaturesOfSymbol(members.get("__call" /* Call */));
52542                 var constructSignatures = getSignaturesOfSymbol(members.get("__new" /* New */));
52543                 var stringIndexInfo = getIndexInfoOfSymbol(symbol, 0 /* String */);
52544                 var numberIndexInfo = getIndexInfoOfSymbol(symbol, 1 /* Number */);
52545                 setStructuredTypeMembers(type, members, callSignatures, constructSignatures, stringIndexInfo, numberIndexInfo);
52546             }
52547             else {
52548                 // Combinations of function, class, enum and module
52549                 var members = emptySymbols;
52550                 var stringIndexInfo = void 0;
52551                 if (symbol.exports) {
52552                     members = getExportsOfSymbol(symbol);
52553                     if (symbol === globalThisSymbol) {
52554                         var varsOnly_1 = new ts.Map();
52555                         members.forEach(function (p) {
52556                             if (!(p.flags & 418 /* BlockScoped */)) {
52557                                 varsOnly_1.set(p.escapedName, p);
52558                             }
52559                         });
52560                         members = varsOnly_1;
52561                     }
52562                 }
52563                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, undefined, undefined);
52564                 if (symbol.flags & 32 /* Class */) {
52565                     var classType = getDeclaredTypeOfClassOrInterface(symbol);
52566                     var baseConstructorType = getBaseConstructorTypeOfClass(classType);
52567                     if (baseConstructorType.flags & (524288 /* Object */ | 2097152 /* Intersection */ | 8650752 /* TypeVariable */)) {
52568                         members = ts.createSymbolTable(getNamedMembers(members));
52569                         addInheritedMembers(members, getPropertiesOfType(baseConstructorType));
52570                     }
52571                     else if (baseConstructorType === anyType) {
52572                         stringIndexInfo = createIndexInfo(anyType, /*isReadonly*/ false);
52573                     }
52574                 }
52575                 var numberIndexInfo = symbol.flags & 384 /* Enum */ && (getDeclaredTypeOfSymbol(symbol).flags & 32 /* Enum */ ||
52576                     ts.some(type.properties, function (prop) { return !!(getTypeOfSymbol(prop).flags & 296 /* NumberLike */); })) ? enumNumberIndexInfo : undefined;
52577                 setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
52578                 // We resolve the members before computing the signatures because a signature may use
52579                 // typeof with a qualified name expression that circularly references the type we are
52580                 // in the process of resolving (see issue #6072). The temporarily empty signature list
52581                 // will never be observed because a qualified name can't reference signatures.
52582                 if (symbol.flags & (16 /* Function */ | 8192 /* Method */)) {
52583                     type.callSignatures = getSignaturesOfSymbol(symbol);
52584                 }
52585                 // And likewise for construct signatures for classes
52586                 if (symbol.flags & 32 /* Class */) {
52587                     var classType_1 = getDeclaredTypeOfClassOrInterface(symbol);
52588                     var constructSignatures = symbol.members ? getSignaturesOfSymbol(symbol.members.get("__constructor" /* Constructor */)) : ts.emptyArray;
52589                     if (symbol.flags & 16 /* Function */) {
52590                         constructSignatures = ts.addRange(constructSignatures.slice(), ts.mapDefined(type.callSignatures, function (sig) { return isJSConstructor(sig.declaration) ?
52591                             createSignature(sig.declaration, sig.typeParameters, sig.thisParameter, sig.parameters, classType_1, /*resolvedTypePredicate*/ undefined, sig.minArgumentCount, sig.flags & 19 /* PropagatingFlags */) :
52592                             undefined; }));
52593                     }
52594                     if (!constructSignatures.length) {
52595                         constructSignatures = getDefaultConstructSignatures(classType_1);
52596                     }
52597                     type.constructSignatures = constructSignatures;
52598                 }
52599             }
52600         }
52601         function resolveReverseMappedTypeMembers(type) {
52602             var indexInfo = getIndexInfoOfType(type.source, 0 /* String */);
52603             var modifiers = getMappedTypeModifiers(type.mappedType);
52604             var readonlyMask = modifiers & 1 /* IncludeReadonly */ ? false : true;
52605             var optionalMask = modifiers & 4 /* IncludeOptional */ ? 0 : 16777216 /* Optional */;
52606             var stringIndexInfo = indexInfo && createIndexInfo(inferReverseMappedType(indexInfo.type, type.mappedType, type.constraintType), readonlyMask && indexInfo.isReadonly);
52607             var members = ts.createSymbolTable();
52608             for (var _i = 0, _a = getPropertiesOfType(type.source); _i < _a.length; _i++) {
52609                 var prop = _a[_i];
52610                 var checkFlags = 8192 /* ReverseMapped */ | (readonlyMask && isReadonlySymbol(prop) ? 8 /* Readonly */ : 0);
52611                 var inferredProp = createSymbol(4 /* Property */ | prop.flags & optionalMask, prop.escapedName, checkFlags);
52612                 inferredProp.declarations = prop.declarations;
52613                 inferredProp.nameType = getSymbolLinks(prop).nameType;
52614                 inferredProp.propertyType = getTypeOfSymbol(prop);
52615                 inferredProp.mappedType = type.mappedType;
52616                 inferredProp.constraintType = type.constraintType;
52617                 members.set(prop.escapedName, inferredProp);
52618             }
52619             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, undefined);
52620         }
52621         // Return the lower bound of the key type in a mapped type. Intuitively, the lower
52622         // bound includes those keys that are known to always be present, for example because
52623         // because of constraints on type parameters (e.g. 'keyof T' for a constrained T).
52624         function getLowerBoundOfKeyType(type) {
52625             if (type.flags & 4194304 /* Index */) {
52626                 var t = getApparentType(type.type);
52627                 return isGenericTupleType(t) ? getKnownKeysOfTupleType(t) : getIndexType(t);
52628             }
52629             if (type.flags & 16777216 /* Conditional */) {
52630                 if (type.root.isDistributive) {
52631                     var checkType = type.checkType;
52632                     var constraint = getLowerBoundOfKeyType(checkType);
52633                     if (constraint !== checkType) {
52634                         return getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
52635                     }
52636                 }
52637                 return type;
52638             }
52639             if (type.flags & 1048576 /* Union */) {
52640                 return getUnionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
52641             }
52642             if (type.flags & 2097152 /* Intersection */) {
52643                 return getIntersectionType(ts.sameMap(type.types, getLowerBoundOfKeyType));
52644             }
52645             return type;
52646         }
52647         /** Resolve the members of a mapped type { [P in K]: T } */
52648         function resolveMappedTypeMembers(type) {
52649             var members = ts.createSymbolTable();
52650             var stringIndexInfo;
52651             var numberIndexInfo;
52652             // Resolve upfront such that recursive references see an empty object type.
52653             setStructuredTypeMembers(type, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
52654             // In { [P in K]: T }, we refer to P as the type parameter type, K as the constraint type,
52655             // and T as the template type.
52656             var typeParameter = getTypeParameterFromMappedType(type);
52657             var constraintType = getConstraintTypeFromMappedType(type);
52658             var nameType = getNameTypeFromMappedType(type.target || type);
52659             var templateType = getTemplateTypeFromMappedType(type.target || type);
52660             var modifiersType = getApparentType(getModifiersTypeFromMappedType(type)); // The 'T' in 'keyof T'
52661             var templateModifiers = getMappedTypeModifiers(type);
52662             var include = keyofStringsOnly ? 128 /* StringLiteral */ : 8576 /* StringOrNumberLiteralOrUnique */;
52663             if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
52664                 // We have a { [P in keyof T]: X }
52665                 for (var _i = 0, _a = getPropertiesOfType(modifiersType); _i < _a.length; _i++) {
52666                     var prop = _a[_i];
52667                     addMemberForKeyType(getLiteralTypeFromProperty(prop, include));
52668                 }
52669                 if (modifiersType.flags & 1 /* Any */ || getIndexInfoOfType(modifiersType, 0 /* String */)) {
52670                     addMemberForKeyType(stringType);
52671                 }
52672                 if (!keyofStringsOnly && getIndexInfoOfType(modifiersType, 1 /* Number */)) {
52673                     addMemberForKeyType(numberType);
52674                 }
52675             }
52676             else {
52677                 forEachType(getLowerBoundOfKeyType(constraintType), addMemberForKeyType);
52678             }
52679             setStructuredTypeMembers(type, members, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
52680             function addMemberForKeyType(keyType) {
52681                 var propNameType = nameType ? instantiateType(nameType, appendTypeMapping(type.mapper, typeParameter, keyType)) : keyType;
52682                 forEachType(propNameType, function (t) { return addMemberForKeyTypeWorker(keyType, t); });
52683             }
52684             function addMemberForKeyTypeWorker(keyType, propNameType) {
52685                 // If the current iteration type constituent is a string literal type, create a property.
52686                 // Otherwise, for type string create a string index signature.
52687                 if (isTypeUsableAsPropertyName(propNameType)) {
52688                     var propName = getPropertyNameFromType(propNameType);
52689                     // String enum members from separate enums with identical values
52690                     // are distinct types with the same property name. Make the resulting
52691                     // property symbol's name type be the union of those enum member types.
52692                     var existingProp = members.get(propName);
52693                     if (existingProp) {
52694                         existingProp.nameType = getUnionType([existingProp.nameType, propNameType]);
52695                         existingProp.keyType = getUnionType([existingProp.keyType, keyType]);
52696                     }
52697                     else {
52698                         var modifiersProp = isTypeUsableAsPropertyName(keyType) ? getPropertyOfType(modifiersType, getPropertyNameFromType(keyType)) : undefined;
52699                         var isOptional = !!(templateModifiers & 4 /* IncludeOptional */ ||
52700                             !(templateModifiers & 8 /* ExcludeOptional */) && modifiersProp && modifiersProp.flags & 16777216 /* Optional */);
52701                         var isReadonly = !!(templateModifiers & 1 /* IncludeReadonly */ ||
52702                             !(templateModifiers & 2 /* ExcludeReadonly */) && modifiersProp && isReadonlySymbol(modifiersProp));
52703                         var stripOptional = strictNullChecks && !isOptional && modifiersProp && modifiersProp.flags & 16777216 /* Optional */;
52704                         var prop = createSymbol(4 /* Property */ | (isOptional ? 16777216 /* Optional */ : 0), propName, 262144 /* Mapped */ | (isReadonly ? 8 /* Readonly */ : 0) | (stripOptional ? 524288 /* StripOptional */ : 0));
52705                         prop.mappedType = type;
52706                         prop.nameType = propNameType;
52707                         prop.keyType = keyType;
52708                         if (modifiersProp) {
52709                             prop.syntheticOrigin = modifiersProp;
52710                             prop.declarations = modifiersProp.declarations;
52711                         }
52712                         members.set(propName, prop);
52713                     }
52714                 }
52715                 else if (propNameType.flags & (1 /* Any */ | 4 /* String */ | 8 /* Number */ | 32 /* Enum */)) {
52716                     var propType = instantiateType(templateType, appendTypeMapping(type.mapper, typeParameter, keyType));
52717                     if (propNameType.flags & (1 /* Any */ | 4 /* String */)) {
52718                         stringIndexInfo = createIndexInfo(stringIndexInfo ? getUnionType([stringIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
52719                     }
52720                     else {
52721                         numberIndexInfo = createIndexInfo(numberIndexInfo ? getUnionType([numberIndexInfo.type, propType]) : propType, !!(templateModifiers & 1 /* IncludeReadonly */));
52722                     }
52723                 }
52724             }
52725         }
52726         function getTypeOfMappedSymbol(symbol) {
52727             if (!symbol.type) {
52728                 var mappedType = symbol.mappedType;
52729                 if (!pushTypeResolution(symbol, 0 /* Type */)) {
52730                     mappedType.containsError = true;
52731                     return errorType;
52732                 }
52733                 var templateType = getTemplateTypeFromMappedType(mappedType.target || mappedType);
52734                 var mapper = appendTypeMapping(mappedType.mapper, getTypeParameterFromMappedType(mappedType), symbol.keyType);
52735                 var propType = instantiateType(templateType, mapper);
52736                 // When creating an optional property in strictNullChecks mode, if 'undefined' isn't assignable to the
52737                 // type, we include 'undefined' in the type. Similarly, when creating a non-optional property in strictNullChecks
52738                 // mode, if the underlying property is optional we remove 'undefined' from the type.
52739                 var type = strictNullChecks && symbol.flags & 16777216 /* Optional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
52740                     symbol.checkFlags & 524288 /* StripOptional */ ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
52741                         propType;
52742                 if (!popTypeResolution()) {
52743                     error(currentNode, ts.Diagnostics.Type_of_property_0_circularly_references_itself_in_mapped_type_1, symbolToString(symbol), typeToString(mappedType));
52744                     type = errorType;
52745                 }
52746                 symbol.type = type;
52747             }
52748             return symbol.type;
52749         }
52750         function getTypeParameterFromMappedType(type) {
52751             return type.typeParameter ||
52752                 (type.typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(type.declaration.typeParameter)));
52753         }
52754         function getConstraintTypeFromMappedType(type) {
52755             return type.constraintType ||
52756                 (type.constraintType = getConstraintOfTypeParameter(getTypeParameterFromMappedType(type)) || errorType);
52757         }
52758         function getNameTypeFromMappedType(type) {
52759             return type.declaration.nameType ?
52760                 type.nameType || (type.nameType = instantiateType(getTypeFromTypeNode(type.declaration.nameType), type.mapper)) :
52761                 undefined;
52762         }
52763         function getTemplateTypeFromMappedType(type) {
52764             return type.templateType ||
52765                 (type.templateType = type.declaration.type ?
52766                     instantiateType(addOptionality(getTypeFromTypeNode(type.declaration.type), !!(getMappedTypeModifiers(type) & 4 /* IncludeOptional */)), type.mapper) :
52767                     errorType);
52768         }
52769         function getConstraintDeclarationForMappedType(type) {
52770             return ts.getEffectiveConstraintOfTypeParameter(type.declaration.typeParameter);
52771         }
52772         function isMappedTypeWithKeyofConstraintDeclaration(type) {
52773             var constraintDeclaration = getConstraintDeclarationForMappedType(type); // TODO: GH#18217
52774             return constraintDeclaration.kind === 188 /* TypeOperator */ &&
52775                 constraintDeclaration.operator === 138 /* KeyOfKeyword */;
52776         }
52777         function getModifiersTypeFromMappedType(type) {
52778             if (!type.modifiersType) {
52779                 if (isMappedTypeWithKeyofConstraintDeclaration(type)) {
52780                     // If the constraint declaration is a 'keyof T' node, the modifiers type is T. We check
52781                     // AST nodes here because, when T is a non-generic type, the logic below eagerly resolves
52782                     // 'keyof T' to a literal union type and we can't recover T from that type.
52783                     type.modifiersType = instantiateType(getTypeFromTypeNode(getConstraintDeclarationForMappedType(type).type), type.mapper);
52784                 }
52785                 else {
52786                     // Otherwise, get the declared constraint type, and if the constraint type is a type parameter,
52787                     // get the constraint of that type parameter. If the resulting type is an indexed type 'keyof T',
52788                     // the modifiers type is T. Otherwise, the modifiers type is unknown.
52789                     var declaredType = getTypeFromMappedTypeNode(type.declaration);
52790                     var constraint = getConstraintTypeFromMappedType(declaredType);
52791                     var extendedConstraint = constraint && constraint.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(constraint) : constraint;
52792                     type.modifiersType = extendedConstraint && extendedConstraint.flags & 4194304 /* Index */ ? instantiateType(extendedConstraint.type, type.mapper) : unknownType;
52793                 }
52794             }
52795             return type.modifiersType;
52796         }
52797         function getMappedTypeModifiers(type) {
52798             var declaration = type.declaration;
52799             return (declaration.readonlyToken ? declaration.readonlyToken.kind === 40 /* MinusToken */ ? 2 /* ExcludeReadonly */ : 1 /* IncludeReadonly */ : 0) |
52800                 (declaration.questionToken ? declaration.questionToken.kind === 40 /* MinusToken */ ? 8 /* ExcludeOptional */ : 4 /* IncludeOptional */ : 0);
52801         }
52802         function getMappedTypeOptionality(type) {
52803             var modifiers = getMappedTypeModifiers(type);
52804             return modifiers & 8 /* ExcludeOptional */ ? -1 : modifiers & 4 /* IncludeOptional */ ? 1 : 0;
52805         }
52806         function getCombinedMappedTypeOptionality(type) {
52807             var optionality = getMappedTypeOptionality(type);
52808             var modifiersType = getModifiersTypeFromMappedType(type);
52809             return optionality || (isGenericMappedType(modifiersType) ? getMappedTypeOptionality(modifiersType) : 0);
52810         }
52811         function isPartialMappedType(type) {
52812             return !!(ts.getObjectFlags(type) & 32 /* Mapped */ && getMappedTypeModifiers(type) & 4 /* IncludeOptional */);
52813         }
52814         function isGenericMappedType(type) {
52815             return !!(ts.getObjectFlags(type) & 32 /* Mapped */) && isGenericIndexType(getConstraintTypeFromMappedType(type));
52816         }
52817         function resolveStructuredTypeMembers(type) {
52818             if (!type.members) {
52819                 if (type.flags & 524288 /* Object */) {
52820                     if (type.objectFlags & 4 /* Reference */) {
52821                         resolveTypeReferenceMembers(type);
52822                     }
52823                     else if (type.objectFlags & 3 /* ClassOrInterface */) {
52824                         resolveClassOrInterfaceMembers(type);
52825                     }
52826                     else if (type.objectFlags & 2048 /* ReverseMapped */) {
52827                         resolveReverseMappedTypeMembers(type);
52828                     }
52829                     else if (type.objectFlags & 16 /* Anonymous */) {
52830                         resolveAnonymousTypeMembers(type);
52831                     }
52832                     else if (type.objectFlags & 32 /* Mapped */) {
52833                         resolveMappedTypeMembers(type);
52834                     }
52835                 }
52836                 else if (type.flags & 1048576 /* Union */) {
52837                     resolveUnionTypeMembers(type);
52838                 }
52839                 else if (type.flags & 2097152 /* Intersection */) {
52840                     resolveIntersectionTypeMembers(type);
52841                 }
52842             }
52843             return type;
52844         }
52845         /** Return properties of an object type or an empty array for other types */
52846         function getPropertiesOfObjectType(type) {
52847             if (type.flags & 524288 /* Object */) {
52848                 return resolveStructuredTypeMembers(type).properties;
52849             }
52850             return ts.emptyArray;
52851         }
52852         /** If the given type is an object type and that type has a property by the given name,
52853          * return the symbol for that property. Otherwise return undefined.
52854          */
52855         function getPropertyOfObjectType(type, name) {
52856             if (type.flags & 524288 /* Object */) {
52857                 var resolved = resolveStructuredTypeMembers(type);
52858                 var symbol = resolved.members.get(name);
52859                 if (symbol && symbolIsValue(symbol)) {
52860                     return symbol;
52861                 }
52862             }
52863         }
52864         function getPropertiesOfUnionOrIntersectionType(type) {
52865             if (!type.resolvedProperties) {
52866                 var members = ts.createSymbolTable();
52867                 for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
52868                     var current = _a[_i];
52869                     for (var _b = 0, _c = getPropertiesOfType(current); _b < _c.length; _b++) {
52870                         var prop = _c[_b];
52871                         if (!members.has(prop.escapedName)) {
52872                             var combinedProp = getPropertyOfUnionOrIntersectionType(type, prop.escapedName);
52873                             if (combinedProp) {
52874                                 members.set(prop.escapedName, combinedProp);
52875                             }
52876                         }
52877                     }
52878                     // The properties of a union type are those that are present in all constituent types, so
52879                     // we only need to check the properties of the first type without index signature
52880                     if (type.flags & 1048576 /* Union */ && !getIndexInfoOfType(current, 0 /* String */) && !getIndexInfoOfType(current, 1 /* Number */)) {
52881                         break;
52882                     }
52883                 }
52884                 type.resolvedProperties = getNamedMembers(members);
52885             }
52886             return type.resolvedProperties;
52887         }
52888         function getPropertiesOfType(type) {
52889             type = getReducedApparentType(type);
52890             return type.flags & 3145728 /* UnionOrIntersection */ ?
52891                 getPropertiesOfUnionOrIntersectionType(type) :
52892                 getPropertiesOfObjectType(type);
52893         }
52894         function isTypeInvalidDueToUnionDiscriminant(contextualType, obj) {
52895             var list = obj.properties;
52896             return list.some(function (property) {
52897                 var nameType = property.name && getLiteralTypeFromPropertyName(property.name);
52898                 var name = nameType && isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
52899                 var expected = name === undefined ? undefined : getTypeOfPropertyOfType(contextualType, name);
52900                 return !!expected && isLiteralType(expected) && !isTypeAssignableTo(getTypeOfNode(property), expected);
52901             });
52902         }
52903         function getAllPossiblePropertiesOfTypes(types) {
52904             var unionType = getUnionType(types);
52905             if (!(unionType.flags & 1048576 /* Union */)) {
52906                 return getAugmentedPropertiesOfType(unionType);
52907             }
52908             var props = ts.createSymbolTable();
52909             for (var _i = 0, types_5 = types; _i < types_5.length; _i++) {
52910                 var memberType = types_5[_i];
52911                 for (var _a = 0, _b = getAugmentedPropertiesOfType(memberType); _a < _b.length; _a++) {
52912                     var escapedName = _b[_a].escapedName;
52913                     if (!props.has(escapedName)) {
52914                         var prop = createUnionOrIntersectionProperty(unionType, escapedName);
52915                         // May be undefined if the property is private
52916                         if (prop)
52917                             props.set(escapedName, prop);
52918                     }
52919                 }
52920             }
52921             return ts.arrayFrom(props.values());
52922         }
52923         function getConstraintOfType(type) {
52924             return type.flags & 262144 /* TypeParameter */ ? getConstraintOfTypeParameter(type) :
52925                 type.flags & 8388608 /* IndexedAccess */ ? getConstraintOfIndexedAccess(type) :
52926                     type.flags & 16777216 /* Conditional */ ? getConstraintOfConditionalType(type) :
52927                         getBaseConstraintOfType(type);
52928         }
52929         function getConstraintOfTypeParameter(typeParameter) {
52930             return hasNonCircularBaseConstraint(typeParameter) ? getConstraintFromTypeParameter(typeParameter) : undefined;
52931         }
52932         function getConstraintOfIndexedAccess(type) {
52933             return hasNonCircularBaseConstraint(type) ? getConstraintFromIndexedAccess(type) : undefined;
52934         }
52935         function getSimplifiedTypeOrConstraint(type) {
52936             var simplified = getSimplifiedType(type, /*writing*/ false);
52937             return simplified !== type ? simplified : getConstraintOfType(type);
52938         }
52939         function getConstraintFromIndexedAccess(type) {
52940             var indexConstraint = getSimplifiedTypeOrConstraint(type.indexType);
52941             if (indexConstraint && indexConstraint !== type.indexType) {
52942                 var indexedAccess = getIndexedAccessTypeOrUndefined(type.objectType, indexConstraint, type.noUncheckedIndexedAccessCandidate);
52943                 if (indexedAccess) {
52944                     return indexedAccess;
52945                 }
52946             }
52947             var objectConstraint = getSimplifiedTypeOrConstraint(type.objectType);
52948             if (objectConstraint && objectConstraint !== type.objectType) {
52949                 return getIndexedAccessTypeOrUndefined(objectConstraint, type.indexType, type.noUncheckedIndexedAccessCandidate);
52950             }
52951             return undefined;
52952         }
52953         function getDefaultConstraintOfConditionalType(type) {
52954             if (!type.resolvedDefaultConstraint) {
52955                 // An `any` branch of a conditional type would normally be viral - specifically, without special handling here,
52956                 // a conditional type with a single branch of type `any` would be assignable to anything, since it's constraint would simplify to
52957                 // just `any`. This result is _usually_ unwanted - so instead here we elide an `any` branch from the constraint type,
52958                 // in effect treating `any` like `never` rather than `unknown` in this location.
52959                 var trueConstraint = getInferredTrueTypeFromConditionalType(type);
52960                 var falseConstraint = getFalseTypeFromConditionalType(type);
52961                 type.resolvedDefaultConstraint = isTypeAny(trueConstraint) ? falseConstraint : isTypeAny(falseConstraint) ? trueConstraint : getUnionType([trueConstraint, falseConstraint]);
52962             }
52963             return type.resolvedDefaultConstraint;
52964         }
52965         function getConstraintOfDistributiveConditionalType(type) {
52966             // Check if we have a conditional type of the form 'T extends U ? X : Y', where T is a constrained
52967             // type parameter. If so, create an instantiation of the conditional type where T is replaced
52968             // with its constraint. We do this because if the constraint is a union type it will be distributed
52969             // over the conditional type and possibly reduced. For example, 'T extends undefined ? never : T'
52970             // removes 'undefined' from T.
52971             // We skip returning a distributive constraint for a restrictive instantiation of a conditional type
52972             // as the constraint for all type params (check type included) have been replace with `unknown`, which
52973             // is going to produce even more false positive/negative results than the distribute constraint already does.
52974             // Please note: the distributive constraint is a kludge for emulating what a negated type could to do filter
52975             // a union - once negated types exist and are applied to the conditional false branch, this "constraint"
52976             // likely doesn't need to exist.
52977             if (type.root.isDistributive && type.restrictiveInstantiation !== type) {
52978                 var simplified = getSimplifiedType(type.checkType, /*writing*/ false);
52979                 var constraint = simplified === type.checkType ? getConstraintOfType(simplified) : simplified;
52980                 if (constraint && constraint !== type.checkType) {
52981                     var instantiated = getConditionalTypeInstantiation(type, prependTypeMapping(type.root.checkType, constraint, type.mapper));
52982                     if (!(instantiated.flags & 131072 /* Never */)) {
52983                         return instantiated;
52984                     }
52985                 }
52986             }
52987             return undefined;
52988         }
52989         function getConstraintFromConditionalType(type) {
52990             return getConstraintOfDistributiveConditionalType(type) || getDefaultConstraintOfConditionalType(type);
52991         }
52992         function getConstraintOfConditionalType(type) {
52993             return hasNonCircularBaseConstraint(type) ? getConstraintFromConditionalType(type) : undefined;
52994         }
52995         function getEffectiveConstraintOfIntersection(types, targetIsUnion) {
52996             var constraints;
52997             var hasDisjointDomainType = false;
52998             for (var _i = 0, types_6 = types; _i < types_6.length; _i++) {
52999                 var t = types_6[_i];
53000                 if (t.flags & 465829888 /* Instantiable */) {
53001                     // We keep following constraints as long as we have an instantiable type that is known
53002                     // not to be circular or infinite (hence we stop on index access types).
53003                     var constraint = getConstraintOfType(t);
53004                     while (constraint && constraint.flags & (262144 /* TypeParameter */ | 4194304 /* Index */ | 16777216 /* Conditional */)) {
53005                         constraint = getConstraintOfType(constraint);
53006                     }
53007                     if (constraint) {
53008                         constraints = ts.append(constraints, constraint);
53009                         if (targetIsUnion) {
53010                             constraints = ts.append(constraints, t);
53011                         }
53012                     }
53013                 }
53014                 else if (t.flags & 469892092 /* DisjointDomains */) {
53015                     hasDisjointDomainType = true;
53016                 }
53017             }
53018             // If the target is a union type or if we are intersecting with types belonging to one of the
53019             // disjoint domains, we may end up producing a constraint that hasn't been examined before.
53020             if (constraints && (targetIsUnion || hasDisjointDomainType)) {
53021                 if (hasDisjointDomainType) {
53022                     // We add any types belong to one of the disjoint domains because they might cause the final
53023                     // intersection operation to reduce the union constraints.
53024                     for (var _a = 0, types_7 = types; _a < types_7.length; _a++) {
53025                         var t = types_7[_a];
53026                         if (t.flags & 469892092 /* DisjointDomains */) {
53027                             constraints = ts.append(constraints, t);
53028                         }
53029                     }
53030                 }
53031                 return getIntersectionType(constraints);
53032             }
53033             return undefined;
53034         }
53035         function getBaseConstraintOfType(type) {
53036             if (type.flags & (58982400 /* InstantiableNonPrimitive */ | 3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) {
53037                 var constraint = getResolvedBaseConstraint(type);
53038                 return constraint !== noConstraintType && constraint !== circularConstraintType ? constraint : undefined;
53039             }
53040             return type.flags & 4194304 /* Index */ ? keyofConstraintType : undefined;
53041         }
53042         /**
53043          * This is similar to `getBaseConstraintOfType` except it returns the input type if there's no base constraint, instead of `undefined`
53044          * It also doesn't map indexes to `string`, as where this is used this would be unneeded (and likely undesirable)
53045          */
53046         function getBaseConstraintOrType(type) {
53047             return getBaseConstraintOfType(type) || type;
53048         }
53049         function hasNonCircularBaseConstraint(type) {
53050             return getResolvedBaseConstraint(type) !== circularConstraintType;
53051         }
53052         /**
53053          * Return the resolved base constraint of a type variable. The noConstraintType singleton is returned if the
53054          * type variable has no constraint, and the circularConstraintType singleton is returned if the constraint
53055          * circularly references the type variable.
53056          */
53057         function getResolvedBaseConstraint(type) {
53058             if (type.resolvedBaseConstraint) {
53059                 return type.resolvedBaseConstraint;
53060             }
53061             var nonTerminating = false;
53062             var stack = [];
53063             return type.resolvedBaseConstraint = getTypeWithThisArgument(getImmediateBaseConstraint(type), type);
53064             function getImmediateBaseConstraint(t) {
53065                 if (!t.immediateBaseConstraint) {
53066                     if (!pushTypeResolution(t, 4 /* ImmediateBaseConstraint */)) {
53067                         return circularConstraintType;
53068                     }
53069                     if (constraintDepth >= 50) {
53070                         // We have reached 50 recursive invocations of getImmediateBaseConstraint and there is a
53071                         // very high likelihood we're dealing with an infinite generic type that perpetually generates
53072                         // new type identities as we descend into it. We stop the recursion here and mark this type
53073                         // and the outer types as having circular constraints.
53074                         ts.tracing.instant("check" /* Check */, "getImmediateBaseConstraint_DepthLimit", { typeId: t.id, originalTypeId: type.id, depth: constraintDepth });
53075                         error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
53076                         nonTerminating = true;
53077                         return t.immediateBaseConstraint = noConstraintType;
53078                     }
53079                     var result = void 0;
53080                     if (!isDeeplyNestedType(t, stack, stack.length)) {
53081                         stack.push(t);
53082                         constraintDepth++;
53083                         result = computeBaseConstraint(getSimplifiedType(t, /*writing*/ false));
53084                         constraintDepth--;
53085                         stack.pop();
53086                     }
53087                     if (!popTypeResolution()) {
53088                         if (t.flags & 262144 /* TypeParameter */) {
53089                             var errorNode = getConstraintDeclaration(t);
53090                             if (errorNode) {
53091                                 var diagnostic = error(errorNode, ts.Diagnostics.Type_parameter_0_has_a_circular_constraint, typeToString(t));
53092                                 if (currentNode && !ts.isNodeDescendantOf(errorNode, currentNode) && !ts.isNodeDescendantOf(currentNode, errorNode)) {
53093                                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(currentNode, ts.Diagnostics.Circularity_originates_in_type_at_this_location));
53094                                 }
53095                             }
53096                         }
53097                         result = circularConstraintType;
53098                     }
53099                     if (nonTerminating) {
53100                         result = circularConstraintType;
53101                     }
53102                     t.immediateBaseConstraint = result || noConstraintType;
53103                 }
53104                 return t.immediateBaseConstraint;
53105             }
53106             function getBaseConstraint(t) {
53107                 var c = getImmediateBaseConstraint(t);
53108                 return c !== noConstraintType && c !== circularConstraintType ? c : undefined;
53109             }
53110             function computeBaseConstraint(t) {
53111                 if (t.flags & 262144 /* TypeParameter */) {
53112                     var constraint = getConstraintFromTypeParameter(t);
53113                     return t.isThisType || !constraint ?
53114                         constraint :
53115                         getBaseConstraint(constraint);
53116                 }
53117                 if (t.flags & 3145728 /* UnionOrIntersection */) {
53118                     var types = t.types;
53119                     var baseTypes = [];
53120                     for (var _i = 0, types_8 = types; _i < types_8.length; _i++) {
53121                         var type_3 = types_8[_i];
53122                         var baseType = getBaseConstraint(type_3);
53123                         if (baseType) {
53124                             baseTypes.push(baseType);
53125                         }
53126                     }
53127                     return t.flags & 1048576 /* Union */ && baseTypes.length === types.length ? getUnionType(baseTypes) :
53128                         t.flags & 2097152 /* Intersection */ && baseTypes.length ? getIntersectionType(baseTypes) :
53129                             undefined;
53130                 }
53131                 if (t.flags & 4194304 /* Index */) {
53132                     return keyofConstraintType;
53133                 }
53134                 if (t.flags & 134217728 /* TemplateLiteral */) {
53135                     var types = t.types;
53136                     var constraints = ts.mapDefined(types, getBaseConstraint);
53137                     return constraints.length === types.length ? getTemplateLiteralType(t.texts, constraints) : stringType;
53138                 }
53139                 if (t.flags & 268435456 /* StringMapping */) {
53140                     var constraint = getBaseConstraint(t.type);
53141                     return constraint ? getStringMappingType(t.symbol, constraint) : stringType;
53142                 }
53143                 if (t.flags & 8388608 /* IndexedAccess */) {
53144                     var baseObjectType = getBaseConstraint(t.objectType);
53145                     var baseIndexType = getBaseConstraint(t.indexType);
53146                     var baseIndexedAccess = baseObjectType && baseIndexType && getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, t.noUncheckedIndexedAccessCandidate);
53147                     return baseIndexedAccess && getBaseConstraint(baseIndexedAccess);
53148                 }
53149                 if (t.flags & 16777216 /* Conditional */) {
53150                     var constraint = getConstraintFromConditionalType(t);
53151                     constraintDepth++; // Penalize repeating conditional types (this captures the recursion within getConstraintFromConditionalType and carries it forward)
53152                     var result = constraint && getBaseConstraint(constraint);
53153                     constraintDepth--;
53154                     return result;
53155                 }
53156                 if (t.flags & 33554432 /* Substitution */) {
53157                     return getBaseConstraint(t.substitute);
53158                 }
53159                 return t;
53160             }
53161         }
53162         function getApparentTypeOfIntersectionType(type) {
53163             return type.resolvedApparentType || (type.resolvedApparentType = getTypeWithThisArgument(type, type, /*apparentType*/ true));
53164         }
53165         function getResolvedTypeParameterDefault(typeParameter) {
53166             if (!typeParameter.default) {
53167                 if (typeParameter.target) {
53168                     var targetDefault = getResolvedTypeParameterDefault(typeParameter.target);
53169                     typeParameter.default = targetDefault ? instantiateType(targetDefault, typeParameter.mapper) : noConstraintType;
53170                 }
53171                 else {
53172                     // To block recursion, set the initial value to the resolvingDefaultType.
53173                     typeParameter.default = resolvingDefaultType;
53174                     var defaultDeclaration = typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; });
53175                     var defaultType = defaultDeclaration ? getTypeFromTypeNode(defaultDeclaration) : noConstraintType;
53176                     if (typeParameter.default === resolvingDefaultType) {
53177                         // If we have not been called recursively, set the correct default type.
53178                         typeParameter.default = defaultType;
53179                     }
53180                 }
53181             }
53182             else if (typeParameter.default === resolvingDefaultType) {
53183                 // If we are called recursively for this type parameter, mark the default as circular.
53184                 typeParameter.default = circularConstraintType;
53185             }
53186             return typeParameter.default;
53187         }
53188         /**
53189          * Gets the default type for a type parameter.
53190          *
53191          * If the type parameter is the result of an instantiation, this gets the instantiated
53192          * default type of its target. If the type parameter has no default type or the default is
53193          * circular, `undefined` is returned.
53194          */
53195         function getDefaultFromTypeParameter(typeParameter) {
53196             var defaultType = getResolvedTypeParameterDefault(typeParameter);
53197             return defaultType !== noConstraintType && defaultType !== circularConstraintType ? defaultType : undefined;
53198         }
53199         function hasNonCircularTypeParameterDefault(typeParameter) {
53200             return getResolvedTypeParameterDefault(typeParameter) !== circularConstraintType;
53201         }
53202         /**
53203          * Indicates whether the declaration of a typeParameter has a default type.
53204          */
53205         function hasTypeParameterDefault(typeParameter) {
53206             return !!(typeParameter.symbol && ts.forEach(typeParameter.symbol.declarations, function (decl) { return ts.isTypeParameterDeclaration(decl) && decl.default; }));
53207         }
53208         function getApparentTypeOfMappedType(type) {
53209             return type.resolvedApparentType || (type.resolvedApparentType = getResolvedApparentTypeOfMappedType(type));
53210         }
53211         function getResolvedApparentTypeOfMappedType(type) {
53212             var typeVariable = getHomomorphicTypeVariable(type);
53213             if (typeVariable && !type.declaration.nameType) {
53214                 var constraint = getConstraintOfTypeParameter(typeVariable);
53215                 if (constraint && (isArrayType(constraint) || isTupleType(constraint))) {
53216                     return instantiateType(type, prependTypeMapping(typeVariable, constraint, type.mapper));
53217                 }
53218             }
53219             return type;
53220         }
53221         /**
53222          * For a type parameter, return the base constraint of the type parameter. For the string, number,
53223          * boolean, and symbol primitive types, return the corresponding object types. Otherwise return the
53224          * type itself.
53225          */
53226         function getApparentType(type) {
53227             var t = type.flags & 465829888 /* Instantiable */ ? getBaseConstraintOfType(type) || unknownType : type;
53228             return ts.getObjectFlags(t) & 32 /* Mapped */ ? getApparentTypeOfMappedType(t) :
53229                 t.flags & 2097152 /* Intersection */ ? getApparentTypeOfIntersectionType(t) :
53230                     t.flags & 402653316 /* StringLike */ ? globalStringType :
53231                         t.flags & 296 /* NumberLike */ ? globalNumberType :
53232                             t.flags & 2112 /* BigIntLike */ ? getGlobalBigIntType(/*reportErrors*/ languageVersion >= 7 /* ES2020 */) :
53233                                 t.flags & 528 /* BooleanLike */ ? globalBooleanType :
53234                                     t.flags & 12288 /* ESSymbolLike */ ? getGlobalESSymbolType(/*reportErrors*/ languageVersion >= 2 /* ES2015 */) :
53235                                         t.flags & 67108864 /* NonPrimitive */ ? emptyObjectType :
53236                                             t.flags & 4194304 /* Index */ ? keyofConstraintType :
53237                                                 t.flags & 2 /* Unknown */ && !strictNullChecks ? emptyObjectType :
53238                                                     t;
53239         }
53240         function getReducedApparentType(type) {
53241             // Since getApparentType may return a non-reduced union or intersection type, we need to perform
53242             // type reduction both before and after obtaining the apparent type. For example, given a type parameter
53243             // 'T extends A | B', the type 'T & X' becomes 'A & X | B & X' after obtaining the apparent type, and
53244             // that type may need further reduction to remove empty intersections.
53245             return getReducedType(getApparentType(getReducedType(type)));
53246         }
53247         function createUnionOrIntersectionProperty(containingType, name) {
53248             var singleProp;
53249             var propSet;
53250             var indexTypes;
53251             var isUnion = containingType.flags & 1048576 /* Union */;
53252             // Flags we want to propagate to the result if they exist in all source symbols
53253             var optionalFlag = isUnion ? 0 /* None */ : 16777216 /* Optional */;
53254             var syntheticFlag = 4 /* SyntheticMethod */;
53255             var checkFlags = 0;
53256             for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
53257                 var current = _a[_i];
53258                 var type = getApparentType(current);
53259                 if (!(type === errorType || type.flags & 131072 /* Never */)) {
53260                     var prop = getPropertyOfType(type, name);
53261                     var modifiers = prop ? ts.getDeclarationModifierFlagsFromSymbol(prop) : 0;
53262                     if (prop) {
53263                         if (isUnion) {
53264                             optionalFlag |= (prop.flags & 16777216 /* Optional */);
53265                         }
53266                         else {
53267                             optionalFlag &= prop.flags;
53268                         }
53269                         if (!singleProp) {
53270                             singleProp = prop;
53271                         }
53272                         else if (prop !== singleProp) {
53273                             if (!propSet) {
53274                                 propSet = new ts.Map();
53275                                 propSet.set(getSymbolId(singleProp), singleProp);
53276                             }
53277                             var id = getSymbolId(prop);
53278                             if (!propSet.has(id)) {
53279                                 propSet.set(id, prop);
53280                             }
53281                         }
53282                         checkFlags |= (isReadonlySymbol(prop) ? 8 /* Readonly */ : 0) |
53283                             (!(modifiers & 24 /* NonPublicAccessibilityModifier */) ? 256 /* ContainsPublic */ : 0) |
53284                             (modifiers & 16 /* Protected */ ? 512 /* ContainsProtected */ : 0) |
53285                             (modifiers & 8 /* Private */ ? 1024 /* ContainsPrivate */ : 0) |
53286                             (modifiers & 32 /* Static */ ? 2048 /* ContainsStatic */ : 0);
53287                         if (!isPrototypeProperty(prop)) {
53288                             syntheticFlag = 2 /* SyntheticProperty */;
53289                         }
53290                     }
53291                     else if (isUnion) {
53292                         var indexInfo = !isLateBoundName(name) && (isNumericLiteralName(name) && getIndexInfoOfType(type, 1 /* Number */) || getIndexInfoOfType(type, 0 /* String */));
53293                         if (indexInfo) {
53294                             checkFlags |= 32 /* WritePartial */ | (indexInfo.isReadonly ? 8 /* Readonly */ : 0);
53295                             indexTypes = ts.append(indexTypes, isTupleType(type) ? getRestTypeOfTupleType(type) || undefinedType : indexInfo.type);
53296                         }
53297                         else if (isObjectLiteralType(type)) {
53298                             checkFlags |= 32 /* WritePartial */;
53299                             indexTypes = ts.append(indexTypes, undefinedType);
53300                         }
53301                         else {
53302                             checkFlags |= 16 /* ReadPartial */;
53303                         }
53304                     }
53305                 }
53306             }
53307             if (!singleProp || isUnion && (propSet || checkFlags & 48 /* Partial */) && checkFlags & (1024 /* ContainsPrivate */ | 512 /* ContainsProtected */)) {
53308                 // No property was found, or, in a union, a property has a private or protected declaration in one
53309                 // constituent, but is missing or has a different declaration in another constituent.
53310                 return undefined;
53311             }
53312             if (!propSet && !(checkFlags & 16 /* ReadPartial */) && !indexTypes) {
53313                 return singleProp;
53314             }
53315             var props = propSet ? ts.arrayFrom(propSet.values()) : [singleProp];
53316             var declarations;
53317             var firstType;
53318             var nameType;
53319             var propTypes = [];
53320             var firstValueDeclaration;
53321             var hasNonUniformValueDeclaration = false;
53322             for (var _b = 0, props_1 = props; _b < props_1.length; _b++) {
53323                 var prop = props_1[_b];
53324                 if (!firstValueDeclaration) {
53325                     firstValueDeclaration = prop.valueDeclaration;
53326                 }
53327                 else if (prop.valueDeclaration && prop.valueDeclaration !== firstValueDeclaration) {
53328                     hasNonUniformValueDeclaration = true;
53329                 }
53330                 declarations = ts.addRange(declarations, prop.declarations);
53331                 var type = getTypeOfSymbol(prop);
53332                 if (!firstType) {
53333                     firstType = type;
53334                     nameType = getSymbolLinks(prop).nameType;
53335                 }
53336                 else if (type !== firstType) {
53337                     checkFlags |= 64 /* HasNonUniformType */;
53338                 }
53339                 if (isLiteralType(type)) {
53340                     checkFlags |= 128 /* HasLiteralType */;
53341                 }
53342                 if (type.flags & 131072 /* Never */) {
53343                     checkFlags |= 131072 /* HasNeverType */;
53344                 }
53345                 propTypes.push(type);
53346             }
53347             ts.addRange(propTypes, indexTypes);
53348             var result = createSymbol(4 /* Property */ | optionalFlag, name, syntheticFlag | checkFlags);
53349             result.containingType = containingType;
53350             if (!hasNonUniformValueDeclaration && firstValueDeclaration) {
53351                 result.valueDeclaration = firstValueDeclaration;
53352                 // Inherit information about parent type.
53353                 if (firstValueDeclaration.symbol.parent) {
53354                     result.parent = firstValueDeclaration.symbol.parent;
53355                 }
53356             }
53357             result.declarations = declarations;
53358             result.nameType = nameType;
53359             if (propTypes.length > 2) {
53360                 // When `propTypes` has the potential to explode in size when normalized, defer normalization until absolutely needed
53361                 result.checkFlags |= 65536 /* DeferredType */;
53362                 result.deferralParent = containingType;
53363                 result.deferralConstituents = propTypes;
53364             }
53365             else {
53366                 result.type = isUnion ? getUnionType(propTypes) : getIntersectionType(propTypes);
53367             }
53368             return result;
53369         }
53370         // Return the symbol for a given property in a union or intersection type, or undefined if the property
53371         // does not exist in any constituent type. Note that the returned property may only be present in some
53372         // constituents, in which case the isPartial flag is set when the containing type is union type. We need
53373         // these partial properties when identifying discriminant properties, but otherwise they are filtered out
53374         // and do not appear to be present in the union type.
53375         function getUnionOrIntersectionProperty(type, name) {
53376             var properties = type.propertyCache || (type.propertyCache = ts.createSymbolTable());
53377             var property = properties.get(name);
53378             if (!property) {
53379                 property = createUnionOrIntersectionProperty(type, name);
53380                 if (property) {
53381                     properties.set(name, property);
53382                 }
53383             }
53384             return property;
53385         }
53386         function getPropertyOfUnionOrIntersectionType(type, name) {
53387             var property = getUnionOrIntersectionProperty(type, name);
53388             // We need to filter out partial properties in union types
53389             return property && !(ts.getCheckFlags(property) & 16 /* ReadPartial */) ? property : undefined;
53390         }
53391         /**
53392          * Return the reduced form of the given type. For a union type, it is a union of the normalized constituent types.
53393          * For an intersection of types containing one or more mututally exclusive discriminant properties, it is 'never'.
53394          * For all other types, it is simply the type itself. Discriminant properties are considered mutually exclusive when
53395          * no constituent property has type 'never', but the intersection of the constituent property types is 'never'.
53396          */
53397         function getReducedType(type) {
53398             if (type.flags & 1048576 /* Union */ && type.objectFlags & 268435456 /* ContainsIntersections */) {
53399                 return type.resolvedReducedType || (type.resolvedReducedType = getReducedUnionType(type));
53400             }
53401             else if (type.flags & 2097152 /* Intersection */) {
53402                 if (!(type.objectFlags & 268435456 /* IsNeverIntersectionComputed */)) {
53403                     type.objectFlags |= 268435456 /* IsNeverIntersectionComputed */ |
53404                         (ts.some(getPropertiesOfUnionOrIntersectionType(type), isNeverReducedProperty) ? 536870912 /* IsNeverIntersection */ : 0);
53405                 }
53406                 return type.objectFlags & 536870912 /* IsNeverIntersection */ ? neverType : type;
53407             }
53408             return type;
53409         }
53410         function getReducedUnionType(unionType) {
53411             var reducedTypes = ts.sameMap(unionType.types, getReducedType);
53412             if (reducedTypes === unionType.types) {
53413                 return unionType;
53414             }
53415             var reduced = getUnionType(reducedTypes);
53416             if (reduced.flags & 1048576 /* Union */) {
53417                 reduced.resolvedReducedType = reduced;
53418             }
53419             return reduced;
53420         }
53421         function isNeverReducedProperty(prop) {
53422             return isDiscriminantWithNeverType(prop) || isConflictingPrivateProperty(prop);
53423         }
53424         function isDiscriminantWithNeverType(prop) {
53425             // Return true for a synthetic non-optional property with non-uniform types, where at least one is
53426             // a literal type and none is never, that reduces to never.
53427             return !(prop.flags & 16777216 /* Optional */) &&
53428                 (ts.getCheckFlags(prop) & (192 /* Discriminant */ | 131072 /* HasNeverType */)) === 192 /* Discriminant */ &&
53429                 !!(getTypeOfSymbol(prop).flags & 131072 /* Never */);
53430         }
53431         function isConflictingPrivateProperty(prop) {
53432             // Return true for a synthetic property with multiple declarations, at least one of which is private.
53433             return !prop.valueDeclaration && !!(ts.getCheckFlags(prop) & 1024 /* ContainsPrivate */);
53434         }
53435         function elaborateNeverIntersection(errorInfo, type) {
53436             if (ts.getObjectFlags(type) & 536870912 /* IsNeverIntersection */) {
53437                 var neverProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isDiscriminantWithNeverType);
53438                 if (neverProp) {
53439                     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));
53440                 }
53441                 var privateProp = ts.find(getPropertiesOfUnionOrIntersectionType(type), isConflictingPrivateProperty);
53442                 if (privateProp) {
53443                     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));
53444                 }
53445             }
53446             return errorInfo;
53447         }
53448         /**
53449          * Return the symbol for the property with the given name in the given type. Creates synthetic union properties when
53450          * necessary, maps primitive types and type parameters are to their apparent types, and augments with properties from
53451          * Object and Function as appropriate.
53452          *
53453          * @param type a type to look up property from
53454          * @param name a name of property to look up in a given type
53455          */
53456         function getPropertyOfType(type, name) {
53457             type = getReducedApparentType(type);
53458             if (type.flags & 524288 /* Object */) {
53459                 var resolved = resolveStructuredTypeMembers(type);
53460                 var symbol = resolved.members.get(name);
53461                 if (symbol && symbolIsValue(symbol)) {
53462                     return symbol;
53463                 }
53464                 var functionType = resolved === anyFunctionType ? globalFunctionType :
53465                     resolved.callSignatures.length ? globalCallableFunctionType :
53466                         resolved.constructSignatures.length ? globalNewableFunctionType :
53467                             undefined;
53468                 if (functionType) {
53469                     var symbol_1 = getPropertyOfObjectType(functionType, name);
53470                     if (symbol_1) {
53471                         return symbol_1;
53472                     }
53473                 }
53474                 return getPropertyOfObjectType(globalObjectType, name);
53475             }
53476             if (type.flags & 3145728 /* UnionOrIntersection */) {
53477                 return getPropertyOfUnionOrIntersectionType(type, name);
53478             }
53479             return undefined;
53480         }
53481         function getSignaturesOfStructuredType(type, kind) {
53482             if (type.flags & 3670016 /* StructuredType */) {
53483                 var resolved = resolveStructuredTypeMembers(type);
53484                 return kind === 0 /* Call */ ? resolved.callSignatures : resolved.constructSignatures;
53485             }
53486             return ts.emptyArray;
53487         }
53488         /**
53489          * Return the signatures of the given kind in the given type. Creates synthetic union signatures when necessary and
53490          * maps primitive types and type parameters are to their apparent types.
53491          */
53492         function getSignaturesOfType(type, kind) {
53493             return getSignaturesOfStructuredType(getReducedApparentType(type), kind);
53494         }
53495         function getIndexInfoOfStructuredType(type, kind) {
53496             if (type.flags & 3670016 /* StructuredType */) {
53497                 var resolved = resolveStructuredTypeMembers(type);
53498                 return kind === 0 /* String */ ? resolved.stringIndexInfo : resolved.numberIndexInfo;
53499             }
53500         }
53501         function getIndexTypeOfStructuredType(type, kind) {
53502             var info = getIndexInfoOfStructuredType(type, kind);
53503             return info && info.type;
53504         }
53505         // Return the indexing info of the given kind in the given type. Creates synthetic union index types when necessary and
53506         // maps primitive types and type parameters are to their apparent types.
53507         function getIndexInfoOfType(type, kind) {
53508             return getIndexInfoOfStructuredType(getReducedApparentType(type), kind);
53509         }
53510         // Return the index type of the given kind in the given type. Creates synthetic union index types when necessary and
53511         // maps primitive types and type parameters are to their apparent types.
53512         function getIndexTypeOfType(type, kind) {
53513             return getIndexTypeOfStructuredType(getReducedApparentType(type), kind);
53514         }
53515         function getImplicitIndexTypeOfType(type, kind) {
53516             if (isObjectTypeWithInferableIndex(type)) {
53517                 var propTypes = [];
53518                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
53519                     var prop = _a[_i];
53520                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
53521                         propTypes.push(getTypeOfSymbol(prop));
53522                     }
53523                 }
53524                 if (kind === 0 /* String */) {
53525                     ts.append(propTypes, getIndexTypeOfType(type, 1 /* Number */));
53526                 }
53527                 if (propTypes.length) {
53528                     return getUnionType(propTypes);
53529                 }
53530             }
53531             return undefined;
53532         }
53533         // Return list of type parameters with duplicates removed (duplicate identifier errors are generated in the actual
53534         // type checking functions).
53535         function getTypeParametersFromDeclaration(declaration) {
53536             var result;
53537             for (var _i = 0, _a = ts.getEffectiveTypeParameterDeclarations(declaration); _i < _a.length; _i++) {
53538                 var node = _a[_i];
53539                 result = ts.appendIfUnique(result, getDeclaredTypeOfTypeParameter(node.symbol));
53540             }
53541             return result;
53542         }
53543         function symbolsToArray(symbols) {
53544             var result = [];
53545             symbols.forEach(function (symbol, id) {
53546                 if (!isReservedMemberName(id)) {
53547                     result.push(symbol);
53548                 }
53549             });
53550             return result;
53551         }
53552         function isJSDocOptionalParameter(node) {
53553             return ts.isInJSFile(node) && (
53554             // node.type should only be a JSDocOptionalType when node is a parameter of a JSDocFunctionType
53555             node.type && node.type.kind === 307 /* JSDocOptionalType */
53556                 || ts.getJSDocParameterTags(node).some(function (_a) {
53557                     var isBracketed = _a.isBracketed, typeExpression = _a.typeExpression;
53558                     return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */;
53559                 }));
53560         }
53561         function tryFindAmbientModule(moduleName, withAugmentations) {
53562             if (ts.isExternalModuleNameRelative(moduleName)) {
53563                 return undefined;
53564             }
53565             var symbol = getSymbol(globals, '"' + moduleName + '"', 512 /* ValueModule */);
53566             // merged symbol is module declaration symbol combined with all augmentations
53567             return symbol && withAugmentations ? getMergedSymbol(symbol) : symbol;
53568         }
53569         function isOptionalParameter(node) {
53570             if (ts.hasQuestionToken(node) || isOptionalJSDocPropertyLikeTag(node) || isJSDocOptionalParameter(node)) {
53571                 return true;
53572             }
53573             if (node.initializer) {
53574                 var signature = getSignatureFromDeclaration(node.parent);
53575                 var parameterIndex = node.parent.parameters.indexOf(node);
53576                 ts.Debug.assert(parameterIndex >= 0);
53577                 // Only consider syntactic or instantiated parameters as optional, not `void` parameters as this function is used
53578                 // in grammar checks and checking for `void` too early results in parameter types widening too early
53579                 // and causes some noImplicitAny errors to be lost.
53580                 return parameterIndex >= getMinArgumentCount(signature, 1 /* StrongArityForUntypedJS */ | 2 /* VoidIsNonOptional */);
53581             }
53582             var iife = ts.getImmediatelyInvokedFunctionExpression(node.parent);
53583             if (iife) {
53584                 return !node.type &&
53585                     !node.dotDotDotToken &&
53586                     node.parent.parameters.indexOf(node) >= iife.arguments.length;
53587             }
53588             return false;
53589         }
53590         function isOptionalJSDocPropertyLikeTag(node) {
53591             if (!ts.isJSDocPropertyLikeTag(node)) {
53592                 return false;
53593             }
53594             var isBracketed = node.isBracketed, typeExpression = node.typeExpression;
53595             return isBracketed || !!typeExpression && typeExpression.type.kind === 307 /* JSDocOptionalType */;
53596         }
53597         function createTypePredicate(kind, parameterName, parameterIndex, type) {
53598             return { kind: kind, parameterName: parameterName, parameterIndex: parameterIndex, type: type };
53599         }
53600         /**
53601          * Gets the minimum number of type arguments needed to satisfy all non-optional type
53602          * parameters.
53603          */
53604         function getMinTypeArgumentCount(typeParameters) {
53605             var minTypeArgumentCount = 0;
53606             if (typeParameters) {
53607                 for (var i = 0; i < typeParameters.length; i++) {
53608                     if (!hasTypeParameterDefault(typeParameters[i])) {
53609                         minTypeArgumentCount = i + 1;
53610                     }
53611                 }
53612             }
53613             return minTypeArgumentCount;
53614         }
53615         function fillMissingTypeArguments(typeArguments, typeParameters, minTypeArgumentCount, isJavaScriptImplicitAny) {
53616             var numTypeParameters = ts.length(typeParameters);
53617             if (!numTypeParameters) {
53618                 return [];
53619             }
53620             var numTypeArguments = ts.length(typeArguments);
53621             if (isJavaScriptImplicitAny || (numTypeArguments >= minTypeArgumentCount && numTypeArguments <= numTypeParameters)) {
53622                 var result = typeArguments ? typeArguments.slice() : [];
53623                 // Map invalid forward references in default types to the error type
53624                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
53625                     result[i] = errorType;
53626                 }
53627                 var baseDefaultType = getDefaultTypeArgumentType(isJavaScriptImplicitAny);
53628                 for (var i = numTypeArguments; i < numTypeParameters; i++) {
53629                     var defaultType = getDefaultFromTypeParameter(typeParameters[i]);
53630                     if (isJavaScriptImplicitAny && defaultType && (isTypeIdenticalTo(defaultType, unknownType) || isTypeIdenticalTo(defaultType, emptyObjectType))) {
53631                         defaultType = anyType;
53632                     }
53633                     result[i] = defaultType ? instantiateType(defaultType, createTypeMapper(typeParameters, result)) : baseDefaultType;
53634                 }
53635                 result.length = typeParameters.length;
53636                 return result;
53637             }
53638             return typeArguments && typeArguments.slice();
53639         }
53640         function getSignatureFromDeclaration(declaration) {
53641             var links = getNodeLinks(declaration);
53642             if (!links.resolvedSignature) {
53643                 var parameters = [];
53644                 var flags = 0 /* None */;
53645                 var minArgumentCount = 0;
53646                 var thisParameter = void 0;
53647                 var hasThisParameter = false;
53648                 var iife = ts.getImmediatelyInvokedFunctionExpression(declaration);
53649                 var isJSConstructSignature = ts.isJSDocConstructSignature(declaration);
53650                 var isUntypedSignatureInJSFile = !iife &&
53651                     ts.isInJSFile(declaration) &&
53652                     ts.isValueSignatureDeclaration(declaration) &&
53653                     !ts.hasJSDocParameterTags(declaration) &&
53654                     !ts.getJSDocType(declaration);
53655                 if (isUntypedSignatureInJSFile) {
53656                     flags |= 16 /* IsUntypedSignatureInJSFile */;
53657                 }
53658                 // If this is a JSDoc construct signature, then skip the first parameter in the
53659                 // parameter list.  The first parameter represents the return type of the construct
53660                 // signature.
53661                 for (var i = isJSConstructSignature ? 1 : 0; i < declaration.parameters.length; i++) {
53662                     var param = declaration.parameters[i];
53663                     var paramSymbol = param.symbol;
53664                     var type = ts.isJSDocParameterTag(param) ? (param.typeExpression && param.typeExpression.type) : param.type;
53665                     // Include parameter symbol instead of property symbol in the signature
53666                     if (paramSymbol && !!(paramSymbol.flags & 4 /* Property */) && !ts.isBindingPattern(param.name)) {
53667                         var resolvedSymbol = resolveName(param, paramSymbol.escapedName, 111551 /* Value */, undefined, undefined, /*isUse*/ false);
53668                         paramSymbol = resolvedSymbol;
53669                     }
53670                     if (i === 0 && paramSymbol.escapedName === "this" /* This */) {
53671                         hasThisParameter = true;
53672                         thisParameter = param.symbol;
53673                     }
53674                     else {
53675                         parameters.push(paramSymbol);
53676                     }
53677                     if (type && type.kind === 191 /* LiteralType */) {
53678                         flags |= 2 /* HasLiteralTypes */;
53679                     }
53680                     // Record a new minimum argument count if this is not an optional parameter
53681                     var isOptionalParameter_1 = isOptionalJSDocPropertyLikeTag(param) ||
53682                         param.initializer || param.questionToken || param.dotDotDotToken ||
53683                         iife && parameters.length > iife.arguments.length && !type ||
53684                         isJSDocOptionalParameter(param);
53685                     if (!isOptionalParameter_1) {
53686                         minArgumentCount = parameters.length;
53687                     }
53688                 }
53689                 // If only one accessor includes a this-type annotation, the other behaves as if it had the same type annotation
53690                 if ((declaration.kind === 167 /* GetAccessor */ || declaration.kind === 168 /* SetAccessor */) &&
53691                     !hasNonBindableDynamicName(declaration) &&
53692                     (!hasThisParameter || !thisParameter)) {
53693                     var otherKind = declaration.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
53694                     var other = ts.getDeclarationOfKind(getSymbolOfNode(declaration), otherKind);
53695                     if (other) {
53696                         thisParameter = getAnnotatedAccessorThisParameter(other);
53697                     }
53698                 }
53699                 var classType = declaration.kind === 166 /* Constructor */ ?
53700                     getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol))
53701                     : undefined;
53702                 var typeParameters = classType ? classType.localTypeParameters : getTypeParametersFromDeclaration(declaration);
53703                 if (ts.hasRestParameter(declaration) || ts.isInJSFile(declaration) && maybeAddJsSyntheticRestParameter(declaration, parameters)) {
53704                     flags |= 1 /* HasRestParameter */;
53705                 }
53706                 links.resolvedSignature = createSignature(declaration, typeParameters, thisParameter, parameters, 
53707                 /*resolvedReturnType*/ undefined, /*resolvedTypePredicate*/ undefined, minArgumentCount, flags);
53708             }
53709             return links.resolvedSignature;
53710         }
53711         /**
53712          * A JS function gets a synthetic rest parameter if it references `arguments` AND:
53713          * 1. It has no parameters but at least one `@param` with a type that starts with `...`
53714          * OR
53715          * 2. It has at least one parameter, and the last parameter has a matching `@param` with a type that starts with `...`
53716          */
53717         function maybeAddJsSyntheticRestParameter(declaration, parameters) {
53718             if (ts.isJSDocSignature(declaration) || !containsArgumentsReference(declaration)) {
53719                 return false;
53720             }
53721             var lastParam = ts.lastOrUndefined(declaration.parameters);
53722             var lastParamTags = lastParam ? ts.getJSDocParameterTags(lastParam) : ts.getJSDocTags(declaration).filter(ts.isJSDocParameterTag);
53723             var lastParamVariadicType = ts.firstDefined(lastParamTags, function (p) {
53724                 return p.typeExpression && ts.isJSDocVariadicType(p.typeExpression.type) ? p.typeExpression.type : undefined;
53725             });
53726             var syntheticArgsSymbol = createSymbol(3 /* Variable */, "args", 32768 /* RestParameter */);
53727             syntheticArgsSymbol.type = lastParamVariadicType ? createArrayType(getTypeFromTypeNode(lastParamVariadicType.type)) : anyArrayType;
53728             if (lastParamVariadicType) {
53729                 // Replace the last parameter with a rest parameter.
53730                 parameters.pop();
53731             }
53732             parameters.push(syntheticArgsSymbol);
53733             return true;
53734         }
53735         function getSignatureOfTypeTag(node) {
53736             // should be attached to a function declaration or expression
53737             if (!(ts.isInJSFile(node) && ts.isFunctionLikeDeclaration(node)))
53738                 return undefined;
53739             var typeTag = ts.getJSDocTypeTag(node);
53740             var signature = typeTag && typeTag.typeExpression && getSingleCallSignature(getTypeFromTypeNode(typeTag.typeExpression));
53741             return signature && getErasedSignature(signature);
53742         }
53743         function getReturnTypeOfTypeTag(node) {
53744             var signature = getSignatureOfTypeTag(node);
53745             return signature && getReturnTypeOfSignature(signature);
53746         }
53747         function containsArgumentsReference(declaration) {
53748             var links = getNodeLinks(declaration);
53749             if (links.containsArgumentsReference === undefined) {
53750                 if (links.flags & 8192 /* CaptureArguments */) {
53751                     links.containsArgumentsReference = true;
53752                 }
53753                 else {
53754                     links.containsArgumentsReference = traverse(declaration.body);
53755                 }
53756             }
53757             return links.containsArgumentsReference;
53758             function traverse(node) {
53759                 if (!node)
53760                     return false;
53761                 switch (node.kind) {
53762                     case 78 /* Identifier */:
53763                         return node.escapedText === "arguments" && ts.isExpressionNode(node);
53764                     case 163 /* PropertyDeclaration */:
53765                     case 165 /* MethodDeclaration */:
53766                     case 167 /* GetAccessor */:
53767                     case 168 /* SetAccessor */:
53768                         return node.name.kind === 158 /* ComputedPropertyName */
53769                             && traverse(node.name);
53770                     default:
53771                         return !ts.nodeStartsNewLexicalEnvironment(node) && !ts.isPartOfTypeNode(node) && !!ts.forEachChild(node, traverse);
53772                 }
53773             }
53774         }
53775         function getSignaturesOfSymbol(symbol) {
53776             if (!symbol)
53777                 return ts.emptyArray;
53778             var result = [];
53779             for (var i = 0; i < symbol.declarations.length; i++) {
53780                 var decl = symbol.declarations[i];
53781                 if (!ts.isFunctionLike(decl))
53782                     continue;
53783                 // Don't include signature if node is the implementation of an overloaded function. A node is considered
53784                 // an implementation node if it has a body and the previous node is of the same kind and immediately
53785                 // precedes the implementation node (i.e. has the same parent and ends where the implementation starts).
53786                 if (i > 0 && decl.body) {
53787                     var previous = symbol.declarations[i - 1];
53788                     if (decl.parent === previous.parent && decl.kind === previous.kind && decl.pos === previous.end) {
53789                         continue;
53790                     }
53791                 }
53792                 result.push(getSignatureFromDeclaration(decl));
53793             }
53794             return result;
53795         }
53796         function resolveExternalModuleTypeByLiteral(name) {
53797             var moduleSym = resolveExternalModuleName(name, name);
53798             if (moduleSym) {
53799                 var resolvedModuleSymbol = resolveExternalModuleSymbol(moduleSym);
53800                 if (resolvedModuleSymbol) {
53801                     return getTypeOfSymbol(resolvedModuleSymbol);
53802                 }
53803             }
53804             return anyType;
53805         }
53806         function getThisTypeOfSignature(signature) {
53807             if (signature.thisParameter) {
53808                 return getTypeOfSymbol(signature.thisParameter);
53809             }
53810         }
53811         function getTypePredicateOfSignature(signature) {
53812             if (!signature.resolvedTypePredicate) {
53813                 if (signature.target) {
53814                     var targetTypePredicate = getTypePredicateOfSignature(signature.target);
53815                     signature.resolvedTypePredicate = targetTypePredicate ? instantiateTypePredicate(targetTypePredicate, signature.mapper) : noTypePredicate;
53816                 }
53817                 else if (signature.unionSignatures) {
53818                     signature.resolvedTypePredicate = getUnionTypePredicate(signature.unionSignatures) || noTypePredicate;
53819                 }
53820                 else {
53821                     var type = signature.declaration && ts.getEffectiveReturnTypeNode(signature.declaration);
53822                     var jsdocPredicate = void 0;
53823                     if (!type && ts.isInJSFile(signature.declaration)) {
53824                         var jsdocSignature = getSignatureOfTypeTag(signature.declaration);
53825                         if (jsdocSignature && signature !== jsdocSignature) {
53826                             jsdocPredicate = getTypePredicateOfSignature(jsdocSignature);
53827                         }
53828                     }
53829                     signature.resolvedTypePredicate = type && ts.isTypePredicateNode(type) ?
53830                         createTypePredicateFromTypePredicateNode(type, signature) :
53831                         jsdocPredicate || noTypePredicate;
53832                 }
53833                 ts.Debug.assert(!!signature.resolvedTypePredicate);
53834             }
53835             return signature.resolvedTypePredicate === noTypePredicate ? undefined : signature.resolvedTypePredicate;
53836         }
53837         function createTypePredicateFromTypePredicateNode(node, signature) {
53838             var parameterName = node.parameterName;
53839             var type = node.type && getTypeFromTypeNode(node.type);
53840             return parameterName.kind === 187 /* ThisType */ ?
53841                 createTypePredicate(node.assertsModifier ? 2 /* AssertsThis */ : 0 /* This */, /*parameterName*/ undefined, /*parameterIndex*/ undefined, type) :
53842                 createTypePredicate(node.assertsModifier ? 3 /* AssertsIdentifier */ : 1 /* Identifier */, parameterName.escapedText, ts.findIndex(signature.parameters, function (p) { return p.escapedName === parameterName.escapedText; }), type);
53843         }
53844         function getReturnTypeOfSignature(signature) {
53845             if (!signature.resolvedReturnType) {
53846                 if (!pushTypeResolution(signature, 3 /* ResolvedReturnType */)) {
53847                     return errorType;
53848                 }
53849                 var type = signature.target ? instantiateType(getReturnTypeOfSignature(signature.target), signature.mapper) :
53850                     signature.unionSignatures ? getUnionType(ts.map(signature.unionSignatures, getReturnTypeOfSignature), 2 /* Subtype */) :
53851                         getReturnTypeFromAnnotation(signature.declaration) ||
53852                             (ts.nodeIsMissing(signature.declaration.body) ? anyType : getReturnTypeFromBody(signature.declaration));
53853                 if (signature.flags & 4 /* IsInnerCallChain */) {
53854                     type = addOptionalTypeMarker(type);
53855                 }
53856                 else if (signature.flags & 8 /* IsOuterCallChain */) {
53857                     type = getOptionalType(type);
53858                 }
53859                 if (!popTypeResolution()) {
53860                     if (signature.declaration) {
53861                         var typeNode = ts.getEffectiveReturnTypeNode(signature.declaration);
53862                         if (typeNode) {
53863                             error(typeNode, ts.Diagnostics.Return_type_annotation_circularly_references_itself);
53864                         }
53865                         else if (noImplicitAny) {
53866                             var declaration = signature.declaration;
53867                             var name = ts.getNameOfDeclaration(declaration);
53868                             if (name) {
53869                                 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));
53870                             }
53871                             else {
53872                                 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);
53873                             }
53874                         }
53875                     }
53876                     type = anyType;
53877                 }
53878                 signature.resolvedReturnType = type;
53879             }
53880             return signature.resolvedReturnType;
53881         }
53882         function getReturnTypeFromAnnotation(declaration) {
53883             if (declaration.kind === 166 /* Constructor */) {
53884                 return getDeclaredTypeOfClassOrInterface(getMergedSymbol(declaration.parent.symbol));
53885             }
53886             if (ts.isJSDocConstructSignature(declaration)) {
53887                 return getTypeFromTypeNode(declaration.parameters[0].type); // TODO: GH#18217
53888             }
53889             var typeNode = ts.getEffectiveReturnTypeNode(declaration);
53890             if (typeNode) {
53891                 return getTypeFromTypeNode(typeNode);
53892             }
53893             if (declaration.kind === 167 /* GetAccessor */ && !hasNonBindableDynamicName(declaration)) {
53894                 var jsDocType = ts.isInJSFile(declaration) && getTypeForDeclarationFromJSDocComment(declaration);
53895                 if (jsDocType) {
53896                     return jsDocType;
53897                 }
53898                 var setter = ts.getDeclarationOfKind(getSymbolOfNode(declaration), 168 /* SetAccessor */);
53899                 var setterType = getAnnotatedAccessorType(setter);
53900                 if (setterType) {
53901                     return setterType;
53902                 }
53903             }
53904             return getReturnTypeOfTypeTag(declaration);
53905         }
53906         function isResolvingReturnTypeOfSignature(signature) {
53907             return !signature.resolvedReturnType && findResolutionCycleStartIndex(signature, 3 /* ResolvedReturnType */) >= 0;
53908         }
53909         function getRestTypeOfSignature(signature) {
53910             return tryGetRestTypeOfSignature(signature) || anyType;
53911         }
53912         function tryGetRestTypeOfSignature(signature) {
53913             if (signatureHasRestParameter(signature)) {
53914                 var sigRestType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
53915                 var restType = isTupleType(sigRestType) ? getRestTypeOfTupleType(sigRestType) : sigRestType;
53916                 return restType && getIndexTypeOfType(restType, 1 /* Number */);
53917             }
53918             return undefined;
53919         }
53920         function getSignatureInstantiation(signature, typeArguments, isJavascript, inferredTypeParameters) {
53921             var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, fillMissingTypeArguments(typeArguments, signature.typeParameters, getMinTypeArgumentCount(signature.typeParameters), isJavascript));
53922             if (inferredTypeParameters) {
53923                 var returnSignature = getSingleCallOrConstructSignature(getReturnTypeOfSignature(instantiatedSignature));
53924                 if (returnSignature) {
53925                     var newReturnSignature = cloneSignature(returnSignature);
53926                     newReturnSignature.typeParameters = inferredTypeParameters;
53927                     var newInstantiatedSignature = cloneSignature(instantiatedSignature);
53928                     newInstantiatedSignature.resolvedReturnType = getOrCreateTypeFromSignature(newReturnSignature);
53929                     return newInstantiatedSignature;
53930                 }
53931             }
53932             return instantiatedSignature;
53933         }
53934         function getSignatureInstantiationWithoutFillingInTypeArguments(signature, typeArguments) {
53935             var instantiations = signature.instantiations || (signature.instantiations = new ts.Map());
53936             var id = getTypeListId(typeArguments);
53937             var instantiation = instantiations.get(id);
53938             if (!instantiation) {
53939                 instantiations.set(id, instantiation = createSignatureInstantiation(signature, typeArguments));
53940             }
53941             return instantiation;
53942         }
53943         function createSignatureInstantiation(signature, typeArguments) {
53944             return instantiateSignature(signature, createSignatureTypeMapper(signature, typeArguments), /*eraseTypeParameters*/ true);
53945         }
53946         function createSignatureTypeMapper(signature, typeArguments) {
53947             return createTypeMapper(signature.typeParameters, typeArguments);
53948         }
53949         function getErasedSignature(signature) {
53950             return signature.typeParameters ?
53951                 signature.erasedSignatureCache || (signature.erasedSignatureCache = createErasedSignature(signature)) :
53952                 signature;
53953         }
53954         function createErasedSignature(signature) {
53955             // Create an instantiation of the signature where all type arguments are the any type.
53956             return instantiateSignature(signature, createTypeEraser(signature.typeParameters), /*eraseTypeParameters*/ true);
53957         }
53958         function getCanonicalSignature(signature) {
53959             return signature.typeParameters ?
53960                 signature.canonicalSignatureCache || (signature.canonicalSignatureCache = createCanonicalSignature(signature)) :
53961                 signature;
53962         }
53963         function createCanonicalSignature(signature) {
53964             // Create an instantiation of the signature where each unconstrained type parameter is replaced with
53965             // its original. When a generic class or interface is instantiated, each generic method in the class or
53966             // interface is instantiated with a fresh set of cloned type parameters (which we need to handle scenarios
53967             // where different generations of the same type parameter are in scope). This leads to a lot of new type
53968             // identities, and potentially a lot of work comparing those identities, so here we create an instantiation
53969             // that uses the original type identities for all unconstrained type parameters.
53970             return getSignatureInstantiation(signature, ts.map(signature.typeParameters, function (tp) { return tp.target && !getConstraintOfTypeParameter(tp.target) ? tp.target : tp; }), ts.isInJSFile(signature.declaration));
53971         }
53972         function getBaseSignature(signature) {
53973             var typeParameters = signature.typeParameters;
53974             if (typeParameters) {
53975                 var typeEraser_1 = createTypeEraser(typeParameters);
53976                 var baseConstraints = ts.map(typeParameters, function (tp) { return instantiateType(getBaseConstraintOfType(tp), typeEraser_1) || unknownType; });
53977                 return instantiateSignature(signature, createTypeMapper(typeParameters, baseConstraints), /*eraseTypeParameters*/ true);
53978             }
53979             return signature;
53980         }
53981         function getOrCreateTypeFromSignature(signature) {
53982             // There are two ways to declare a construct signature, one is by declaring a class constructor
53983             // using the constructor keyword, and the other is declaring a bare construct signature in an
53984             // object type literal or interface (using the new keyword). Each way of declaring a constructor
53985             // will result in a different declaration kind.
53986             if (!signature.isolatedSignatureType) {
53987                 var kind = signature.declaration ? signature.declaration.kind : 0 /* Unknown */;
53988                 var isConstructor = kind === 166 /* Constructor */ || kind === 170 /* ConstructSignature */ || kind === 175 /* ConstructorType */;
53989                 var type = createObjectType(16 /* Anonymous */);
53990                 type.members = emptySymbols;
53991                 type.properties = ts.emptyArray;
53992                 type.callSignatures = !isConstructor ? [signature] : ts.emptyArray;
53993                 type.constructSignatures = isConstructor ? [signature] : ts.emptyArray;
53994                 signature.isolatedSignatureType = type;
53995             }
53996             return signature.isolatedSignatureType;
53997         }
53998         function getIndexSymbol(symbol) {
53999             return symbol.members.get("__index" /* Index */);
54000         }
54001         function getIndexDeclarationOfSymbol(symbol, kind) {
54002             var syntaxKind = kind === 1 /* Number */ ? 144 /* NumberKeyword */ : 147 /* StringKeyword */;
54003             var indexSymbol = getIndexSymbol(symbol);
54004             if (indexSymbol) {
54005                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
54006                     var decl = _a[_i];
54007                     var node = ts.cast(decl, ts.isIndexSignatureDeclaration);
54008                     if (node.parameters.length === 1) {
54009                         var parameter = node.parameters[0];
54010                         if (parameter.type && parameter.type.kind === syntaxKind) {
54011                             return node;
54012                         }
54013                     }
54014                 }
54015             }
54016             return undefined;
54017         }
54018         function createIndexInfo(type, isReadonly, declaration) {
54019             return { type: type, isReadonly: isReadonly, declaration: declaration };
54020         }
54021         function getIndexInfoOfSymbol(symbol, kind) {
54022             var declaration = getIndexDeclarationOfSymbol(symbol, kind);
54023             if (declaration) {
54024                 return createIndexInfo(declaration.type ? getTypeFromTypeNode(declaration.type) : anyType, ts.hasEffectiveModifier(declaration, 64 /* Readonly */), declaration);
54025             }
54026             return undefined;
54027         }
54028         function getConstraintDeclaration(type) {
54029             return ts.mapDefined(ts.filter(type.symbol && type.symbol.declarations, ts.isTypeParameterDeclaration), ts.getEffectiveConstraintOfTypeParameter)[0];
54030         }
54031         function getInferredTypeParameterConstraint(typeParameter) {
54032             var inferences;
54033             if (typeParameter.symbol) {
54034                 for (var _i = 0, _a = typeParameter.symbol.declarations; _i < _a.length; _i++) {
54035                     var declaration = _a[_i];
54036                     if (declaration.parent.kind === 185 /* InferType */) {
54037                         // When an 'infer T' declaration is immediately contained in a type reference node
54038                         // (such as 'Foo<infer T>'), T's constraint is inferred from the constraint of the
54039                         // corresponding type parameter in 'Foo'. When multiple 'infer T' declarations are
54040                         // present, we form an intersection of the inferred constraint types.
54041                         var _b = ts.walkUpParenthesizedTypesAndGetParentAndChild(declaration.parent.parent), _c = _b[0], childTypeParameter = _c === void 0 ? declaration.parent : _c, grandParent = _b[1];
54042                         if (grandParent.kind === 173 /* TypeReference */) {
54043                             var typeReference = grandParent;
54044                             var typeParameters = getTypeParametersForTypeReference(typeReference);
54045                             if (typeParameters) {
54046                                 var index = typeReference.typeArguments.indexOf(childTypeParameter);
54047                                 if (index < typeParameters.length) {
54048                                     var declaredConstraint = getConstraintOfTypeParameter(typeParameters[index]);
54049                                     if (declaredConstraint) {
54050                                         // Type parameter constraints can reference other type parameters so
54051                                         // constraints need to be instantiated. If instantiation produces the
54052                                         // type parameter itself, we discard that inference. For example, in
54053                                         //   type Foo<T extends string, U extends T> = [T, U];
54054                                         //   type Bar<T> = T extends Foo<infer X, infer X> ? Foo<X, X> : T;
54055                                         // the instantiated constraint for U is X, so we discard that inference.
54056                                         var mapper = createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReference, typeParameters));
54057                                         var constraint = instantiateType(declaredConstraint, mapper);
54058                                         if (constraint !== typeParameter) {
54059                                             inferences = ts.append(inferences, constraint);
54060                                         }
54061                                     }
54062                                 }
54063                             }
54064                         }
54065                         // When an 'infer T' declaration is immediately contained in a rest parameter declaration, a rest type
54066                         // or a named rest tuple element, we infer an 'unknown[]' constraint.
54067                         else if (grandParent.kind === 160 /* Parameter */ && grandParent.dotDotDotToken ||
54068                             grandParent.kind === 181 /* RestType */ ||
54069                             grandParent.kind === 192 /* NamedTupleMember */ && grandParent.dotDotDotToken) {
54070                             inferences = ts.append(inferences, createArrayType(unknownType));
54071                         }
54072                         // When an 'infer T' declaration is immediately contained in a string template type, we infer a 'string'
54073                         // constraint.
54074                         else if (grandParent.kind === 194 /* TemplateLiteralTypeSpan */) {
54075                             inferences = ts.append(inferences, stringType);
54076                         }
54077                     }
54078                 }
54079             }
54080             return inferences && getIntersectionType(inferences);
54081         }
54082         /** This is a worker function. Use getConstraintOfTypeParameter which guards against circular constraints. */
54083         function getConstraintFromTypeParameter(typeParameter) {
54084             if (!typeParameter.constraint) {
54085                 if (typeParameter.target) {
54086                     var targetConstraint = getConstraintOfTypeParameter(typeParameter.target);
54087                     typeParameter.constraint = targetConstraint ? instantiateType(targetConstraint, typeParameter.mapper) : noConstraintType;
54088                 }
54089                 else {
54090                     var constraintDeclaration = getConstraintDeclaration(typeParameter);
54091                     if (!constraintDeclaration) {
54092                         typeParameter.constraint = getInferredTypeParameterConstraint(typeParameter) || noConstraintType;
54093                     }
54094                     else {
54095                         var type = getTypeFromTypeNode(constraintDeclaration);
54096                         if (type.flags & 1 /* Any */ && type !== errorType) { // Allow errorType to propegate to keep downstream errors suppressed
54097                             // use keyofConstraintType as the base constraint for mapped type key constraints (unknown isn;t assignable to that, but `any` was),
54098                             // use unknown otherwise
54099                             type = constraintDeclaration.parent.parent.kind === 190 /* MappedType */ ? keyofConstraintType : unknownType;
54100                         }
54101                         typeParameter.constraint = type;
54102                     }
54103                 }
54104             }
54105             return typeParameter.constraint === noConstraintType ? undefined : typeParameter.constraint;
54106         }
54107         function getParentSymbolOfTypeParameter(typeParameter) {
54108             var tp = ts.getDeclarationOfKind(typeParameter.symbol, 159 /* TypeParameter */);
54109             var host = ts.isJSDocTemplateTag(tp.parent) ? ts.getHostSignatureFromJSDoc(tp.parent) : tp.parent;
54110             return host && getSymbolOfNode(host);
54111         }
54112         function getTypeListId(types) {
54113             var result = "";
54114             if (types) {
54115                 var length_4 = types.length;
54116                 var i = 0;
54117                 while (i < length_4) {
54118                     var startId = types[i].id;
54119                     var count = 1;
54120                     while (i + count < length_4 && types[i + count].id === startId + count) {
54121                         count++;
54122                     }
54123                     if (result.length) {
54124                         result += ",";
54125                     }
54126                     result += startId;
54127                     if (count > 1) {
54128                         result += ":" + count;
54129                     }
54130                     i += count;
54131                 }
54132             }
54133             return result;
54134         }
54135         // This function is used to propagate certain flags when creating new object type references and union types.
54136         // It is only necessary to do so if a constituent type might be the undefined type, the null type, the type
54137         // of an object literal or the anyFunctionType. This is because there are operations in the type checker
54138         // that care about the presence of such types at arbitrary depth in a containing type.
54139         function getPropagatingFlagsOfTypes(types, excludeKinds) {
54140             var result = 0;
54141             for (var _i = 0, types_9 = types; _i < types_9.length; _i++) {
54142                 var type = types_9[_i];
54143                 if (!(type.flags & excludeKinds)) {
54144                     result |= ts.getObjectFlags(type);
54145                 }
54146             }
54147             return result & 3670016 /* PropagatingFlags */;
54148         }
54149         function createTypeReference(target, typeArguments) {
54150             var id = getTypeListId(typeArguments);
54151             var type = target.instantiations.get(id);
54152             if (!type) {
54153                 type = createObjectType(4 /* Reference */, target.symbol);
54154                 target.instantiations.set(id, type);
54155                 type.objectFlags |= typeArguments ? getPropagatingFlagsOfTypes(typeArguments, /*excludeKinds*/ 0) : 0;
54156                 type.target = target;
54157                 type.resolvedTypeArguments = typeArguments;
54158             }
54159             return type;
54160         }
54161         function cloneTypeReference(source) {
54162             var type = createType(source.flags);
54163             type.symbol = source.symbol;
54164             type.objectFlags = source.objectFlags;
54165             type.target = source.target;
54166             type.resolvedTypeArguments = source.resolvedTypeArguments;
54167             return type;
54168         }
54169         function createDeferredTypeReference(target, node, mapper) {
54170             var aliasSymbol = getAliasSymbolForTypeNode(node);
54171             var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
54172             var type = createObjectType(4 /* Reference */, target.symbol);
54173             type.target = target;
54174             type.node = node;
54175             type.mapper = mapper;
54176             type.aliasSymbol = aliasSymbol;
54177             type.aliasTypeArguments = mapper ? instantiateTypes(aliasTypeArguments, mapper) : aliasTypeArguments;
54178             return type;
54179         }
54180         function getTypeArguments(type) {
54181             var _a, _b;
54182             if (!type.resolvedTypeArguments) {
54183                 if (!pushTypeResolution(type, 6 /* ResolvedTypeArguments */)) {
54184                     return ((_a = type.target.localTypeParameters) === null || _a === void 0 ? void 0 : _a.map(function () { return errorType; })) || ts.emptyArray;
54185                 }
54186                 var node = type.node;
54187                 var typeArguments = !node ? ts.emptyArray :
54188                     node.kind === 173 /* TypeReference */ ? ts.concatenate(type.target.outerTypeParameters, getEffectiveTypeArguments(node, type.target.localTypeParameters)) :
54189                         node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] :
54190                             ts.map(node.elements, getTypeFromTypeNode);
54191                 if (popTypeResolution()) {
54192                     type.resolvedTypeArguments = type.mapper ? instantiateTypes(typeArguments, type.mapper) : typeArguments;
54193                 }
54194                 else {
54195                     type.resolvedTypeArguments = ((_b = type.target.localTypeParameters) === null || _b === void 0 ? void 0 : _b.map(function () { return errorType; })) || ts.emptyArray;
54196                     error(type.node || currentNode, type.target.symbol ? ts.Diagnostics.Type_arguments_for_0_circularly_reference_themselves : ts.Diagnostics.Tuple_type_arguments_circularly_reference_themselves, type.target.symbol && symbolToString(type.target.symbol));
54197                 }
54198             }
54199             return type.resolvedTypeArguments;
54200         }
54201         function getTypeReferenceArity(type) {
54202             return ts.length(type.target.typeParameters);
54203         }
54204         /**
54205          * Get type from type-reference that reference to class or interface
54206          */
54207         function getTypeFromClassOrInterfaceReference(node, symbol) {
54208             var type = getDeclaredTypeOfSymbol(getMergedSymbol(symbol));
54209             var typeParameters = type.localTypeParameters;
54210             if (typeParameters) {
54211                 var numTypeArguments = ts.length(node.typeArguments);
54212                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
54213                 var isJs = ts.isInJSFile(node);
54214                 var isJsImplicitAny = !noImplicitAny && isJs;
54215                 if (!isJsImplicitAny && (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length)) {
54216                     var missingAugmentsTag = isJs && ts.isExpressionWithTypeArguments(node) && !ts.isJSDocAugmentsTag(node.parent);
54217                     var diag = minTypeArgumentCount === typeParameters.length ?
54218                         missingAugmentsTag ?
54219                             ts.Diagnostics.Expected_0_type_arguments_provide_these_with_an_extends_tag :
54220                             ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
54221                         missingAugmentsTag ?
54222                             ts.Diagnostics.Expected_0_1_type_arguments_provide_these_with_an_extends_tag :
54223                             ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments;
54224                     var typeStr = typeToString(type, /*enclosingDeclaration*/ undefined, 2 /* WriteArrayAsGenericType */);
54225                     error(node, diag, typeStr, minTypeArgumentCount, typeParameters.length);
54226                     if (!isJs) {
54227                         // TODO: Adopt same permissive behavior in TS as in JS to reduce follow-on editing experience failures (requires editing fillMissingTypeArguments)
54228                         return errorType;
54229                     }
54230                 }
54231                 if (node.kind === 173 /* TypeReference */ && isDeferredTypeReferenceNode(node, ts.length(node.typeArguments) !== typeParameters.length)) {
54232                     return createDeferredTypeReference(type, node, /*mapper*/ undefined);
54233                 }
54234                 // In a type reference, the outer type parameters of the referenced class or interface are automatically
54235                 // supplied as type arguments and the type reference only specifies arguments for the local type parameters
54236                 // of the class or interface.
54237                 var typeArguments = ts.concatenate(type.outerTypeParameters, fillMissingTypeArguments(typeArgumentsFromTypeReferenceNode(node), typeParameters, minTypeArgumentCount, isJs));
54238                 return createTypeReference(type, typeArguments);
54239             }
54240             return checkNoTypeArguments(node, symbol) ? type : errorType;
54241         }
54242         function getTypeAliasInstantiation(symbol, typeArguments) {
54243             var type = getDeclaredTypeOfSymbol(symbol);
54244             if (type === intrinsicMarkerType && intrinsicTypeKinds.has(symbol.escapedName) && typeArguments && typeArguments.length === 1) {
54245                 return getStringMappingType(symbol, typeArguments[0]);
54246             }
54247             var links = getSymbolLinks(symbol);
54248             var typeParameters = links.typeParameters;
54249             var id = getTypeListId(typeArguments);
54250             var instantiation = links.instantiations.get(id);
54251             if (!instantiation) {
54252                 links.instantiations.set(id, instantiation = instantiateType(type, createTypeMapper(typeParameters, fillMissingTypeArguments(typeArguments, typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(symbol.valueDeclaration)))));
54253             }
54254             return instantiation;
54255         }
54256         /**
54257          * Get type from reference to type alias. When a type alias is generic, the declared type of the type alias may include
54258          * references to the type parameters of the alias. We replace those with the actual type arguments by instantiating the
54259          * declared type. Instantiations are cached using the type identities of the type arguments as the key.
54260          */
54261         function getTypeFromTypeAliasReference(node, symbol) {
54262             var type = getDeclaredTypeOfSymbol(symbol);
54263             var typeParameters = getSymbolLinks(symbol).typeParameters;
54264             if (typeParameters) {
54265                 var numTypeArguments = ts.length(node.typeArguments);
54266                 var minTypeArgumentCount = getMinTypeArgumentCount(typeParameters);
54267                 if (numTypeArguments < minTypeArgumentCount || numTypeArguments > typeParameters.length) {
54268                     error(node, minTypeArgumentCount === typeParameters.length ?
54269                         ts.Diagnostics.Generic_type_0_requires_1_type_argument_s :
54270                         ts.Diagnostics.Generic_type_0_requires_between_1_and_2_type_arguments, symbolToString(symbol), minTypeArgumentCount, typeParameters.length);
54271                     return errorType;
54272                 }
54273                 return getTypeAliasInstantiation(symbol, typeArgumentsFromTypeReferenceNode(node));
54274             }
54275             return checkNoTypeArguments(node, symbol) ? type : errorType;
54276         }
54277         function getTypeReferenceName(node) {
54278             switch (node.kind) {
54279                 case 173 /* TypeReference */:
54280                     return node.typeName;
54281                 case 223 /* ExpressionWithTypeArguments */:
54282                     // We only support expressions that are simple qualified names. For other
54283                     // expressions this produces undefined.
54284                     var expr = node.expression;
54285                     if (ts.isEntityNameExpression(expr)) {
54286                         return expr;
54287                     }
54288                 // fall through;
54289             }
54290             return undefined;
54291         }
54292         function resolveTypeReferenceName(typeReferenceName, meaning, ignoreErrors) {
54293             if (!typeReferenceName) {
54294                 return unknownSymbol;
54295             }
54296             return resolveEntityName(typeReferenceName, meaning, ignoreErrors) || unknownSymbol;
54297         }
54298         function getTypeReferenceType(node, symbol) {
54299             if (symbol === unknownSymbol) {
54300                 return errorType;
54301             }
54302             symbol = getExpandoSymbol(symbol) || symbol;
54303             if (symbol.flags & (32 /* Class */ | 64 /* Interface */)) {
54304                 return getTypeFromClassOrInterfaceReference(node, symbol);
54305             }
54306             if (symbol.flags & 524288 /* TypeAlias */) {
54307                 return getTypeFromTypeAliasReference(node, symbol);
54308             }
54309             // Get type from reference to named type that cannot be generic (enum or type parameter)
54310             var res = tryGetDeclaredTypeOfSymbol(symbol);
54311             if (res) {
54312                 return checkNoTypeArguments(node, symbol) ? getRegularTypeOfLiteralType(res) : errorType;
54313             }
54314             if (symbol.flags & 111551 /* Value */ && isJSDocTypeReference(node)) {
54315                 var jsdocType = getTypeFromJSDocValueReference(node, symbol);
54316                 if (jsdocType) {
54317                     return jsdocType;
54318                 }
54319                 else {
54320                     // Resolve the type reference as a Type for the purpose of reporting errors.
54321                     resolveTypeReferenceName(getTypeReferenceName(node), 788968 /* Type */);
54322                     return getTypeOfSymbol(symbol);
54323                 }
54324             }
54325             return errorType;
54326         }
54327         /**
54328          * A JSdoc TypeReference may be to a value, but resolve it as a type anyway.
54329          * Example: import('./b').ConstructorFunction
54330          */
54331         function getTypeFromJSDocValueReference(node, symbol) {
54332             var links = getNodeLinks(node);
54333             if (!links.resolvedJSDocType) {
54334                 var valueType = getTypeOfSymbol(symbol);
54335                 var typeType = valueType;
54336                 if (symbol.valueDeclaration) {
54337                     var isImportTypeWithQualifier = node.kind === 195 /* ImportType */ && node.qualifier;
54338                     // valueType might not have a symbol, eg, {import('./b').STRING_LITERAL}
54339                     if (valueType.symbol && valueType.symbol !== symbol && isImportTypeWithQualifier) {
54340                         typeType = getTypeReferenceType(node, valueType.symbol);
54341                     }
54342                 }
54343                 links.resolvedJSDocType = typeType;
54344             }
54345             return links.resolvedJSDocType;
54346         }
54347         function getSubstitutionType(baseType, substitute) {
54348             if (substitute.flags & 3 /* AnyOrUnknown */ || substitute === baseType) {
54349                 return baseType;
54350             }
54351             var id = getTypeId(baseType) + ">" + getTypeId(substitute);
54352             var cached = substitutionTypes.get(id);
54353             if (cached) {
54354                 return cached;
54355             }
54356             var result = createType(33554432 /* Substitution */);
54357             result.baseType = baseType;
54358             result.substitute = substitute;
54359             substitutionTypes.set(id, result);
54360             return result;
54361         }
54362         function isUnaryTupleTypeNode(node) {
54363             return node.kind === 179 /* TupleType */ && node.elements.length === 1;
54364         }
54365         function getImpliedConstraint(type, checkNode, extendsNode) {
54366             return isUnaryTupleTypeNode(checkNode) && isUnaryTupleTypeNode(extendsNode) ? getImpliedConstraint(type, checkNode.elements[0], extendsNode.elements[0]) :
54367                 getActualTypeVariable(getTypeFromTypeNode(checkNode)) === type ? getTypeFromTypeNode(extendsNode) :
54368                     undefined;
54369         }
54370         function getConditionalFlowTypeOfType(type, node) {
54371             var constraints;
54372             while (node && !ts.isStatement(node) && node.kind !== 311 /* JSDocComment */) {
54373                 var parent = node.parent;
54374                 if (parent.kind === 184 /* ConditionalType */ && node === parent.trueType) {
54375                     var constraint = getImpliedConstraint(type, parent.checkType, parent.extendsType);
54376                     if (constraint) {
54377                         constraints = ts.append(constraints, constraint);
54378                     }
54379                 }
54380                 node = parent;
54381             }
54382             return constraints ? getSubstitutionType(type, getIntersectionType(ts.append(constraints, type))) : type;
54383         }
54384         function isJSDocTypeReference(node) {
54385             return !!(node.flags & 4194304 /* JSDoc */) && (node.kind === 173 /* TypeReference */ || node.kind === 195 /* ImportType */);
54386         }
54387         function checkNoTypeArguments(node, symbol) {
54388             if (node.typeArguments) {
54389                 error(node, ts.Diagnostics.Type_0_is_not_generic, symbol ? symbolToString(symbol) : node.typeName ? ts.declarationNameToString(node.typeName) : anon);
54390                 return false;
54391             }
54392             return true;
54393         }
54394         function getIntendedTypeFromJSDocTypeReference(node) {
54395             if (ts.isIdentifier(node.typeName)) {
54396                 var typeArgs = node.typeArguments;
54397                 switch (node.typeName.escapedText) {
54398                     case "String":
54399                         checkNoTypeArguments(node);
54400                         return stringType;
54401                     case "Number":
54402                         checkNoTypeArguments(node);
54403                         return numberType;
54404                     case "Boolean":
54405                         checkNoTypeArguments(node);
54406                         return booleanType;
54407                     case "Void":
54408                         checkNoTypeArguments(node);
54409                         return voidType;
54410                     case "Undefined":
54411                         checkNoTypeArguments(node);
54412                         return undefinedType;
54413                     case "Null":
54414                         checkNoTypeArguments(node);
54415                         return nullType;
54416                     case "Function":
54417                     case "function":
54418                         checkNoTypeArguments(node);
54419                         return globalFunctionType;
54420                     case "array":
54421                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? anyArrayType : undefined;
54422                     case "promise":
54423                         return (!typeArgs || !typeArgs.length) && !noImplicitAny ? createPromiseType(anyType) : undefined;
54424                     case "Object":
54425                         if (typeArgs && typeArgs.length === 2) {
54426                             if (ts.isJSDocIndexSignature(node)) {
54427                                 var indexed = getTypeFromTypeNode(typeArgs[0]);
54428                                 var target = getTypeFromTypeNode(typeArgs[1]);
54429                                 var index = createIndexInfo(target, /*isReadonly*/ false);
54430                                 return createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, indexed === stringType ? index : undefined, indexed === numberType ? index : undefined);
54431                             }
54432                             return anyType;
54433                         }
54434                         checkNoTypeArguments(node);
54435                         return !noImplicitAny ? anyType : undefined;
54436                 }
54437             }
54438         }
54439         function getTypeFromJSDocNullableTypeNode(node) {
54440             var type = getTypeFromTypeNode(node.type);
54441             return strictNullChecks ? getNullableType(type, 65536 /* Null */) : type;
54442         }
54443         function getTypeFromTypeReference(node) {
54444             var links = getNodeLinks(node);
54445             if (!links.resolvedType) {
54446                 // handle LS queries on the `const` in `x as const` by resolving to the type of `x`
54447                 if (ts.isConstTypeReference(node) && ts.isAssertionExpression(node.parent)) {
54448                     links.resolvedSymbol = unknownSymbol;
54449                     return links.resolvedType = checkExpressionCached(node.parent.expression);
54450                 }
54451                 var symbol = void 0;
54452                 var type = void 0;
54453                 var meaning = 788968 /* Type */;
54454                 if (isJSDocTypeReference(node)) {
54455                     type = getIntendedTypeFromJSDocTypeReference(node);
54456                     if (!type) {
54457                         symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning, /*ignoreErrors*/ true);
54458                         if (symbol === unknownSymbol) {
54459                             symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning | 111551 /* Value */);
54460                         }
54461                         else {
54462                             resolveTypeReferenceName(getTypeReferenceName(node), meaning); // Resolve again to mark errors, if any
54463                         }
54464                         type = getTypeReferenceType(node, symbol);
54465                     }
54466                 }
54467                 if (!type) {
54468                     symbol = resolveTypeReferenceName(getTypeReferenceName(node), meaning);
54469                     type = getTypeReferenceType(node, symbol);
54470                 }
54471                 // Cache both the resolved symbol and the resolved type. The resolved symbol is needed when we check the
54472                 // type reference in checkTypeReferenceNode.
54473                 links.resolvedSymbol = symbol;
54474                 links.resolvedType = type;
54475             }
54476             return links.resolvedType;
54477         }
54478         function typeArgumentsFromTypeReferenceNode(node) {
54479             return ts.map(node.typeArguments, getTypeFromTypeNode);
54480         }
54481         function getTypeFromTypeQueryNode(node) {
54482             var links = getNodeLinks(node);
54483             if (!links.resolvedType) {
54484                 // TypeScript 1.0 spec (April 2014): 3.6.3
54485                 // The expression is processed as an identifier expression (section 4.3)
54486                 // or property access expression(section 4.10),
54487                 // the widened type(section 3.9) of which becomes the result.
54488                 links.resolvedType = getRegularTypeOfLiteralType(getWidenedType(checkExpression(node.exprName)));
54489             }
54490             return links.resolvedType;
54491         }
54492         function getTypeOfGlobalSymbol(symbol, arity) {
54493             function getTypeDeclaration(symbol) {
54494                 var declarations = symbol.declarations;
54495                 for (var _i = 0, declarations_3 = declarations; _i < declarations_3.length; _i++) {
54496                     var declaration = declarations_3[_i];
54497                     switch (declaration.kind) {
54498                         case 252 /* ClassDeclaration */:
54499                         case 253 /* InterfaceDeclaration */:
54500                         case 255 /* EnumDeclaration */:
54501                             return declaration;
54502                     }
54503                 }
54504             }
54505             if (!symbol) {
54506                 return arity ? emptyGenericType : emptyObjectType;
54507             }
54508             var type = getDeclaredTypeOfSymbol(symbol);
54509             if (!(type.flags & 524288 /* Object */)) {
54510                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_be_a_class_or_interface_type, ts.symbolName(symbol));
54511                 return arity ? emptyGenericType : emptyObjectType;
54512             }
54513             if (ts.length(type.typeParameters) !== arity) {
54514                 error(getTypeDeclaration(symbol), ts.Diagnostics.Global_type_0_must_have_1_type_parameter_s, ts.symbolName(symbol), arity);
54515                 return arity ? emptyGenericType : emptyObjectType;
54516             }
54517             return type;
54518         }
54519         function getGlobalValueSymbol(name, reportErrors) {
54520             return getGlobalSymbol(name, 111551 /* Value */, reportErrors ? ts.Diagnostics.Cannot_find_global_value_0 : undefined);
54521         }
54522         function getGlobalTypeSymbol(name, reportErrors) {
54523             return getGlobalSymbol(name, 788968 /* Type */, reportErrors ? ts.Diagnostics.Cannot_find_global_type_0 : undefined);
54524         }
54525         function getGlobalSymbol(name, meaning, diagnostic) {
54526             // Don't track references for global symbols anyway, so value if `isReference` is arbitrary
54527             return resolveName(undefined, name, meaning, diagnostic, name, /*isUse*/ false);
54528         }
54529         function getGlobalType(name, arity, reportErrors) {
54530             var symbol = getGlobalTypeSymbol(name, reportErrors);
54531             return symbol || reportErrors ? getTypeOfGlobalSymbol(symbol, arity) : undefined;
54532         }
54533         function getGlobalTypedPropertyDescriptorType() {
54534             return deferredGlobalTypedPropertyDescriptorType || (deferredGlobalTypedPropertyDescriptorType = getGlobalType("TypedPropertyDescriptor", /*arity*/ 1, /*reportErrors*/ true)) || emptyGenericType;
54535         }
54536         function getGlobalTemplateStringsArrayType() {
54537             return deferredGlobalTemplateStringsArrayType || (deferredGlobalTemplateStringsArrayType = getGlobalType("TemplateStringsArray", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
54538         }
54539         function getGlobalImportMetaType() {
54540             return deferredGlobalImportMetaType || (deferredGlobalImportMetaType = getGlobalType("ImportMeta", /*arity*/ 0, /*reportErrors*/ true)) || emptyObjectType;
54541         }
54542         function getGlobalESSymbolConstructorSymbol(reportErrors) {
54543             return deferredGlobalESSymbolConstructorSymbol || (deferredGlobalESSymbolConstructorSymbol = getGlobalValueSymbol("Symbol", reportErrors));
54544         }
54545         function getGlobalESSymbolType(reportErrors) {
54546             return deferredGlobalESSymbolType || (deferredGlobalESSymbolType = getGlobalType("Symbol", /*arity*/ 0, reportErrors)) || emptyObjectType;
54547         }
54548         function getGlobalPromiseType(reportErrors) {
54549             return deferredGlobalPromiseType || (deferredGlobalPromiseType = getGlobalType("Promise", /*arity*/ 1, reportErrors)) || emptyGenericType;
54550         }
54551         function getGlobalPromiseLikeType(reportErrors) {
54552             return deferredGlobalPromiseLikeType || (deferredGlobalPromiseLikeType = getGlobalType("PromiseLike", /*arity*/ 1, reportErrors)) || emptyGenericType;
54553         }
54554         function getGlobalPromiseConstructorSymbol(reportErrors) {
54555             return deferredGlobalPromiseConstructorSymbol || (deferredGlobalPromiseConstructorSymbol = getGlobalValueSymbol("Promise", reportErrors));
54556         }
54557         function getGlobalPromiseConstructorLikeType(reportErrors) {
54558             return deferredGlobalPromiseConstructorLikeType || (deferredGlobalPromiseConstructorLikeType = getGlobalType("PromiseConstructorLike", /*arity*/ 0, reportErrors)) || emptyObjectType;
54559         }
54560         function getGlobalAsyncIterableType(reportErrors) {
54561             return deferredGlobalAsyncIterableType || (deferredGlobalAsyncIterableType = getGlobalType("AsyncIterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
54562         }
54563         function getGlobalAsyncIteratorType(reportErrors) {
54564             return deferredGlobalAsyncIteratorType || (deferredGlobalAsyncIteratorType = getGlobalType("AsyncIterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
54565         }
54566         function getGlobalAsyncIterableIteratorType(reportErrors) {
54567             return deferredGlobalAsyncIterableIteratorType || (deferredGlobalAsyncIterableIteratorType = getGlobalType("AsyncIterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
54568         }
54569         function getGlobalAsyncGeneratorType(reportErrors) {
54570             return deferredGlobalAsyncGeneratorType || (deferredGlobalAsyncGeneratorType = getGlobalType("AsyncGenerator", /*arity*/ 3, reportErrors)) || emptyGenericType;
54571         }
54572         function getGlobalIterableType(reportErrors) {
54573             return deferredGlobalIterableType || (deferredGlobalIterableType = getGlobalType("Iterable", /*arity*/ 1, reportErrors)) || emptyGenericType;
54574         }
54575         function getGlobalIteratorType(reportErrors) {
54576             return deferredGlobalIteratorType || (deferredGlobalIteratorType = getGlobalType("Iterator", /*arity*/ 3, reportErrors)) || emptyGenericType;
54577         }
54578         function getGlobalIterableIteratorType(reportErrors) {
54579             return deferredGlobalIterableIteratorType || (deferredGlobalIterableIteratorType = getGlobalType("IterableIterator", /*arity*/ 1, reportErrors)) || emptyGenericType;
54580         }
54581         function getGlobalGeneratorType(reportErrors) {
54582             return deferredGlobalGeneratorType || (deferredGlobalGeneratorType = getGlobalType("Generator", /*arity*/ 3, reportErrors)) || emptyGenericType;
54583         }
54584         function getGlobalIteratorYieldResultType(reportErrors) {
54585             return deferredGlobalIteratorYieldResultType || (deferredGlobalIteratorYieldResultType = getGlobalType("IteratorYieldResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
54586         }
54587         function getGlobalIteratorReturnResultType(reportErrors) {
54588             return deferredGlobalIteratorReturnResultType || (deferredGlobalIteratorReturnResultType = getGlobalType("IteratorReturnResult", /*arity*/ 1, reportErrors)) || emptyGenericType;
54589         }
54590         function getGlobalTypeOrUndefined(name, arity) {
54591             if (arity === void 0) { arity = 0; }
54592             var symbol = getGlobalSymbol(name, 788968 /* Type */, /*diagnostic*/ undefined);
54593             return symbol && getTypeOfGlobalSymbol(symbol, arity);
54594         }
54595         function getGlobalExtractSymbol() {
54596             return deferredGlobalExtractSymbol || (deferredGlobalExtractSymbol = getGlobalSymbol("Extract", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
54597         }
54598         function getGlobalOmitSymbol() {
54599             return deferredGlobalOmitSymbol || (deferredGlobalOmitSymbol = getGlobalSymbol("Omit", 524288 /* TypeAlias */, ts.Diagnostics.Cannot_find_global_type_0)); // TODO: GH#18217
54600         }
54601         function getGlobalBigIntType(reportErrors) {
54602             return deferredGlobalBigIntType || (deferredGlobalBigIntType = getGlobalType("BigInt", /*arity*/ 0, reportErrors)) || emptyObjectType;
54603         }
54604         /**
54605          * Instantiates a global type that is generic with some element type, and returns that instantiation.
54606          */
54607         function createTypeFromGenericGlobalType(genericGlobalType, typeArguments) {
54608             return genericGlobalType !== emptyGenericType ? createTypeReference(genericGlobalType, typeArguments) : emptyObjectType;
54609         }
54610         function createTypedPropertyDescriptorType(propertyType) {
54611             return createTypeFromGenericGlobalType(getGlobalTypedPropertyDescriptorType(), [propertyType]);
54612         }
54613         function createIterableType(iteratedType) {
54614             return createTypeFromGenericGlobalType(getGlobalIterableType(/*reportErrors*/ true), [iteratedType]);
54615         }
54616         function createArrayType(elementType, readonly) {
54617             return createTypeFromGenericGlobalType(readonly ? globalReadonlyArrayType : globalArrayType, [elementType]);
54618         }
54619         function getTupleElementFlags(node) {
54620             switch (node.kind) {
54621                 case 180 /* OptionalType */:
54622                     return 2 /* Optional */;
54623                 case 181 /* RestType */:
54624                     return getRestTypeElementFlags(node);
54625                 case 192 /* NamedTupleMember */:
54626                     return node.questionToken ? 2 /* Optional */ :
54627                         node.dotDotDotToken ? getRestTypeElementFlags(node) :
54628                             1 /* Required */;
54629                 default:
54630                     return 1 /* Required */;
54631             }
54632         }
54633         function getRestTypeElementFlags(node) {
54634             return getArrayElementTypeNode(node.type) ? 4 /* Rest */ : 8 /* Variadic */;
54635         }
54636         function getArrayOrTupleTargetType(node) {
54637             var readonly = isReadonlyTypeOperator(node.parent);
54638             var elementType = getArrayElementTypeNode(node);
54639             if (elementType) {
54640                 return readonly ? globalReadonlyArrayType : globalArrayType;
54641             }
54642             var elementFlags = ts.map(node.elements, getTupleElementFlags);
54643             var missingName = ts.some(node.elements, function (e) { return e.kind !== 192 /* NamedTupleMember */; });
54644             return getTupleTargetType(elementFlags, readonly, /*associatedNames*/ missingName ? undefined : node.elements);
54645         }
54646         // Return true if the given type reference node is directly aliased or if it needs to be deferred
54647         // because it is possibly contained in a circular chain of eagerly resolved types.
54648         function isDeferredTypeReferenceNode(node, hasDefaultTypeArguments) {
54649             return !!getAliasSymbolForTypeNode(node) || isResolvedByTypeAlias(node) && (node.kind === 178 /* ArrayType */ ? mayResolveTypeAlias(node.elementType) :
54650                 node.kind === 179 /* TupleType */ ? ts.some(node.elements, mayResolveTypeAlias) :
54651                     hasDefaultTypeArguments || ts.some(node.typeArguments, mayResolveTypeAlias));
54652         }
54653         // Return true when the given node is transitively contained in type constructs that eagerly
54654         // resolve their constituent types. We include SyntaxKind.TypeReference because type arguments
54655         // of type aliases are eagerly resolved.
54656         function isResolvedByTypeAlias(node) {
54657             var parent = node.parent;
54658             switch (parent.kind) {
54659                 case 186 /* ParenthesizedType */:
54660                 case 192 /* NamedTupleMember */:
54661                 case 173 /* TypeReference */:
54662                 case 182 /* UnionType */:
54663                 case 183 /* IntersectionType */:
54664                 case 189 /* IndexedAccessType */:
54665                 case 184 /* ConditionalType */:
54666                 case 188 /* TypeOperator */:
54667                 case 178 /* ArrayType */:
54668                 case 179 /* TupleType */:
54669                     return isResolvedByTypeAlias(parent);
54670                 case 254 /* TypeAliasDeclaration */:
54671                     return true;
54672             }
54673             return false;
54674         }
54675         // Return true if resolving the given node (i.e. getTypeFromTypeNode) possibly causes resolution
54676         // of a type alias.
54677         function mayResolveTypeAlias(node) {
54678             switch (node.kind) {
54679                 case 173 /* TypeReference */:
54680                     return isJSDocTypeReference(node) || !!(resolveTypeReferenceName(node.typeName, 788968 /* Type */).flags & 524288 /* TypeAlias */);
54681                 case 176 /* TypeQuery */:
54682                     return true;
54683                 case 188 /* TypeOperator */:
54684                     return node.operator !== 151 /* UniqueKeyword */ && mayResolveTypeAlias(node.type);
54685                 case 186 /* ParenthesizedType */:
54686                 case 180 /* OptionalType */:
54687                 case 192 /* NamedTupleMember */:
54688                 case 307 /* JSDocOptionalType */:
54689                 case 305 /* JSDocNullableType */:
54690                 case 306 /* JSDocNonNullableType */:
54691                 case 301 /* JSDocTypeExpression */:
54692                     return mayResolveTypeAlias(node.type);
54693                 case 181 /* RestType */:
54694                     return node.type.kind !== 178 /* ArrayType */ || mayResolveTypeAlias(node.type.elementType);
54695                 case 182 /* UnionType */:
54696                 case 183 /* IntersectionType */:
54697                     return ts.some(node.types, mayResolveTypeAlias);
54698                 case 189 /* IndexedAccessType */:
54699                     return mayResolveTypeAlias(node.objectType) || mayResolveTypeAlias(node.indexType);
54700                 case 184 /* ConditionalType */:
54701                     return mayResolveTypeAlias(node.checkType) || mayResolveTypeAlias(node.extendsType) ||
54702                         mayResolveTypeAlias(node.trueType) || mayResolveTypeAlias(node.falseType);
54703             }
54704             return false;
54705         }
54706         function getTypeFromArrayOrTupleTypeNode(node) {
54707             var links = getNodeLinks(node);
54708             if (!links.resolvedType) {
54709                 var target = getArrayOrTupleTargetType(node);
54710                 if (target === emptyGenericType) {
54711                     links.resolvedType = emptyObjectType;
54712                 }
54713                 else if (!(node.kind === 179 /* TupleType */ && ts.some(node.elements, function (e) { return !!(getTupleElementFlags(e) & 8 /* Variadic */); })) && isDeferredTypeReferenceNode(node)) {
54714                     links.resolvedType = node.kind === 179 /* TupleType */ && node.elements.length === 0 ? target :
54715                         createDeferredTypeReference(target, node, /*mapper*/ undefined);
54716                 }
54717                 else {
54718                     var elementTypes = node.kind === 178 /* ArrayType */ ? [getTypeFromTypeNode(node.elementType)] : ts.map(node.elements, getTypeFromTypeNode);
54719                     links.resolvedType = createNormalizedTypeReference(target, elementTypes);
54720                 }
54721             }
54722             return links.resolvedType;
54723         }
54724         function isReadonlyTypeOperator(node) {
54725             return ts.isTypeOperatorNode(node) && node.operator === 142 /* ReadonlyKeyword */;
54726         }
54727         function createTupleType(elementTypes, elementFlags, readonly, namedMemberDeclarations) {
54728             if (readonly === void 0) { readonly = false; }
54729             var tupleTarget = getTupleTargetType(elementFlags || ts.map(elementTypes, function (_) { return 1 /* Required */; }), readonly, namedMemberDeclarations);
54730             return tupleTarget === emptyGenericType ? emptyObjectType :
54731                 elementTypes.length ? createNormalizedTypeReference(tupleTarget, elementTypes) :
54732                     tupleTarget;
54733         }
54734         function getTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
54735             if (elementFlags.length === 1 && elementFlags[0] & 4 /* Rest */) {
54736                 // [...X[]] is equivalent to just X[]
54737                 return readonly ? globalReadonlyArrayType : globalArrayType;
54738             }
54739             var key = ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? "#" : f & 2 /* Optional */ ? "?" : f & 4 /* Rest */ ? "." : "*"; }).join() +
54740                 (readonly ? "R" : "") +
54741                 (namedMemberDeclarations && namedMemberDeclarations.length ? "," + ts.map(namedMemberDeclarations, getNodeId).join(",") : "");
54742             var type = tupleTypes.get(key);
54743             if (!type) {
54744                 tupleTypes.set(key, type = createTupleTargetType(elementFlags, readonly, namedMemberDeclarations));
54745             }
54746             return type;
54747         }
54748         // We represent tuple types as type references to synthesized generic interface types created by
54749         // this function. The types are of the form:
54750         //
54751         //   interface Tuple<T0, T1, T2, ...> extends Array<T0 | T1 | T2 | ...> { 0: T0, 1: T1, 2: T2, ... }
54752         //
54753         // Note that the generic type created by this function has no symbol associated with it. The same
54754         // is true for each of the synthesized type parameters.
54755         function createTupleTargetType(elementFlags, readonly, namedMemberDeclarations) {
54756             var arity = elementFlags.length;
54757             var minLength = ts.findLastIndex(elementFlags, function (f) { return !!(f & (1 /* Required */ | 8 /* Variadic */)); }) + 1;
54758             var typeParameters;
54759             var properties = [];
54760             var combinedFlags = 0;
54761             if (arity) {
54762                 typeParameters = new Array(arity);
54763                 for (var i = 0; i < arity; i++) {
54764                     var typeParameter = typeParameters[i] = createTypeParameter();
54765                     var flags = elementFlags[i];
54766                     combinedFlags |= flags;
54767                     if (!(combinedFlags & 12 /* Variable */)) {
54768                         var property = createSymbol(4 /* Property */ | (flags & 2 /* Optional */ ? 16777216 /* Optional */ : 0), "" + i, readonly ? 8 /* Readonly */ : 0);
54769                         property.tupleLabelDeclaration = namedMemberDeclarations === null || namedMemberDeclarations === void 0 ? void 0 : namedMemberDeclarations[i];
54770                         property.type = typeParameter;
54771                         properties.push(property);
54772                     }
54773                 }
54774             }
54775             var fixedLength = properties.length;
54776             var lengthSymbol = createSymbol(4 /* Property */, "length");
54777             if (combinedFlags & 12 /* Variable */) {
54778                 lengthSymbol.type = numberType;
54779             }
54780             else {
54781                 var literalTypes_1 = [];
54782                 for (var i = minLength; i <= arity; i++)
54783                     literalTypes_1.push(getLiteralType(i));
54784                 lengthSymbol.type = getUnionType(literalTypes_1);
54785             }
54786             properties.push(lengthSymbol);
54787             var type = createObjectType(8 /* Tuple */ | 4 /* Reference */);
54788             type.typeParameters = typeParameters;
54789             type.outerTypeParameters = undefined;
54790             type.localTypeParameters = typeParameters;
54791             type.instantiations = new ts.Map();
54792             type.instantiations.set(getTypeListId(type.typeParameters), type);
54793             type.target = type;
54794             type.resolvedTypeArguments = type.typeParameters;
54795             type.thisType = createTypeParameter();
54796             type.thisType.isThisType = true;
54797             type.thisType.constraint = type;
54798             type.declaredProperties = properties;
54799             type.declaredCallSignatures = ts.emptyArray;
54800             type.declaredConstructSignatures = ts.emptyArray;
54801             type.declaredStringIndexInfo = undefined;
54802             type.declaredNumberIndexInfo = undefined;
54803             type.elementFlags = elementFlags;
54804             type.minLength = minLength;
54805             type.fixedLength = fixedLength;
54806             type.hasRestElement = !!(combinedFlags & 12 /* Variable */);
54807             type.combinedFlags = combinedFlags;
54808             type.readonly = readonly;
54809             type.labeledElementDeclarations = namedMemberDeclarations;
54810             return type;
54811         }
54812         function createNormalizedTypeReference(target, typeArguments) {
54813             return target.objectFlags & 8 /* Tuple */ && target.combinedFlags & 8 /* Variadic */ ?
54814                 createNormalizedTupleType(target, typeArguments) :
54815                 createTypeReference(target, typeArguments);
54816         }
54817         function createNormalizedTupleType(target, elementTypes) {
54818             var _a, _b, _c;
54819             // Transform [A, ...(X | Y | Z)] into [A, ...X] | [A, ...Y] | [A, ...Z]
54820             var unionIndex = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */ && t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
54821             if (unionIndex >= 0) {
54822                 return checkCrossProductUnion(ts.map(elementTypes, function (t, i) { return target.elementFlags[i] & 8 /* Variadic */ ? t : unknownType; })) ?
54823                     mapType(elementTypes[unionIndex], function (t) { return createNormalizedTupleType(target, ts.replaceElement(elementTypes, unionIndex, t)); }) :
54824                     errorType;
54825             }
54826             // If there are no variadic elements with non-generic types, just create a type reference with the same target type.
54827             var spreadIndex = ts.findIndex(elementTypes, function (t, i) { return !!(target.elementFlags[i] & 8 /* Variadic */) && !(t.flags & 58982400 /* InstantiableNonPrimitive */) && !isGenericMappedType(t); });
54828             if (spreadIndex < 0) {
54829                 return createTypeReference(target, elementTypes);
54830             }
54831             // We have non-generic variadic elements that need normalization.
54832             var expandedTypes = [];
54833             var expandedFlags = [];
54834             var expandedDeclarations = [];
54835             var optionalIndex = -1;
54836             var restTypes;
54837             var _loop_13 = function (i) {
54838                 var type = elementTypes[i];
54839                 var flags = target.elementFlags[i];
54840                 if (flags & 8 /* Variadic */) {
54841                     if (type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericMappedType(type)) {
54842                         // Generic variadic elements stay as they are (except following a rest element).
54843                         addElementOrRest(type, 8 /* Variadic */, (_a = target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]);
54844                     }
54845                     else if (isTupleType(type)) {
54846                         // Spread variadic elements with tuple types into the resulting tuple.
54847                         ts.forEach(getTypeArguments(type), function (t, n) { var _a; return addElementOrRest(t, type.target.elementFlags[n], (_a = type.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[n]); });
54848                     }
54849                     else {
54850                         // Treat everything else as an array type and create a rest element.
54851                         addElementOrRest(isArrayLikeType(type) && getIndexTypeOfType(type, 1 /* Number */) || errorType, 4 /* Rest */, (_b = target.labeledElementDeclarations) === null || _b === void 0 ? void 0 : _b[i]);
54852                     }
54853                 }
54854                 else {
54855                     // Copy other element kinds with no change.
54856                     addElementOrRest(type, flags, (_c = target.labeledElementDeclarations) === null || _c === void 0 ? void 0 : _c[i]);
54857                 }
54858             };
54859             for (var i = 0; i < elementTypes.length; i++) {
54860                 _loop_13(i);
54861             }
54862             if (restTypes) {
54863                 // Create a union of the collected rest element types.
54864                 expandedTypes[expandedTypes.length - 1] = getUnionType(restTypes);
54865             }
54866             var tupleTarget = getTupleTargetType(expandedFlags, target.readonly, expandedDeclarations);
54867             return tupleTarget === emptyGenericType ? emptyObjectType :
54868                 expandedFlags.length ? createTypeReference(tupleTarget, expandedTypes) :
54869                     tupleTarget;
54870             function addElementOrRest(type, flags, declaration) {
54871                 if (restTypes) {
54872                     // A rest element was previously added, so simply collect the type of this element.
54873                     restTypes.push(flags & 8 /* Variadic */ ? getIndexedAccessType(type, numberType) : type);
54874                 }
54875                 else {
54876                     if (flags & 1 /* Required */ && optionalIndex >= 0) {
54877                         // Turn preceding optional elements into required elements
54878                         for (var i = optionalIndex; i < expandedFlags.length; i++) {
54879                             if (expandedFlags[i] & 2 /* Optional */)
54880                                 expandedFlags[i] = 1 /* Required */;
54881                         }
54882                         optionalIndex = -1;
54883                     }
54884                     else if (flags & 2 /* Optional */ && optionalIndex < 0) {
54885                         optionalIndex = expandedFlags.length;
54886                     }
54887                     else if (flags & 4 /* Rest */) {
54888                         // Start collecting element types when a rest element is added.
54889                         restTypes = [type];
54890                     }
54891                     expandedTypes.push(type);
54892                     expandedFlags.push(flags);
54893                     if (expandedDeclarations && declaration) {
54894                         expandedDeclarations.push(declaration);
54895                     }
54896                     else {
54897                         expandedDeclarations = undefined;
54898                     }
54899                 }
54900             }
54901         }
54902         function sliceTupleType(type, index, endSkipCount) {
54903             if (endSkipCount === void 0) { endSkipCount = 0; }
54904             var target = type.target;
54905             var endIndex = getTypeReferenceArity(type) - endSkipCount;
54906             return index > target.fixedLength ? getRestArrayTypeOfTupleType(type) || createTupleType(ts.emptyArray) :
54907                 createTupleType(getTypeArguments(type).slice(index, endIndex), target.elementFlags.slice(index, endIndex), 
54908                 /*readonly*/ false, target.labeledElementDeclarations && target.labeledElementDeclarations.slice(index, endIndex));
54909         }
54910         function getKnownKeysOfTupleType(type) {
54911             return getUnionType(ts.append(ts.arrayOf(type.target.fixedLength, function (i) { return getLiteralType("" + i); }), getIndexType(type.target.readonly ? globalReadonlyArrayType : globalArrayType)));
54912         }
54913         function getTypeFromOptionalTypeNode(node) {
54914             var type = getTypeFromTypeNode(node.type);
54915             return strictNullChecks ? getOptionalType(type) : type;
54916         }
54917         function getTypeId(type) {
54918             return type.id;
54919         }
54920         function containsType(types, type) {
54921             return ts.binarySearch(types, type, getTypeId, ts.compareValues) >= 0;
54922         }
54923         function insertType(types, type) {
54924             var index = ts.binarySearch(types, type, getTypeId, ts.compareValues);
54925             if (index < 0) {
54926                 types.splice(~index, 0, type);
54927                 return true;
54928             }
54929             return false;
54930         }
54931         function addTypeToUnion(typeSet, includes, type) {
54932             var flags = type.flags;
54933             if (flags & 1048576 /* Union */) {
54934                 return addTypesToUnion(typeSet, includes, type.types);
54935             }
54936             // We ignore 'never' types in unions
54937             if (!(flags & 131072 /* Never */)) {
54938                 includes |= flags & 205258751 /* IncludesMask */;
54939                 if (flags & 469499904 /* StructuredOrInstantiable */)
54940                     includes |= 262144 /* IncludesStructuredOrInstantiable */;
54941                 if (type === wildcardType)
54942                     includes |= 8388608 /* IncludesWildcard */;
54943                 if (!strictNullChecks && flags & 98304 /* Nullable */) {
54944                     if (!(ts.getObjectFlags(type) & 524288 /* ContainsWideningType */))
54945                         includes |= 4194304 /* IncludesNonWideningType */;
54946                 }
54947                 else {
54948                     var len = typeSet.length;
54949                     var index = len && type.id > typeSet[len - 1].id ? ~len : ts.binarySearch(typeSet, type, getTypeId, ts.compareValues);
54950                     if (index < 0) {
54951                         typeSet.splice(~index, 0, type);
54952                     }
54953                 }
54954             }
54955             return includes;
54956         }
54957         // Add the given types to the given type set. Order is preserved, duplicates are removed,
54958         // and nested types of the given kind are flattened into the set.
54959         function addTypesToUnion(typeSet, includes, types) {
54960             for (var _i = 0, types_10 = types; _i < types_10.length; _i++) {
54961                 var type = types_10[_i];
54962                 includes = addTypeToUnion(typeSet, includes, type);
54963             }
54964             return includes;
54965         }
54966         function isSetOfLiteralsFromSameEnum(types) {
54967             var first = types[0];
54968             if (first.flags & 1024 /* EnumLiteral */) {
54969                 var firstEnum = getParentOfSymbol(first.symbol);
54970                 for (var i = 1; i < types.length; i++) {
54971                     var other = types[i];
54972                     if (!(other.flags & 1024 /* EnumLiteral */) || (firstEnum !== getParentOfSymbol(other.symbol))) {
54973                         return false;
54974                     }
54975                 }
54976                 return true;
54977             }
54978             return false;
54979         }
54980         function removeSubtypes(types, primitivesOnly) {
54981             var len = types.length;
54982             if (len === 0 || isSetOfLiteralsFromSameEnum(types)) {
54983                 return true;
54984             }
54985             var i = len;
54986             var count = 0;
54987             while (i > 0) {
54988                 i--;
54989                 var source = types[i];
54990                 for (var _i = 0, types_11 = types; _i < types_11.length; _i++) {
54991                     var target = types_11[_i];
54992                     if (source !== target) {
54993                         if (count === 100000) {
54994                             // After 100000 subtype checks we estimate the remaining amount of work by assuming the
54995                             // same ratio of checks per element. If the estimated number of remaining type checks is
54996                             // greater than an upper limit we deem the union type too complex to represent. The
54997                             // upper limit is 25M for unions of primitives only, and 1M otherwise. This for example
54998                             // caps union types at 5000 unique literal types and 1000 unique object types.
54999                             var estimatedCount = (count / (len - i)) * len;
55000                             if (estimatedCount > (primitivesOnly ? 25000000 : 1000000)) {
55001                                 ts.tracing.instant("check" /* Check */, "removeSubtypes_DepthLimit", { typeIds: types.map(function (t) { return t.id; }) });
55002                                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
55003                                 return false;
55004                             }
55005                         }
55006                         count++;
55007                         if (isTypeRelatedTo(source, target, strictSubtypeRelation) && (!(ts.getObjectFlags(getTargetType(source)) & 1 /* Class */) ||
55008                             !(ts.getObjectFlags(getTargetType(target)) & 1 /* Class */) ||
55009                             isTypeDerivedFrom(source, target))) {
55010                             ts.orderedRemoveItemAt(types, i);
55011                             break;
55012                         }
55013                     }
55014                 }
55015             }
55016             return true;
55017         }
55018         function removeRedundantLiteralTypes(types, includes) {
55019             var i = types.length;
55020             while (i > 0) {
55021                 i--;
55022                 var t = types[i];
55023                 var remove = t.flags & 128 /* StringLiteral */ && includes & 4 /* String */ ||
55024                     t.flags & 256 /* NumberLiteral */ && includes & 8 /* Number */ ||
55025                     t.flags & 2048 /* BigIntLiteral */ && includes & 64 /* BigInt */ ||
55026                     t.flags & 8192 /* UniqueESSymbol */ && includes & 4096 /* ESSymbol */ ||
55027                     isFreshLiteralType(t) && containsType(types, t.regularType);
55028                 if (remove) {
55029                     ts.orderedRemoveItemAt(types, i);
55030                 }
55031             }
55032         }
55033         function removeStringLiteralsMatchedByTemplateLiterals(types) {
55034             var templates = ts.filter(types, isPatternLiteralType);
55035             if (templates.length) {
55036                 var i = types.length;
55037                 var _loop_14 = function () {
55038                     i--;
55039                     var t = types[i];
55040                     if (t.flags & 128 /* StringLiteral */ && ts.some(templates, function (template) { return isTypeSubtypeOf(t, template); })) {
55041                         ts.orderedRemoveItemAt(types, i);
55042                     }
55043                 };
55044                 while (i > 0) {
55045                     _loop_14();
55046                 }
55047             }
55048         }
55049         // We sort and deduplicate the constituent types based on object identity. If the subtypeReduction
55050         // flag is specified we also reduce the constituent type set to only include types that aren't subtypes
55051         // of other types. Subtype reduction is expensive for large union types and is possible only when union
55052         // types are known not to circularly reference themselves (as is the case with union types created by
55053         // expression constructs such as array literals and the || and ?: operators). Named types can
55054         // circularly reference themselves and therefore cannot be subtype reduced during their declaration.
55055         // For example, "type Item = string | (() => Item" is a named type that circularly references itself.
55056         function getUnionType(types, unionReduction, aliasSymbol, aliasTypeArguments) {
55057             if (unionReduction === void 0) { unionReduction = 1 /* Literal */; }
55058             if (types.length === 0) {
55059                 return neverType;
55060             }
55061             if (types.length === 1) {
55062                 return types[0];
55063             }
55064             var typeSet = [];
55065             var includes = addTypesToUnion(typeSet, 0, types);
55066             if (unionReduction !== 0 /* None */) {
55067                 if (includes & 3 /* AnyOrUnknown */) {
55068                     return includes & 1 /* Any */ ? includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType : unknownType;
55069                 }
55070                 switch (unionReduction) {
55071                     case 1 /* Literal */:
55072                         if (includes & (2944 /* Literal */ | 8192 /* UniqueESSymbol */)) {
55073                             removeRedundantLiteralTypes(typeSet, includes);
55074                         }
55075                         if (includes & 128 /* StringLiteral */ && includes & 134217728 /* TemplateLiteral */) {
55076                             removeStringLiteralsMatchedByTemplateLiterals(typeSet);
55077                         }
55078                         break;
55079                     case 2 /* Subtype */:
55080                         if (!removeSubtypes(typeSet, !(includes & 262144 /* IncludesStructuredOrInstantiable */))) {
55081                             return errorType;
55082                         }
55083                         break;
55084                 }
55085                 if (typeSet.length === 0) {
55086                     return includes & 65536 /* Null */ ? includes & 4194304 /* IncludesNonWideningType */ ? nullType : nullWideningType :
55087                         includes & 32768 /* Undefined */ ? includes & 4194304 /* IncludesNonWideningType */ ? undefinedType : undefinedWideningType :
55088                             neverType;
55089                 }
55090             }
55091             var objectFlags = (includes & 469647395 /* NotPrimitiveUnion */ ? 0 : 262144 /* PrimitiveUnion */) |
55092                 (includes & 2097152 /* Intersection */ ? 268435456 /* ContainsIntersections */ : 0);
55093             return getUnionTypeFromSortedList(typeSet, objectFlags, aliasSymbol, aliasTypeArguments);
55094         }
55095         function getUnionTypePredicate(signatures) {
55096             var first;
55097             var types = [];
55098             for (var _i = 0, signatures_6 = signatures; _i < signatures_6.length; _i++) {
55099                 var sig = signatures_6[_i];
55100                 var pred = getTypePredicateOfSignature(sig);
55101                 if (!pred || pred.kind === 2 /* AssertsThis */ || pred.kind === 3 /* AssertsIdentifier */) {
55102                     continue;
55103                 }
55104                 if (first) {
55105                     if (!typePredicateKindsMatch(first, pred)) {
55106                         // No common type predicate.
55107                         return undefined;
55108                     }
55109                 }
55110                 else {
55111                     first = pred;
55112                 }
55113                 types.push(pred.type);
55114             }
55115             if (!first) {
55116                 // No union signatures had a type predicate.
55117                 return undefined;
55118             }
55119             var unionType = getUnionType(types);
55120             return createTypePredicate(first.kind, first.parameterName, first.parameterIndex, unionType);
55121         }
55122         function typePredicateKindsMatch(a, b) {
55123             return a.kind === b.kind && a.parameterIndex === b.parameterIndex;
55124         }
55125         // This function assumes the constituent type list is sorted and deduplicated.
55126         function getUnionTypeFromSortedList(types, objectFlags, aliasSymbol, aliasTypeArguments) {
55127             if (types.length === 0) {
55128                 return neverType;
55129             }
55130             if (types.length === 1) {
55131                 return types[0];
55132             }
55133             var id = getTypeListId(types);
55134             var type = unionTypes.get(id);
55135             if (!type) {
55136                 type = createType(1048576 /* Union */);
55137                 unionTypes.set(id, type);
55138                 type.objectFlags = objectFlags | getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
55139                 type.types = types;
55140                 /*
55141                 Note: This is the alias symbol (or lack thereof) that we see when we first encounter this union type.
55142                 For aliases of identical unions, eg `type T = A | B; type U = A | B`, the symbol of the first alias encountered is the aliasSymbol.
55143                 (In the language service, the order may depend on the order in which a user takes actions, such as hovering over symbols.)
55144                 It's important that we create equivalent union types only once, so that's an unfortunate side effect.
55145                 */
55146                 type.aliasSymbol = aliasSymbol;
55147                 type.aliasTypeArguments = aliasTypeArguments;
55148             }
55149             return type;
55150         }
55151         function getTypeFromUnionTypeNode(node) {
55152             var links = getNodeLinks(node);
55153             if (!links.resolvedType) {
55154                 var aliasSymbol = getAliasSymbolForTypeNode(node);
55155                 links.resolvedType = getUnionType(ts.map(node.types, getTypeFromTypeNode), 1 /* Literal */, aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
55156             }
55157             return links.resolvedType;
55158         }
55159         function addTypeToIntersection(typeSet, includes, type) {
55160             var flags = type.flags;
55161             if (flags & 2097152 /* Intersection */) {
55162                 return addTypesToIntersection(typeSet, includes, type.types);
55163             }
55164             if (isEmptyAnonymousObjectType(type)) {
55165                 if (!(includes & 16777216 /* IncludesEmptyObject */)) {
55166                     includes |= 16777216 /* IncludesEmptyObject */;
55167                     typeSet.set(type.id.toString(), type);
55168                 }
55169             }
55170             else {
55171                 if (flags & 3 /* AnyOrUnknown */) {
55172                     if (type === wildcardType)
55173                         includes |= 8388608 /* IncludesWildcard */;
55174                 }
55175                 else if ((strictNullChecks || !(flags & 98304 /* Nullable */)) && !typeSet.has(type.id.toString())) {
55176                     if (type.flags & 109440 /* Unit */ && includes & 109440 /* Unit */) {
55177                         // We have seen two distinct unit types which means we should reduce to an
55178                         // empty intersection. Adding TypeFlags.NonPrimitive causes that to happen.
55179                         includes |= 67108864 /* NonPrimitive */;
55180                     }
55181                     typeSet.set(type.id.toString(), type);
55182                 }
55183                 includes |= flags & 205258751 /* IncludesMask */;
55184             }
55185             return includes;
55186         }
55187         // Add the given types to the given type set. Order is preserved, freshness is removed from literal
55188         // types, duplicates are removed, and nested types of the given kind are flattened into the set.
55189         function addTypesToIntersection(typeSet, includes, types) {
55190             for (var _i = 0, types_12 = types; _i < types_12.length; _i++) {
55191                 var type = types_12[_i];
55192                 includes = addTypeToIntersection(typeSet, includes, getRegularTypeOfLiteralType(type));
55193             }
55194             return includes;
55195         }
55196         function removeRedundantPrimitiveTypes(types, includes) {
55197             var i = types.length;
55198             while (i > 0) {
55199                 i--;
55200                 var t = types[i];
55201                 var remove = t.flags & 4 /* String */ && includes & 128 /* StringLiteral */ ||
55202                     t.flags & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
55203                     t.flags & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
55204                     t.flags & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */;
55205                 if (remove) {
55206                     ts.orderedRemoveItemAt(types, i);
55207                 }
55208             }
55209         }
55210         // Check that the given type has a match in every union. A given type is matched by
55211         // an identical type, and a literal type is additionally matched by its corresponding
55212         // primitive type.
55213         function eachUnionContains(unionTypes, type) {
55214             for (var _i = 0, unionTypes_1 = unionTypes; _i < unionTypes_1.length; _i++) {
55215                 var u = unionTypes_1[_i];
55216                 if (!containsType(u.types, type)) {
55217                     var primitive = type.flags & 128 /* StringLiteral */ ? stringType :
55218                         type.flags & 256 /* NumberLiteral */ ? numberType :
55219                             type.flags & 2048 /* BigIntLiteral */ ? bigintType :
55220                                 type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
55221                                     undefined;
55222                     if (!primitive || !containsType(u.types, primitive)) {
55223                         return false;
55224                     }
55225                 }
55226             }
55227             return true;
55228         }
55229         /**
55230          * Returns `true` if the intersection of the template literals and string literals is the empty set, eg `get${string}` & "setX", and should reduce to `never`
55231          */
55232         function extractRedundantTemplateLiterals(types) {
55233             var i = types.length;
55234             var literals = ts.filter(types, function (t) { return !!(t.flags & 128 /* StringLiteral */); });
55235             while (i > 0) {
55236                 i--;
55237                 var t = types[i];
55238                 if (!(t.flags & 134217728 /* TemplateLiteral */))
55239                     continue;
55240                 for (var _i = 0, literals_1 = literals; _i < literals_1.length; _i++) {
55241                     var t2 = literals_1[_i];
55242                     if (isTypeSubtypeOf(t2, t)) {
55243                         // eg, ``get${T}` & "getX"` is just `"getX"`
55244                         ts.orderedRemoveItemAt(types, i);
55245                         break;
55246                     }
55247                     else if (isPatternLiteralType(t)) {
55248                         return true;
55249                     }
55250                 }
55251             }
55252             return false;
55253         }
55254         function extractIrreducible(types, flag) {
55255             if (ts.every(types, function (t) { return !!(t.flags & 1048576 /* Union */) && ts.some(t.types, function (tt) { return !!(tt.flags & flag); }); })) {
55256                 for (var i = 0; i < types.length; i++) {
55257                     types[i] = filterType(types[i], function (t) { return !(t.flags & flag); });
55258                 }
55259                 return true;
55260             }
55261             return false;
55262         }
55263         // If the given list of types contains more than one union of primitive types, replace the
55264         // first with a union containing an intersection of those primitive types, then remove the
55265         // other unions and return true. Otherwise, do nothing and return false.
55266         function intersectUnionsOfPrimitiveTypes(types) {
55267             var unionTypes;
55268             var index = ts.findIndex(types, function (t) { return !!(ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */); });
55269             if (index < 0) {
55270                 return false;
55271             }
55272             var i = index + 1;
55273             // Remove all but the first union of primitive types and collect them in
55274             // the unionTypes array.
55275             while (i < types.length) {
55276                 var t = types[i];
55277                 if (ts.getObjectFlags(t) & 262144 /* PrimitiveUnion */) {
55278                     (unionTypes || (unionTypes = [types[index]])).push(t);
55279                     ts.orderedRemoveItemAt(types, i);
55280                 }
55281                 else {
55282                     i++;
55283                 }
55284             }
55285             // Return false if there was only one union of primitive types
55286             if (!unionTypes) {
55287                 return false;
55288             }
55289             // We have more than one union of primitive types, now intersect them. For each
55290             // type in each union we check if the type is matched in every union and if so
55291             // we include it in the result.
55292             var checked = [];
55293             var result = [];
55294             for (var _i = 0, unionTypes_2 = unionTypes; _i < unionTypes_2.length; _i++) {
55295                 var u = unionTypes_2[_i];
55296                 for (var _a = 0, _b = u.types; _a < _b.length; _a++) {
55297                     var t = _b[_a];
55298                     if (insertType(checked, t)) {
55299                         if (eachUnionContains(unionTypes, t)) {
55300                             insertType(result, t);
55301                         }
55302                     }
55303                 }
55304             }
55305             // Finally replace the first union with the result
55306             types[index] = getUnionTypeFromSortedList(result, 262144 /* PrimitiveUnion */);
55307             return true;
55308         }
55309         function createIntersectionType(types, aliasSymbol, aliasTypeArguments) {
55310             var result = createType(2097152 /* Intersection */);
55311             result.objectFlags = getPropagatingFlagsOfTypes(types, /*excludeKinds*/ 98304 /* Nullable */);
55312             result.types = types;
55313             result.aliasSymbol = aliasSymbol; // See comment in `getUnionTypeFromSortedList`.
55314             result.aliasTypeArguments = aliasTypeArguments;
55315             return result;
55316         }
55317         // We normalize combinations of intersection and union types based on the distributive property of the '&'
55318         // operator. Specifically, because X & (A | B) is equivalent to X & A | X & B, we can transform intersection
55319         // types with union type constituents into equivalent union types with intersection type constituents and
55320         // effectively ensure that union types are always at the top level in type representations.
55321         //
55322         // We do not perform structural deduplication on intersection types. Intersection types are created only by the &
55323         // type operator and we can't reduce those because we want to support recursive intersection types. For example,
55324         // a type alias of the form "type List<T> = T & { next: List<T> }" cannot be reduced during its declaration.
55325         // Also, unlike union types, the order of the constituent types is preserved in order that overload resolution
55326         // for intersections of types with signatures can be deterministic.
55327         function getIntersectionType(types, aliasSymbol, aliasTypeArguments) {
55328             var typeMembershipMap = new ts.Map();
55329             var includes = addTypesToIntersection(typeMembershipMap, 0, types);
55330             var typeSet = ts.arrayFrom(typeMembershipMap.values());
55331             // An intersection type is considered empty if it contains
55332             // the type never, or
55333             // more than one unit type or,
55334             // an object type and a nullable type (null or undefined), or
55335             // a string-like type and a type known to be non-string-like, or
55336             // a number-like type and a type known to be non-number-like, or
55337             // a symbol-like type and a type known to be non-symbol-like, or
55338             // a void-like type and a type known to be non-void-like, or
55339             // a non-primitive type and a type known to be primitive.
55340             if (includes & 131072 /* Never */ ||
55341                 strictNullChecks && includes & 98304 /* Nullable */ && includes & (524288 /* Object */ | 67108864 /* NonPrimitive */ | 16777216 /* IncludesEmptyObject */) ||
55342                 includes & 67108864 /* NonPrimitive */ && includes & (469892092 /* DisjointDomains */ & ~67108864 /* NonPrimitive */) ||
55343                 includes & 402653316 /* StringLike */ && includes & (469892092 /* DisjointDomains */ & ~402653316 /* StringLike */) ||
55344                 includes & 296 /* NumberLike */ && includes & (469892092 /* DisjointDomains */ & ~296 /* NumberLike */) ||
55345                 includes & 2112 /* BigIntLike */ && includes & (469892092 /* DisjointDomains */ & ~2112 /* BigIntLike */) ||
55346                 includes & 12288 /* ESSymbolLike */ && includes & (469892092 /* DisjointDomains */ & ~12288 /* ESSymbolLike */) ||
55347                 includes & 49152 /* VoidLike */ && includes & (469892092 /* DisjointDomains */ & ~49152 /* VoidLike */)) {
55348                 return neverType;
55349             }
55350             if (includes & 134217728 /* TemplateLiteral */ && includes & 128 /* StringLiteral */ && extractRedundantTemplateLiterals(typeSet)) {
55351                 return neverType;
55352             }
55353             if (includes & 1 /* Any */) {
55354                 return includes & 8388608 /* IncludesWildcard */ ? wildcardType : anyType;
55355             }
55356             if (!strictNullChecks && includes & 98304 /* Nullable */) {
55357                 return includes & 32768 /* Undefined */ ? undefinedType : nullType;
55358             }
55359             if (includes & 4 /* String */ && includes & 128 /* StringLiteral */ ||
55360                 includes & 8 /* Number */ && includes & 256 /* NumberLiteral */ ||
55361                 includes & 64 /* BigInt */ && includes & 2048 /* BigIntLiteral */ ||
55362                 includes & 4096 /* ESSymbol */ && includes & 8192 /* UniqueESSymbol */) {
55363                 removeRedundantPrimitiveTypes(typeSet, includes);
55364             }
55365             if (includes & 16777216 /* IncludesEmptyObject */ && includes & 524288 /* Object */) {
55366                 ts.orderedRemoveItemAt(typeSet, ts.findIndex(typeSet, isEmptyAnonymousObjectType));
55367             }
55368             if (typeSet.length === 0) {
55369                 return unknownType;
55370             }
55371             if (typeSet.length === 1) {
55372                 return typeSet[0];
55373             }
55374             var id = getTypeListId(typeSet);
55375             var result = intersectionTypes.get(id);
55376             if (!result) {
55377                 if (includes & 1048576 /* Union */) {
55378                     if (intersectUnionsOfPrimitiveTypes(typeSet)) {
55379                         // When the intersection creates a reduced set (which might mean that *all* union types have
55380                         // disappeared), we restart the operation to get a new set of combined flags. Once we have
55381                         // reduced we'll never reduce again, so this occurs at most once.
55382                         result = getIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
55383                     }
55384                     else if (extractIrreducible(typeSet, 32768 /* Undefined */)) {
55385                         result = getUnionType([getIntersectionType(typeSet), undefinedType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
55386                     }
55387                     else if (extractIrreducible(typeSet, 65536 /* Null */)) {
55388                         result = getUnionType([getIntersectionType(typeSet), nullType], 1 /* Literal */, aliasSymbol, aliasTypeArguments);
55389                     }
55390                     else {
55391                         // We are attempting to construct a type of the form X & (A | B) & Y. Transform this into a type of
55392                         // the form X & A & Y | X & B & Y and recursively reduce until no union type constituents remain.
55393                         // If the estimated size of the resulting union type exceeds 100000 constituents, report an error.
55394                         if (!checkCrossProductUnion(typeSet)) {
55395                             return errorType;
55396                         }
55397                         var unionIndex_1 = ts.findIndex(typeSet, function (t) { return (t.flags & 1048576 /* Union */) !== 0; });
55398                         var unionType = typeSet[unionIndex_1];
55399                         result = getUnionType(ts.map(unionType.types, function (t) { return getIntersectionType(ts.replaceElement(typeSet, unionIndex_1, t)); }), 1 /* Literal */, aliasSymbol, aliasTypeArguments);
55400                     }
55401                 }
55402                 else {
55403                     result = createIntersectionType(typeSet, aliasSymbol, aliasTypeArguments);
55404                 }
55405                 intersectionTypes.set(id, result);
55406             }
55407             return result;
55408         }
55409         function checkCrossProductUnion(types) {
55410             var size = ts.reduceLeft(types, function (n, t) { return n * (t.flags & 1048576 /* Union */ ? t.types.length : t.flags & 131072 /* Never */ ? 0 : 1); }, 1);
55411             if (size >= 100000) {
55412                 ts.tracing.instant("check" /* Check */, "checkCrossProductUnion_DepthLimit", { typeIds: types.map(function (t) { return t.id; }), size: size });
55413                 error(currentNode, ts.Diagnostics.Expression_produces_a_union_type_that_is_too_complex_to_represent);
55414                 return false;
55415             }
55416             return true;
55417         }
55418         function getTypeFromIntersectionTypeNode(node) {
55419             var links = getNodeLinks(node);
55420             if (!links.resolvedType) {
55421                 var aliasSymbol = getAliasSymbolForTypeNode(node);
55422                 links.resolvedType = getIntersectionType(ts.map(node.types, getTypeFromTypeNode), aliasSymbol, getTypeArgumentsForAliasSymbol(aliasSymbol));
55423             }
55424             return links.resolvedType;
55425         }
55426         function createIndexType(type, stringsOnly) {
55427             var result = createType(4194304 /* Index */);
55428             result.type = type;
55429             result.stringsOnly = stringsOnly;
55430             return result;
55431         }
55432         function getIndexTypeForGenericType(type, stringsOnly) {
55433             return stringsOnly ?
55434                 type.resolvedStringIndexType || (type.resolvedStringIndexType = createIndexType(type, /*stringsOnly*/ true)) :
55435                 type.resolvedIndexType || (type.resolvedIndexType = createIndexType(type, /*stringsOnly*/ false));
55436         }
55437         function getIndexTypeForMappedType(type, noIndexSignatures) {
55438             var constraint = filterType(getConstraintTypeFromMappedType(type), function (t) { return !(noIndexSignatures && t.flags & (1 /* Any */ | 4 /* String */)); });
55439             var nameType = type.declaration.nameType && getTypeFromTypeNode(type.declaration.nameType);
55440             return nameType ?
55441                 mapType(constraint, function (t) { return instantiateType(nameType, appendTypeMapping(type.mapper, getTypeParameterFromMappedType(type), t)); }) :
55442                 constraint;
55443         }
55444         // Ordinarily we reduce a keyof M where M is a mapped type { [P in K as N<P>]: X } to simply N<K>. This however presumes
55445         // that N distributes over union types, i.e. that N<A | B | C> is equivalent to N<A> | N<B> | N<C>. That presumption is
55446         // generally true, except when N is a non-distributive conditional type or an instantiable type with non-distributive
55447         // conditional type as a constituent. In those cases, we cannot reduce keyof M and need to preserve it as is.
55448         function isNonDistributiveNameType(type) {
55449             return !!(type && (type.flags & 16777216 /* Conditional */ && !type.root.isDistributive ||
55450                 type.flags & (3145728 /* UnionOrIntersection */ | 134217728 /* TemplateLiteral */) && ts.some(type.types, isNonDistributiveNameType) ||
55451                 type.flags & (4194304 /* Index */ | 268435456 /* StringMapping */) && isNonDistributiveNameType(type.type) ||
55452                 type.flags & 8388608 /* IndexedAccess */ && isNonDistributiveNameType(type.indexType) ||
55453                 type.flags & 33554432 /* Substitution */ && isNonDistributiveNameType(type.substitute)));
55454         }
55455         function getLiteralTypeFromPropertyName(name) {
55456             if (ts.isPrivateIdentifier(name)) {
55457                 return neverType;
55458             }
55459             return ts.isIdentifier(name) ? getLiteralType(ts.unescapeLeadingUnderscores(name.escapedText)) :
55460                 getRegularTypeOfLiteralType(ts.isComputedPropertyName(name) ? checkComputedPropertyName(name) : checkExpression(name));
55461         }
55462         function getBigIntLiteralType(node) {
55463             return getLiteralType({
55464                 negative: false,
55465                 base10Value: ts.parsePseudoBigInt(node.text)
55466             });
55467         }
55468         function getLiteralTypeFromProperty(prop, include) {
55469             if (!(ts.getDeclarationModifierFlagsFromSymbol(prop) & 24 /* NonPublicAccessibilityModifier */)) {
55470                 var type = getSymbolLinks(getLateBoundSymbol(prop)).nameType;
55471                 if (!type && !ts.isKnownSymbol(prop)) {
55472                     if (prop.escapedName === "default" /* Default */) {
55473                         type = getLiteralType("default");
55474                     }
55475                     else {
55476                         var name = prop.valueDeclaration && ts.getNameOfDeclaration(prop.valueDeclaration);
55477                         type = name && getLiteralTypeFromPropertyName(name) || getLiteralType(ts.symbolName(prop));
55478                     }
55479                 }
55480                 if (type && type.flags & include) {
55481                     return type;
55482                 }
55483             }
55484             return neverType;
55485         }
55486         function getLiteralTypeFromProperties(type, include) {
55487             return getUnionType(ts.map(getPropertiesOfType(type), function (p) { return getLiteralTypeFromProperty(p, include); }));
55488         }
55489         function getNonEnumNumberIndexInfo(type) {
55490             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
55491             return numberIndexInfo !== enumNumberIndexInfo ? numberIndexInfo : undefined;
55492         }
55493         function getIndexType(type, stringsOnly, noIndexSignatures) {
55494             if (stringsOnly === void 0) { stringsOnly = keyofStringsOnly; }
55495             type = getReducedType(type);
55496             return type.flags & 1048576 /* Union */ ? getIntersectionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
55497                 type.flags & 2097152 /* Intersection */ ? getUnionType(ts.map(type.types, function (t) { return getIndexType(t, stringsOnly, noIndexSignatures); })) :
55498                     type.flags & 58982400 /* InstantiableNonPrimitive */ || isGenericTupleType(type) || isGenericMappedType(type) && isNonDistributiveNameType(getNameTypeFromMappedType(type)) ? getIndexTypeForGenericType(type, stringsOnly) :
55499                         ts.getObjectFlags(type) & 32 /* Mapped */ ? getIndexTypeForMappedType(type, noIndexSignatures) :
55500                             type === wildcardType ? wildcardType :
55501                                 type.flags & 2 /* Unknown */ ? neverType :
55502                                     type.flags & (1 /* Any */ | 131072 /* Never */) ? keyofConstraintType :
55503                                         stringsOnly ? !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? stringType : getLiteralTypeFromProperties(type, 128 /* StringLiteral */) :
55504                                             !noIndexSignatures && getIndexInfoOfType(type, 0 /* String */) ? getUnionType([stringType, numberType, getLiteralTypeFromProperties(type, 8192 /* UniqueESSymbol */)]) :
55505                                                 getNonEnumNumberIndexInfo(type) ? getUnionType([numberType, getLiteralTypeFromProperties(type, 128 /* StringLiteral */ | 8192 /* UniqueESSymbol */)]) :
55506                                                     getLiteralTypeFromProperties(type, 8576 /* StringOrNumberLiteralOrUnique */);
55507         }
55508         function getExtractStringType(type) {
55509             if (keyofStringsOnly) {
55510                 return type;
55511             }
55512             var extractTypeAlias = getGlobalExtractSymbol();
55513             return extractTypeAlias ? getTypeAliasInstantiation(extractTypeAlias, [type, stringType]) : stringType;
55514         }
55515         function getIndexTypeOrString(type) {
55516             var indexType = getExtractStringType(getIndexType(type));
55517             return indexType.flags & 131072 /* Never */ ? stringType : indexType;
55518         }
55519         function getTypeFromTypeOperatorNode(node) {
55520             var links = getNodeLinks(node);
55521             if (!links.resolvedType) {
55522                 switch (node.operator) {
55523                     case 138 /* KeyOfKeyword */:
55524                         links.resolvedType = getIndexType(getTypeFromTypeNode(node.type));
55525                         break;
55526                     case 151 /* UniqueKeyword */:
55527                         links.resolvedType = node.type.kind === 148 /* SymbolKeyword */
55528                             ? getESSymbolLikeTypeForNode(ts.walkUpParenthesizedTypes(node.parent))
55529                             : errorType;
55530                         break;
55531                     case 142 /* ReadonlyKeyword */:
55532                         links.resolvedType = getTypeFromTypeNode(node.type);
55533                         break;
55534                     default:
55535                         throw ts.Debug.assertNever(node.operator);
55536                 }
55537             }
55538             return links.resolvedType;
55539         }
55540         function getTypeFromTemplateTypeNode(node) {
55541             var links = getNodeLinks(node);
55542             if (!links.resolvedType) {
55543                 links.resolvedType = getTemplateLiteralType(__spreadArrays([node.head.text], ts.map(node.templateSpans, function (span) { return span.literal.text; })), ts.map(node.templateSpans, function (span) { return getTypeFromTypeNode(span.type); }));
55544             }
55545             return links.resolvedType;
55546         }
55547         function getTemplateLiteralType(texts, types) {
55548             var unionIndex = ts.findIndex(types, function (t) { return !!(t.flags & (131072 /* Never */ | 1048576 /* Union */)); });
55549             if (unionIndex >= 0) {
55550                 return checkCrossProductUnion(types) ?
55551                     mapType(types[unionIndex], function (t) { return getTemplateLiteralType(texts, ts.replaceElement(types, unionIndex, t)); }) :
55552                     errorType;
55553             }
55554             if (ts.contains(types, wildcardType)) {
55555                 return wildcardType;
55556             }
55557             var newTypes = [];
55558             var newTexts = [];
55559             var text = texts[0];
55560             if (!addSpans(texts, types)) {
55561                 return stringType;
55562             }
55563             if (newTypes.length === 0) {
55564                 return getLiteralType(text);
55565             }
55566             newTexts.push(text);
55567             var id = getTypeListId(newTypes) + "|" + ts.map(newTexts, function (t) { return t.length; }).join(",") + "|" + newTexts.join("");
55568             var type = templateLiteralTypes.get(id);
55569             if (!type) {
55570                 templateLiteralTypes.set(id, type = createTemplateLiteralType(newTexts, newTypes));
55571             }
55572             return type;
55573             function addSpans(texts, types) {
55574                 for (var i = 0; i < types.length; i++) {
55575                     var t = types[i];
55576                     if (t.flags & (2944 /* Literal */ | 65536 /* Null */ | 32768 /* Undefined */)) {
55577                         text += getTemplateStringForType(t) || "";
55578                         text += texts[i + 1];
55579                     }
55580                     else if (t.flags & 134217728 /* TemplateLiteral */) {
55581                         text += t.texts[0];
55582                         if (!addSpans(t.texts, t.types))
55583                             return false;
55584                         text += texts[i + 1];
55585                     }
55586                     else if (isGenericIndexType(t) || isPatternLiteralPlaceholderType(t)) {
55587                         newTypes.push(t);
55588                         newTexts.push(text);
55589                         text = texts[i + 1];
55590                     }
55591                     else {
55592                         return false;
55593                     }
55594                 }
55595                 return true;
55596             }
55597         }
55598         function getTemplateStringForType(type) {
55599             return type.flags & 128 /* StringLiteral */ ? type.value :
55600                 type.flags & 256 /* NumberLiteral */ ? "" + type.value :
55601                     type.flags & 2048 /* BigIntLiteral */ ? ts.pseudoBigIntToString(type.value) :
55602                         type.flags & 512 /* BooleanLiteral */ ? type.intrinsicName :
55603                             type.flags & 65536 /* Null */ ? "null" :
55604                                 type.flags & 32768 /* Undefined */ ? "undefined" :
55605                                     undefined;
55606         }
55607         function createTemplateLiteralType(texts, types) {
55608             var type = createType(134217728 /* TemplateLiteral */);
55609             type.texts = texts;
55610             type.types = types;
55611             return type;
55612         }
55613         function getStringMappingType(symbol, type) {
55614             return type.flags & (1048576 /* Union */ | 131072 /* Never */) ? mapType(type, function (t) { return getStringMappingType(symbol, t); }) :
55615                 isGenericIndexType(type) ? getStringMappingTypeForGenericType(symbol, type) :
55616                     type.flags & 128 /* StringLiteral */ ? getLiteralType(applyStringMapping(symbol, type.value)) :
55617                         type;
55618         }
55619         function applyStringMapping(symbol, str) {
55620             switch (intrinsicTypeKinds.get(symbol.escapedName)) {
55621                 case 0 /* Uppercase */: return str.toUpperCase();
55622                 case 1 /* Lowercase */: return str.toLowerCase();
55623                 case 2 /* Capitalize */: return str.charAt(0).toUpperCase() + str.slice(1);
55624                 case 3 /* Uncapitalize */: return str.charAt(0).toLowerCase() + str.slice(1);
55625             }
55626             return str;
55627         }
55628         function getStringMappingTypeForGenericType(symbol, type) {
55629             var id = getSymbolId(symbol) + "," + getTypeId(type);
55630             var result = stringMappingTypes.get(id);
55631             if (!result) {
55632                 stringMappingTypes.set(id, result = createStringMappingType(symbol, type));
55633             }
55634             return result;
55635         }
55636         function createStringMappingType(symbol, type) {
55637             var result = createType(268435456 /* StringMapping */);
55638             result.symbol = symbol;
55639             result.type = type;
55640             return result;
55641         }
55642         function createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined) {
55643             var type = createType(8388608 /* IndexedAccess */);
55644             type.objectType = objectType;
55645             type.indexType = indexType;
55646             type.aliasSymbol = aliasSymbol;
55647             type.aliasTypeArguments = aliasTypeArguments;
55648             type.noUncheckedIndexedAccessCandidate = shouldIncludeUndefined;
55649             return type;
55650         }
55651         /**
55652          * Returns if a type is or consists of a JSLiteral object type
55653          * In addition to objects which are directly literals,
55654          * * unions where every element is a jsliteral
55655          * * intersections where at least one element is a jsliteral
55656          * * and instantiable types constrained to a jsliteral
55657          * Should all count as literals and not print errors on access or assignment of possibly existing properties.
55658          * This mirrors the behavior of the index signature propagation, to which this behaves similarly (but doesn't affect assignability or inference).
55659          */
55660         function isJSLiteralType(type) {
55661             if (noImplicitAny) {
55662                 return false; // Flag is meaningless under `noImplicitAny` mode
55663             }
55664             if (ts.getObjectFlags(type) & 16384 /* JSLiteral */) {
55665                 return true;
55666             }
55667             if (type.flags & 1048576 /* Union */) {
55668                 return ts.every(type.types, isJSLiteralType);
55669             }
55670             if (type.flags & 2097152 /* Intersection */) {
55671                 return ts.some(type.types, isJSLiteralType);
55672             }
55673             if (type.flags & 465829888 /* Instantiable */) {
55674                 return isJSLiteralType(getResolvedBaseConstraint(type));
55675             }
55676             return false;
55677         }
55678         function getPropertyNameFromIndex(indexType, accessNode) {
55679             var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined;
55680             return isTypeUsableAsPropertyName(indexType) ?
55681                 getPropertyNameFromType(indexType) :
55682                 accessExpression && checkThatExpressionIsProperSymbolReference(accessExpression.argumentExpression, indexType, /*reportError*/ false) ?
55683                     ts.getPropertyNameForKnownSymbolName(ts.idText(accessExpression.argumentExpression.name)) :
55684                     accessNode && ts.isPropertyName(accessNode) ?
55685                         // late bound names are handled in the first branch, so here we only need to handle normal names
55686                         ts.getPropertyNameForPropertyNameNode(accessNode) :
55687                         undefined;
55688         }
55689         function isUncalledFunctionReference(node, symbol) {
55690             return !(symbol.flags & (16 /* Function */ | 8192 /* Method */))
55691                 || !ts.isCallLikeExpression(ts.findAncestor(node, function (n) { return !ts.isAccessExpression(n); }) || node.parent)
55692                     && ts.every(symbol.declarations, function (d) { return !ts.isFunctionLike(d) || !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); });
55693         }
55694         function getPropertyTypeForIndexType(originalObjectType, objectType, indexType, fullIndexType, suppressNoImplicitAnyError, accessNode, accessFlags, noUncheckedIndexedAccessCandidate, reportDeprecated) {
55695             var _a;
55696             var accessExpression = accessNode && accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode : undefined;
55697             var propName = accessNode && ts.isPrivateIdentifier(accessNode) ? undefined : getPropertyNameFromIndex(indexType, accessNode);
55698             if (propName !== undefined) {
55699                 var prop = getPropertyOfType(objectType, propName);
55700                 if (prop) {
55701                     if (reportDeprecated && accessNode && getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(accessNode, prop)) {
55702                         var deprecatedNode = (_a = accessExpression === null || accessExpression === void 0 ? void 0 : accessExpression.argumentExpression) !== null && _a !== void 0 ? _a : (ts.isIndexedAccessTypeNode(accessNode) ? accessNode.indexType : accessNode);
55703                         errorOrSuggestion(/* isError */ false, deprecatedNode, ts.Diagnostics._0_is_deprecated, propName);
55704                     }
55705                     if (accessExpression) {
55706                         markPropertyAsReferenced(prop, accessExpression, /*isThisAccess*/ accessExpression.expression.kind === 107 /* ThisKeyword */);
55707                         if (isAssignmentToReadonlyEntity(accessExpression, prop, ts.getAssignmentTargetKind(accessExpression))) {
55708                             error(accessExpression.argumentExpression, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(prop));
55709                             return undefined;
55710                         }
55711                         if (accessFlags & 4 /* CacheSymbol */) {
55712                             getNodeLinks(accessNode).resolvedSymbol = prop;
55713                         }
55714                         if (isThisPropertyAccessInConstructor(accessExpression, prop)) {
55715                             return autoType;
55716                         }
55717                     }
55718                     var propType = getTypeOfSymbol(prop);
55719                     return accessExpression && ts.getAssignmentTargetKind(accessExpression) !== 1 /* Definite */ ?
55720                         getFlowTypeOfReference(accessExpression, propType) :
55721                         propType;
55722                 }
55723                 if (everyType(objectType, isTupleType) && isNumericLiteralName(propName) && +propName >= 0) {
55724                     if (accessNode && everyType(objectType, function (t) { return !t.target.hasRestElement; }) && !(accessFlags & 8 /* NoTupleBoundsCheck */)) {
55725                         var indexNode = getIndexNodeForAccessExpression(accessNode);
55726                         if (isTupleType(objectType)) {
55727                             error(indexNode, ts.Diagnostics.Tuple_type_0_of_length_1_has_no_element_at_index_2, typeToString(objectType), getTypeReferenceArity(objectType), ts.unescapeLeadingUnderscores(propName));
55728                         }
55729                         else {
55730                             error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
55731                         }
55732                     }
55733                     errorIfWritingToReadonlyIndex(getIndexInfoOfType(objectType, 1 /* Number */));
55734                     return mapType(objectType, function (t) {
55735                         var restType = getRestTypeOfTupleType(t) || undefinedType;
55736                         return noUncheckedIndexedAccessCandidate ? getUnionType([restType, undefinedType]) : restType;
55737                     });
55738                 }
55739             }
55740             if (!(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */)) {
55741                 if (objectType.flags & (1 /* Any */ | 131072 /* Never */)) {
55742                     return objectType;
55743                 }
55744                 var stringIndexInfo = getIndexInfoOfType(objectType, 0 /* String */);
55745                 var indexInfo = isTypeAssignableToKind(indexType, 296 /* NumberLike */) && getIndexInfoOfType(objectType, 1 /* Number */) || stringIndexInfo;
55746                 if (indexInfo) {
55747                     if (accessFlags & 1 /* NoIndexSignatures */ && indexInfo === stringIndexInfo) {
55748                         if (accessExpression) {
55749                             error(accessExpression, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(originalObjectType));
55750                         }
55751                         return undefined;
55752                     }
55753                     if (accessNode && !isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
55754                         var indexNode = getIndexNodeForAccessExpression(accessNode);
55755                         error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
55756                         return noUncheckedIndexedAccessCandidate ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
55757                     }
55758                     errorIfWritingToReadonlyIndex(indexInfo);
55759                     return noUncheckedIndexedAccessCandidate ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
55760                 }
55761                 if (indexType.flags & 131072 /* Never */) {
55762                     return neverType;
55763                 }
55764                 if (isJSLiteralType(objectType)) {
55765                     return anyType;
55766                 }
55767                 if (accessExpression && !isConstEnumObjectType(objectType)) {
55768                     if (objectType.symbol === globalThisSymbol && propName !== undefined && globalThisSymbol.exports.has(propName) && (globalThisSymbol.exports.get(propName).flags & 418 /* BlockScoped */)) {
55769                         error(accessExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(propName), typeToString(objectType));
55770                     }
55771                     else if (noImplicitAny && !compilerOptions.suppressImplicitAnyIndexErrors && !suppressNoImplicitAnyError) {
55772                         if (propName !== undefined && typeHasStaticProperty(propName, objectType)) {
55773                             error(accessExpression, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, propName, typeToString(objectType));
55774                         }
55775                         else if (getIndexTypeOfType(objectType, 1 /* Number */)) {
55776                             error(accessExpression.argumentExpression, ts.Diagnostics.Element_implicitly_has_an_any_type_because_index_expression_is_not_of_type_number);
55777                         }
55778                         else {
55779                             var suggestion = void 0;
55780                             if (propName !== undefined && (suggestion = getSuggestionForNonexistentProperty(propName, objectType))) {
55781                                 if (suggestion !== undefined) {
55782                                     error(accessExpression.argumentExpression, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(objectType), suggestion);
55783                                 }
55784                             }
55785                             else {
55786                                 var suggestion_1 = getSuggestionForNonexistentIndexSignature(objectType, accessExpression, indexType);
55787                                 if (suggestion_1 !== undefined) {
55788                                     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);
55789                                 }
55790                                 else {
55791                                     var errorInfo = void 0;
55792                                     if (indexType.flags & 1024 /* EnumLiteral */) {
55793                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + typeToString(indexType) + "]", typeToString(objectType));
55794                                     }
55795                                     else if (indexType.flags & 8192 /* UniqueESSymbol */) {
55796                                         var symbolName_2 = getFullyQualifiedName(indexType.symbol, accessExpression);
55797                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "[" + symbolName_2 + "]", typeToString(objectType));
55798                                     }
55799                                     else if (indexType.flags & 128 /* StringLiteral */) {
55800                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
55801                                     }
55802                                     else if (indexType.flags & 256 /* NumberLiteral */) {
55803                                         errorInfo = ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics.Property_0_does_not_exist_on_type_1, indexType.value, typeToString(objectType));
55804                                     }
55805                                     else if (indexType.flags & (8 /* Number */ | 4 /* String */)) {
55806                                         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));
55807                                     }
55808                                     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));
55809                                     diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(accessExpression, errorInfo));
55810                                 }
55811                             }
55812                         }
55813                     }
55814                     return undefined;
55815                 }
55816             }
55817             if (isJSLiteralType(objectType)) {
55818                 return anyType;
55819             }
55820             if (accessNode) {
55821                 var indexNode = getIndexNodeForAccessExpression(accessNode);
55822                 if (indexType.flags & (128 /* StringLiteral */ | 256 /* NumberLiteral */)) {
55823                     error(indexNode, ts.Diagnostics.Property_0_does_not_exist_on_type_1, "" + indexType.value, typeToString(objectType));
55824                 }
55825                 else if (indexType.flags & (4 /* String */ | 8 /* Number */)) {
55826                     error(indexNode, ts.Diagnostics.Type_0_has_no_matching_index_signature_for_type_1, typeToString(objectType), typeToString(indexType));
55827                 }
55828                 else {
55829                     error(indexNode, ts.Diagnostics.Type_0_cannot_be_used_as_an_index_type, typeToString(indexType));
55830                 }
55831             }
55832             if (isTypeAny(indexType)) {
55833                 return indexType;
55834             }
55835             return undefined;
55836             function errorIfWritingToReadonlyIndex(indexInfo) {
55837                 if (indexInfo && indexInfo.isReadonly && accessExpression && (ts.isAssignmentTarget(accessExpression) || ts.isDeleteTarget(accessExpression))) {
55838                     error(accessExpression, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
55839                 }
55840             }
55841         }
55842         function getIndexNodeForAccessExpression(accessNode) {
55843             return accessNode.kind === 202 /* ElementAccessExpression */ ? accessNode.argumentExpression :
55844                 accessNode.kind === 189 /* IndexedAccessType */ ? accessNode.indexType :
55845                     accessNode.kind === 158 /* ComputedPropertyName */ ? accessNode.expression :
55846                         accessNode;
55847         }
55848         function isPatternLiteralPlaceholderType(type) {
55849             return templateConstraintType.types.indexOf(type) !== -1 || !!(type.flags & 1 /* Any */);
55850         }
55851         function isPatternLiteralType(type) {
55852             return !!(type.flags & 134217728 /* TemplateLiteral */) && ts.every(type.types, isPatternLiteralPlaceholderType);
55853         }
55854         function isGenericObjectType(type) {
55855             if (type.flags & 3145728 /* UnionOrIntersection */) {
55856                 if (!(type.objectFlags & 4194304 /* IsGenericObjectTypeComputed */)) {
55857                     type.objectFlags |= 4194304 /* IsGenericObjectTypeComputed */ |
55858                         (ts.some(type.types, isGenericObjectType) ? 8388608 /* IsGenericObjectType */ : 0);
55859                 }
55860                 return !!(type.objectFlags & 8388608 /* IsGenericObjectType */);
55861             }
55862             return !!(type.flags & 58982400 /* InstantiableNonPrimitive */) || isGenericMappedType(type) || isGenericTupleType(type);
55863         }
55864         function isGenericIndexType(type) {
55865             if (type.flags & 3145728 /* UnionOrIntersection */) {
55866                 if (!(type.objectFlags & 16777216 /* IsGenericIndexTypeComputed */)) {
55867                     type.objectFlags |= 16777216 /* IsGenericIndexTypeComputed */ |
55868                         (ts.some(type.types, isGenericIndexType) ? 33554432 /* IsGenericIndexType */ : 0);
55869                 }
55870                 return !!(type.objectFlags & 33554432 /* IsGenericIndexType */);
55871             }
55872             return !!(type.flags & (58982400 /* InstantiableNonPrimitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */)) && !isPatternLiteralType(type);
55873         }
55874         function isThisTypeParameter(type) {
55875             return !!(type.flags & 262144 /* TypeParameter */ && type.isThisType);
55876         }
55877         function getSimplifiedType(type, writing) {
55878             return type.flags & 8388608 /* IndexedAccess */ ? getSimplifiedIndexedAccessType(type, writing) :
55879                 type.flags & 16777216 /* Conditional */ ? getSimplifiedConditionalType(type, writing) :
55880                     type;
55881         }
55882         function distributeIndexOverObjectType(objectType, indexType, writing) {
55883             // (T | U)[K] -> T[K] | U[K] (reading)
55884             // (T | U)[K] -> T[K] & U[K] (writing)
55885             // (T & U)[K] -> T[K] & U[K]
55886             if (objectType.flags & 3145728 /* UnionOrIntersection */) {
55887                 var types = ts.map(objectType.types, function (t) { return getSimplifiedType(getIndexedAccessType(t, indexType), writing); });
55888                 return objectType.flags & 2097152 /* Intersection */ || writing ? getIntersectionType(types) : getUnionType(types);
55889             }
55890         }
55891         function distributeObjectOverIndexType(objectType, indexType, writing) {
55892             // T[A | B] -> T[A] | T[B] (reading)
55893             // T[A | B] -> T[A] & T[B] (writing)
55894             if (indexType.flags & 1048576 /* Union */) {
55895                 var types = ts.map(indexType.types, function (t) { return getSimplifiedType(getIndexedAccessType(objectType, t), writing); });
55896                 return writing ? getIntersectionType(types) : getUnionType(types);
55897             }
55898         }
55899         function unwrapSubstitution(type) {
55900             if (type.flags & 33554432 /* Substitution */) {
55901                 return type.substitute;
55902             }
55903             return type;
55904         }
55905         // Transform an indexed access to a simpler form, if possible. Return the simpler form, or return
55906         // the type itself if no transformation is possible. The writing flag indicates that the type is
55907         // the target of an assignment.
55908         function getSimplifiedIndexedAccessType(type, writing) {
55909             var cache = writing ? "simplifiedForWriting" : "simplifiedForReading";
55910             if (type[cache]) {
55911                 return type[cache] === circularConstraintType ? type : type[cache];
55912             }
55913             type[cache] = circularConstraintType;
55914             // We recursively simplify the object type as it may in turn be an indexed access type. For example, with
55915             // '{ [P in T]: { [Q in U]: number } }[T][U]' we want to first simplify the inner indexed access type.
55916             var objectType = unwrapSubstitution(getSimplifiedType(type.objectType, writing));
55917             var indexType = getSimplifiedType(type.indexType, writing);
55918             // T[A | B] -> T[A] | T[B] (reading)
55919             // T[A | B] -> T[A] & T[B] (writing)
55920             var distributedOverIndex = distributeObjectOverIndexType(objectType, indexType, writing);
55921             if (distributedOverIndex) {
55922                 return type[cache] = distributedOverIndex;
55923             }
55924             // Only do the inner distributions if the index can no longer be instantiated to cause index distribution again
55925             if (!(indexType.flags & 465829888 /* Instantiable */)) {
55926                 // (T | U)[K] -> T[K] | U[K] (reading)
55927                 // (T | U)[K] -> T[K] & U[K] (writing)
55928                 // (T & U)[K] -> T[K] & U[K]
55929                 var distributedOverObject = distributeIndexOverObjectType(objectType, indexType, writing);
55930                 if (distributedOverObject) {
55931                     return type[cache] = distributedOverObject;
55932                 }
55933             }
55934             // So ultimately (reading):
55935             // ((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]
55936             // A generic tuple type indexed by a number exists only when the index type doesn't select a
55937             // fixed element. We simplify to either the combined type of all elements (when the index type
55938             // the actual number type) or to the combined type of all non-fixed elements.
55939             if (isGenericTupleType(objectType) && indexType.flags & 296 /* NumberLike */) {
55940                 var elementType = getElementTypeOfSliceOfTupleType(objectType, indexType.flags & 8 /* Number */ ? 0 : objectType.target.fixedLength, /*endSkipCount*/ 0, writing);
55941                 if (elementType) {
55942                     return type[cache] = elementType;
55943                 }
55944             }
55945             // If the object type is a mapped type { [P in K]: E }, where K is generic, instantiate E using a mapper
55946             // that substitutes the index type for P. For example, for an index access { [P in K]: Box<T[P]> }[X], we
55947             // construct the type Box<T[X]>.
55948             if (isGenericMappedType(objectType)) {
55949                 return type[cache] = mapType(substituteIndexedMappedType(objectType, type.indexType), function (t) { return getSimplifiedType(t, writing); });
55950             }
55951             return type[cache] = type;
55952         }
55953         function getSimplifiedConditionalType(type, writing) {
55954             var checkType = type.checkType;
55955             var extendsType = type.extendsType;
55956             var trueType = getTrueTypeFromConditionalType(type);
55957             var falseType = getFalseTypeFromConditionalType(type);
55958             // Simplifications for types of the form `T extends U ? T : never` and `T extends U ? never : T`.
55959             if (falseType.flags & 131072 /* Never */ && getActualTypeVariable(trueType) === getActualTypeVariable(checkType)) {
55960                 if (checkType.flags & 1 /* Any */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
55961                     return getSimplifiedType(trueType, writing);
55962                 }
55963                 else if (isIntersectionEmpty(checkType, extendsType)) { // Always false
55964                     return neverType;
55965                 }
55966             }
55967             else if (trueType.flags & 131072 /* Never */ && getActualTypeVariable(falseType) === getActualTypeVariable(checkType)) {
55968                 if (!(checkType.flags & 1 /* Any */) && isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(extendsType))) { // Always true
55969                     return neverType;
55970                 }
55971                 else if (checkType.flags & 1 /* Any */ || isIntersectionEmpty(checkType, extendsType)) { // Always false
55972                     return getSimplifiedType(falseType, writing);
55973                 }
55974             }
55975             return type;
55976         }
55977         /**
55978          * Invokes union simplification logic to determine if an intersection is considered empty as a union constituent
55979          */
55980         function isIntersectionEmpty(type1, type2) {
55981             return !!(getUnionType([intersectTypes(type1, type2), neverType]).flags & 131072 /* Never */);
55982         }
55983         function substituteIndexedMappedType(objectType, index) {
55984             var mapper = createTypeMapper([getTypeParameterFromMappedType(objectType)], [index]);
55985             var templateMapper = combineTypeMappers(objectType.mapper, mapper);
55986             return instantiateType(getTemplateTypeFromMappedType(objectType), templateMapper);
55987         }
55988         function getIndexedAccessType(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, aliasSymbol, aliasTypeArguments, accessFlags) {
55989             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
55990             return getIndexedAccessTypeOrUndefined(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) || (accessNode ? errorType : unknownType);
55991         }
55992         function indexTypeLessThan(indexType, limit) {
55993             return everyType(indexType, function (t) {
55994                 if (t.flags & 384 /* StringOrNumberLiteral */) {
55995                     var propName = getPropertyNameFromType(t);
55996                     if (isNumericLiteralName(propName)) {
55997                         var index = +propName;
55998                         return index >= 0 && index < limit;
55999                     }
56000                 }
56001                 return false;
56002             });
56003         }
56004         function getIndexedAccessTypeOrUndefined(objectType, indexType, noUncheckedIndexedAccessCandidate, accessNode, accessFlags, aliasSymbol, aliasTypeArguments) {
56005             if (accessFlags === void 0) { accessFlags = 0 /* None */; }
56006             if (objectType === wildcardType || indexType === wildcardType) {
56007                 return wildcardType;
56008             }
56009             var shouldIncludeUndefined = noUncheckedIndexedAccessCandidate ||
56010                 (!!compilerOptions.noUncheckedIndexedAccess &&
56011                     (accessFlags & (2 /* Writing */ | 16 /* ExpressionPosition */)) === 16 /* ExpressionPosition */);
56012             // If the object type has a string index signature and no other members we know that the result will
56013             // always be the type of that index signature and we can simplify accordingly.
56014             if (isStringIndexSignatureOnlyType(objectType) && !(indexType.flags & 98304 /* Nullable */) && isTypeAssignableToKind(indexType, 4 /* String */ | 8 /* Number */)) {
56015                 indexType = stringType;
56016             }
56017             // If the index type is generic, or if the object type is generic and doesn't originate in an expression and
56018             // the operation isn't exclusively indexing the fixed (non-variadic) portion of a tuple type, we are performing
56019             // a higher-order index access where we cannot meaningfully access the properties of the object type. Note that
56020             // for a generic T and a non-generic K, we eagerly resolve T[K] if it originates in an expression. This is to
56021             // preserve backwards compatibility. For example, an element access 'this["foo"]' has always been resolved
56022             // eagerly using the constraint type of 'this' at the given location.
56023             if (isGenericIndexType(indexType) || (accessNode && accessNode.kind !== 189 /* IndexedAccessType */ ?
56024                 isGenericTupleType(objectType) && !indexTypeLessThan(indexType, objectType.target.fixedLength) :
56025                 isGenericObjectType(objectType) && !(isTupleType(objectType) && indexTypeLessThan(indexType, objectType.target.fixedLength)))) {
56026                 if (objectType.flags & 3 /* AnyOrUnknown */) {
56027                     return objectType;
56028                 }
56029                 // Defer the operation by creating an indexed access type.
56030                 var id = objectType.id + "," + indexType.id + (shouldIncludeUndefined ? "?" : "");
56031                 var type = indexedAccessTypes.get(id);
56032                 if (!type) {
56033                     indexedAccessTypes.set(id, type = createIndexedAccessType(objectType, indexType, aliasSymbol, aliasTypeArguments, shouldIncludeUndefined));
56034                 }
56035                 return type;
56036             }
56037             // In the following we resolve T[K] to the type of the property in T selected by K.
56038             // We treat boolean as different from other unions to improve errors;
56039             // skipping straight to getPropertyTypeForIndexType gives errors with 'boolean' instead of 'true'.
56040             var apparentObjectType = getReducedApparentType(objectType);
56041             if (indexType.flags & 1048576 /* Union */ && !(indexType.flags & 16 /* Boolean */)) {
56042                 var propTypes = [];
56043                 var wasMissingProp = false;
56044                 for (var _i = 0, _a = indexType.types; _i < _a.length; _i++) {
56045                     var t = _a[_i];
56046                     var propType = getPropertyTypeForIndexType(objectType, apparentObjectType, t, indexType, wasMissingProp, accessNode, accessFlags, shouldIncludeUndefined);
56047                     if (propType) {
56048                         propTypes.push(propType);
56049                     }
56050                     else if (!accessNode) {
56051                         // If there's no error node, we can immeditely stop, since error reporting is off
56052                         return undefined;
56053                     }
56054                     else {
56055                         // Otherwise we set a flag and return at the end of the loop so we still mark all errors
56056                         wasMissingProp = true;
56057                     }
56058                 }
56059                 if (wasMissingProp) {
56060                     return undefined;
56061                 }
56062                 return accessFlags & 2 /* Writing */
56063                     ? getIntersectionType(propTypes, aliasSymbol, aliasTypeArguments)
56064                     : getUnionType(propTypes, 1 /* Literal */, aliasSymbol, aliasTypeArguments);
56065             }
56066             return getPropertyTypeForIndexType(objectType, apparentObjectType, indexType, indexType, /* supressNoImplicitAnyError */ false, accessNode, accessFlags | 4 /* CacheSymbol */, shouldIncludeUndefined, /* reportDeprecated */ true);
56067         }
56068         function getTypeFromIndexedAccessTypeNode(node) {
56069             var links = getNodeLinks(node);
56070             if (!links.resolvedType) {
56071                 var objectType = getTypeFromTypeNode(node.objectType);
56072                 var indexType = getTypeFromTypeNode(node.indexType);
56073                 var potentialAlias = getAliasSymbolForTypeNode(node);
56074                 var resolved = getIndexedAccessType(objectType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, potentialAlias, getTypeArgumentsForAliasSymbol(potentialAlias));
56075                 links.resolvedType = resolved.flags & 8388608 /* IndexedAccess */ &&
56076                     resolved.objectType === objectType &&
56077                     resolved.indexType === indexType ?
56078                     getConditionalFlowTypeOfType(resolved, node) : resolved;
56079             }
56080             return links.resolvedType;
56081         }
56082         function getTypeFromMappedTypeNode(node) {
56083             var links = getNodeLinks(node);
56084             if (!links.resolvedType) {
56085                 var type = createObjectType(32 /* Mapped */, node.symbol);
56086                 type.declaration = node;
56087                 type.aliasSymbol = getAliasSymbolForTypeNode(node);
56088                 type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(type.aliasSymbol);
56089                 links.resolvedType = type;
56090                 // Eagerly resolve the constraint type which forces an error if the constraint type circularly
56091                 // references itself through one or more type aliases.
56092                 getConstraintTypeFromMappedType(type);
56093             }
56094             return links.resolvedType;
56095         }
56096         function getActualTypeVariable(type) {
56097             if (type.flags & 33554432 /* Substitution */) {
56098                 return type.baseType;
56099             }
56100             if (type.flags & 8388608 /* IndexedAccess */ && (type.objectType.flags & 33554432 /* Substitution */ ||
56101                 type.indexType.flags & 33554432 /* Substitution */)) {
56102                 return getIndexedAccessType(getActualTypeVariable(type.objectType), getActualTypeVariable(type.indexType));
56103             }
56104             return type;
56105         }
56106         function getConditionalType(root, mapper) {
56107             var result;
56108             var extraTypes;
56109             var _loop_15 = function () {
56110                 var checkType = instantiateType(root.checkType, mapper);
56111                 var checkTypeInstantiable = isGenericObjectType(checkType) || isGenericIndexType(checkType);
56112                 var extendsType = instantiateType(root.extendsType, mapper);
56113                 if (checkType === wildcardType || extendsType === wildcardType) {
56114                     return { value: wildcardType };
56115                 }
56116                 var combinedMapper = void 0;
56117                 if (root.inferTypeParameters) {
56118                     var context = createInferenceContext(root.inferTypeParameters, /*signature*/ undefined, 0 /* None */);
56119                     // We skip inference of the possible `infer` types unles the `extendsType` _is_ an infer type
56120                     // if it was, it's trivial to say that extendsType = checkType, however such a pattern is used to
56121                     // "reset" the type being build up during constraint calculation and avoid making an apparently "infinite" constraint
56122                     // so in those cases we refain from performing inference and retain the uninfered type parameter
56123                     if (!checkTypeInstantiable || !ts.some(root.inferTypeParameters, function (t) { return t === extendsType; })) {
56124                         // We don't want inferences from constraints as they may cause us to eagerly resolve the
56125                         // conditional type instead of deferring resolution. Also, we always want strict function
56126                         // types rules (i.e. proper contravariance) for inferences.
56127                         inferTypes(context.inferences, checkType, extendsType, 256 /* NoConstraints */ | 512 /* AlwaysStrict */);
56128                     }
56129                     combinedMapper = mergeTypeMappers(mapper, context.mapper);
56130                 }
56131                 // Instantiate the extends type including inferences for 'infer T' type parameters
56132                 var inferredExtendsType = combinedMapper ? instantiateType(root.extendsType, combinedMapper) : extendsType;
56133                 // We attempt to resolve the conditional type only when the check and extends types are non-generic
56134                 if (!checkTypeInstantiable && !isGenericObjectType(inferredExtendsType) && !isGenericIndexType(inferredExtendsType)) {
56135                     // Return falseType for a definitely false extends check. We check an instantiations of the two
56136                     // types with type parameters mapped to the wildcard type, the most permissive instantiations
56137                     // possible (the wildcard type is assignable to and from all types). If those are not related,
56138                     // then no instantiations will be and we can just return the false branch type.
56139                     if (!(inferredExtendsType.flags & 3 /* AnyOrUnknown */) && (checkType.flags & 1 /* Any */ || !isTypeAssignableTo(getPermissiveInstantiation(checkType), getPermissiveInstantiation(inferredExtendsType)))) {
56140                         // Return union of trueType and falseType for 'any' since it matches anything
56141                         if (checkType.flags & 1 /* Any */) {
56142                             (extraTypes || (extraTypes = [])).push(instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper));
56143                         }
56144                         // If falseType is an immediately nested conditional type that isn't distributive or has an
56145                         // identical checkType, switch to that type and loop.
56146                         var falseType_1 = getTypeFromTypeNode(root.node.falseType);
56147                         if (falseType_1.flags & 16777216 /* Conditional */) {
56148                             var newRoot = falseType_1.root;
56149                             if (newRoot.node.parent === root.node && (!newRoot.isDistributive || newRoot.checkType === root.checkType)) {
56150                                 root = newRoot;
56151                                 return "continue";
56152                             }
56153                         }
56154                         result = instantiateType(falseType_1, mapper);
56155                         return "break";
56156                     }
56157                     // Return trueType for a definitely true extends check. We check instantiations of the two
56158                     // types with type parameters mapped to their restrictive form, i.e. a form of the type parameter
56159                     // that has no constraint. This ensures that, for example, the type
56160                     //   type Foo<T extends { x: any }> = T extends { x: string } ? string : number
56161                     // doesn't immediately resolve to 'string' instead of being deferred.
56162                     if (inferredExtendsType.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(checkType), getRestrictiveInstantiation(inferredExtendsType))) {
56163                         result = instantiateType(getTypeFromTypeNode(root.node.trueType), combinedMapper || mapper);
56164                         return "break";
56165                     }
56166                 }
56167                 // Return a deferred type for a check that is neither definitely true nor definitely false
56168                 var erasedCheckType = getActualTypeVariable(checkType);
56169                 result = createType(16777216 /* Conditional */);
56170                 result.root = root;
56171                 result.checkType = erasedCheckType;
56172                 result.extendsType = extendsType;
56173                 result.mapper = mapper;
56174                 result.combinedMapper = combinedMapper;
56175                 result.aliasSymbol = root.aliasSymbol;
56176                 result.aliasTypeArguments = instantiateTypes(root.aliasTypeArguments, mapper); // TODO: GH#18217
56177                 return "break";
56178             };
56179             // We loop here for an immediately nested conditional type in the false position, effectively treating
56180             // types of the form 'A extends B ? X : C extends D ? Y : E extends F ? Z : ...' as a single construct for
56181             // purposes of resolution. This means such types aren't subject to the instatiation depth limiter.
56182             while (true) {
56183                 var state_4 = _loop_15();
56184                 if (typeof state_4 === "object")
56185                     return state_4.value;
56186                 if (state_4 === "break")
56187                     break;
56188             }
56189             return extraTypes ? getUnionType(ts.append(extraTypes, result)) : result;
56190         }
56191         function getTrueTypeFromConditionalType(type) {
56192             return type.resolvedTrueType || (type.resolvedTrueType = instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.mapper));
56193         }
56194         function getFalseTypeFromConditionalType(type) {
56195             return type.resolvedFalseType || (type.resolvedFalseType = instantiateType(getTypeFromTypeNode(type.root.node.falseType), type.mapper));
56196         }
56197         function getInferredTrueTypeFromConditionalType(type) {
56198             return type.resolvedInferredTrueType || (type.resolvedInferredTrueType = type.combinedMapper ? instantiateType(getTypeFromTypeNode(type.root.node.trueType), type.combinedMapper) : getTrueTypeFromConditionalType(type));
56199         }
56200         function getInferTypeParameters(node) {
56201             var result;
56202             if (node.locals) {
56203                 node.locals.forEach(function (symbol) {
56204                     if (symbol.flags & 262144 /* TypeParameter */) {
56205                         result = ts.append(result, getDeclaredTypeOfSymbol(symbol));
56206                     }
56207                 });
56208             }
56209             return result;
56210         }
56211         function getTypeFromConditionalTypeNode(node) {
56212             var links = getNodeLinks(node);
56213             if (!links.resolvedType) {
56214                 var checkType = getTypeFromTypeNode(node.checkType);
56215                 var aliasSymbol = getAliasSymbolForTypeNode(node);
56216                 var aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
56217                 var allOuterTypeParameters = getOuterTypeParameters(node, /*includeThisTypes*/ true);
56218                 var outerTypeParameters = aliasTypeArguments ? allOuterTypeParameters : ts.filter(allOuterTypeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, node); });
56219                 var root = {
56220                     node: node,
56221                     checkType: checkType,
56222                     extendsType: getTypeFromTypeNode(node.extendsType),
56223                     isDistributive: !!(checkType.flags & 262144 /* TypeParameter */),
56224                     inferTypeParameters: getInferTypeParameters(node),
56225                     outerTypeParameters: outerTypeParameters,
56226                     instantiations: undefined,
56227                     aliasSymbol: aliasSymbol,
56228                     aliasTypeArguments: aliasTypeArguments
56229                 };
56230                 links.resolvedType = getConditionalType(root, /*mapper*/ undefined);
56231                 if (outerTypeParameters) {
56232                     root.instantiations = new ts.Map();
56233                     root.instantiations.set(getTypeListId(outerTypeParameters), links.resolvedType);
56234                 }
56235             }
56236             return links.resolvedType;
56237         }
56238         function getTypeFromInferTypeNode(node) {
56239             var links = getNodeLinks(node);
56240             if (!links.resolvedType) {
56241                 links.resolvedType = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node.typeParameter));
56242             }
56243             return links.resolvedType;
56244         }
56245         function getIdentifierChain(node) {
56246             if (ts.isIdentifier(node)) {
56247                 return [node];
56248             }
56249             else {
56250                 return ts.append(getIdentifierChain(node.left), node.right);
56251             }
56252         }
56253         function getTypeFromImportTypeNode(node) {
56254             var links = getNodeLinks(node);
56255             if (!links.resolvedType) {
56256                 if (node.isTypeOf && node.typeArguments) { // Only the non-typeof form can make use of type arguments
56257                     error(node, ts.Diagnostics.Type_arguments_cannot_be_used_here);
56258                     links.resolvedSymbol = unknownSymbol;
56259                     return links.resolvedType = errorType;
56260                 }
56261                 if (!ts.isLiteralImportTypeNode(node)) {
56262                     error(node.argument, ts.Diagnostics.String_literal_expected);
56263                     links.resolvedSymbol = unknownSymbol;
56264                     return links.resolvedType = errorType;
56265                 }
56266                 var targetMeaning = node.isTypeOf ? 111551 /* Value */ : node.flags & 4194304 /* JSDoc */ ? 111551 /* Value */ | 788968 /* Type */ : 788968 /* Type */;
56267                 // TODO: Future work: support unions/generics/whatever via a deferred import-type
56268                 var innerModuleSymbol = resolveExternalModuleName(node, node.argument.literal);
56269                 if (!innerModuleSymbol) {
56270                     links.resolvedSymbol = unknownSymbol;
56271                     return links.resolvedType = errorType;
56272                 }
56273                 var moduleSymbol = resolveExternalModuleSymbol(innerModuleSymbol, /*dontResolveAlias*/ false);
56274                 if (!ts.nodeIsMissing(node.qualifier)) {
56275                     var nameStack = getIdentifierChain(node.qualifier);
56276                     var currentNamespace = moduleSymbol;
56277                     var current = void 0;
56278                     while (current = nameStack.shift()) {
56279                         var meaning = nameStack.length ? 1920 /* Namespace */ : targetMeaning;
56280                         // typeof a.b.c is normally resolved using `checkExpression` which in turn defers to `checkQualifiedName`
56281                         // That, in turn, ultimately uses `getPropertyOfType` on the type of the symbol, which differs slightly from
56282                         // the `exports` lookup process that only looks up namespace members which is used for most type references
56283                         var mergedResolvedSymbol = getMergedSymbol(resolveSymbol(currentNamespace));
56284                         var next = node.isTypeOf
56285                             ? getPropertyOfType(getTypeOfSymbol(mergedResolvedSymbol), current.escapedText)
56286                             : getSymbol(getExportsOfSymbol(mergedResolvedSymbol), current.escapedText, meaning);
56287                         if (!next) {
56288                             error(current, ts.Diagnostics.Namespace_0_has_no_exported_member_1, getFullyQualifiedName(currentNamespace), ts.declarationNameToString(current));
56289                             return links.resolvedType = errorType;
56290                         }
56291                         getNodeLinks(current).resolvedSymbol = next;
56292                         getNodeLinks(current.parent).resolvedSymbol = next;
56293                         currentNamespace = next;
56294                     }
56295                     links.resolvedType = resolveImportSymbolType(node, links, currentNamespace, targetMeaning);
56296                 }
56297                 else {
56298                     if (moduleSymbol.flags & targetMeaning) {
56299                         links.resolvedType = resolveImportSymbolType(node, links, moduleSymbol, targetMeaning);
56300                     }
56301                     else {
56302                         var errorMessage = targetMeaning === 111551 /* Value */
56303                             ? ts.Diagnostics.Module_0_does_not_refer_to_a_value_but_is_used_as_a_value_here
56304                             : ts.Diagnostics.Module_0_does_not_refer_to_a_type_but_is_used_as_a_type_here_Did_you_mean_typeof_import_0;
56305                         error(node, errorMessage, node.argument.literal.text);
56306                         links.resolvedSymbol = unknownSymbol;
56307                         links.resolvedType = errorType;
56308                     }
56309                 }
56310             }
56311             return links.resolvedType;
56312         }
56313         function resolveImportSymbolType(node, links, symbol, meaning) {
56314             var resolvedSymbol = resolveSymbol(symbol);
56315             links.resolvedSymbol = resolvedSymbol;
56316             if (meaning === 111551 /* Value */) {
56317                 return getTypeOfSymbol(symbol); // intentionally doesn't use resolved symbol so type is cached as expected on the alias
56318             }
56319             else {
56320                 return getTypeReferenceType(node, resolvedSymbol); // getTypeReferenceType doesn't handle aliases - it must get the resolved symbol
56321             }
56322         }
56323         function getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node) {
56324             var links = getNodeLinks(node);
56325             if (!links.resolvedType) {
56326                 // Deferred resolution of members is handled by resolveObjectTypeMembers
56327                 var aliasSymbol = getAliasSymbolForTypeNode(node);
56328                 if (getMembersOfSymbol(node.symbol).size === 0 && !aliasSymbol) {
56329                     links.resolvedType = emptyTypeLiteralType;
56330                 }
56331                 else {
56332                     var type = createObjectType(16 /* Anonymous */, node.symbol);
56333                     type.aliasSymbol = aliasSymbol;
56334                     type.aliasTypeArguments = getTypeArgumentsForAliasSymbol(aliasSymbol);
56335                     if (ts.isJSDocTypeLiteral(node) && node.isArrayType) {
56336                         type = createArrayType(type);
56337                     }
56338                     links.resolvedType = type;
56339                 }
56340             }
56341             return links.resolvedType;
56342         }
56343         function getAliasSymbolForTypeNode(node) {
56344             var host = node.parent;
56345             while (ts.isParenthesizedTypeNode(host) || ts.isJSDocTypeExpression(host) || ts.isTypeOperatorNode(host) && host.operator === 142 /* ReadonlyKeyword */) {
56346                 host = host.parent;
56347             }
56348             return ts.isTypeAlias(host) ? getSymbolOfNode(host) : undefined;
56349         }
56350         function getTypeArgumentsForAliasSymbol(symbol) {
56351             return symbol ? getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(symbol) : undefined;
56352         }
56353         function isNonGenericObjectType(type) {
56354             return !!(type.flags & 524288 /* Object */) && !isGenericMappedType(type);
56355         }
56356         function isEmptyObjectTypeOrSpreadsIntoEmptyObject(type) {
56357             return isEmptyObjectType(type) || !!(type.flags & (65536 /* Null */ | 32768 /* Undefined */ | 528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */));
56358         }
56359         function tryMergeUnionOfObjectTypeAndEmptyObject(type, readonly) {
56360             if (type.types.length === 2) {
56361                 var firstType = type.types[0];
56362                 var secondType = type.types[1];
56363                 if (ts.every(type.types, isEmptyObjectTypeOrSpreadsIntoEmptyObject)) {
56364                     return isEmptyObjectType(firstType) ? firstType : isEmptyObjectType(secondType) ? secondType : emptyObjectType;
56365                 }
56366                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(firstType)) {
56367                     return getAnonymousPartialType(secondType);
56368                 }
56369                 if (isEmptyObjectTypeOrSpreadsIntoEmptyObject(secondType)) {
56370                     return getAnonymousPartialType(firstType);
56371                 }
56372             }
56373             function getAnonymousPartialType(type) {
56374                 // gets the type as if it had been spread, but where everything in the spread is made optional
56375                 var members = ts.createSymbolTable();
56376                 for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
56377                     var prop = _a[_i];
56378                     if (ts.getDeclarationModifierFlagsFromSymbol(prop) & (8 /* Private */ | 16 /* Protected */)) {
56379                         // do nothing, skip privates
56380                     }
56381                     else if (isSpreadableProperty(prop)) {
56382                         var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
56383                         var flags = 4 /* Property */ | 16777216 /* Optional */;
56384                         var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
56385                         result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
56386                         result.declarations = prop.declarations;
56387                         result.nameType = getSymbolLinks(prop).nameType;
56388                         result.syntheticOrigin = prop;
56389                         members.set(prop.escapedName, result);
56390                     }
56391                 }
56392                 var spread = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoOfType(type, 0 /* String */), getIndexInfoOfType(type, 1 /* Number */));
56393                 spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
56394                 return spread;
56395             }
56396         }
56397         /**
56398          * Since the source of spread types are object literals, which are not binary,
56399          * this function should be called in a left folding style, with left = previous result of getSpreadType
56400          * and right = the new element to be spread.
56401          */
56402         function getSpreadType(left, right, symbol, objectFlags, readonly) {
56403             if (left.flags & 1 /* Any */ || right.flags & 1 /* Any */) {
56404                 return anyType;
56405             }
56406             if (left.flags & 2 /* Unknown */ || right.flags & 2 /* Unknown */) {
56407                 return unknownType;
56408             }
56409             if (left.flags & 131072 /* Never */) {
56410                 return right;
56411             }
56412             if (right.flags & 131072 /* Never */) {
56413                 return left;
56414             }
56415             if (left.flags & 1048576 /* Union */) {
56416                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(left, readonly);
56417                 if (merged) {
56418                     return getSpreadType(merged, right, symbol, objectFlags, readonly);
56419                 }
56420                 return checkCrossProductUnion([left, right])
56421                     ? mapType(left, function (t) { return getSpreadType(t, right, symbol, objectFlags, readonly); })
56422                     : errorType;
56423             }
56424             if (right.flags & 1048576 /* Union */) {
56425                 var merged = tryMergeUnionOfObjectTypeAndEmptyObject(right, readonly);
56426                 if (merged) {
56427                     return getSpreadType(left, merged, symbol, objectFlags, readonly);
56428                 }
56429                 return checkCrossProductUnion([left, right])
56430                     ? mapType(right, function (t) { return getSpreadType(left, t, symbol, objectFlags, readonly); })
56431                     : errorType;
56432             }
56433             if (right.flags & (528 /* BooleanLike */ | 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 1056 /* EnumLike */ | 67108864 /* NonPrimitive */ | 4194304 /* Index */)) {
56434                 return left;
56435             }
56436             if (isGenericObjectType(left) || isGenericObjectType(right)) {
56437                 if (isEmptyObjectType(left)) {
56438                     return right;
56439                 }
56440                 // When the left type is an intersection, we may need to merge the last constituent of the
56441                 // intersection with the right type. For example when the left type is 'T & { a: string }'
56442                 // and the right type is '{ b: string }' we produce 'T & { a: string, b: string }'.
56443                 if (left.flags & 2097152 /* Intersection */) {
56444                     var types = left.types;
56445                     var lastLeft = types[types.length - 1];
56446                     if (isNonGenericObjectType(lastLeft) && isNonGenericObjectType(right)) {
56447                         return getIntersectionType(ts.concatenate(types.slice(0, types.length - 1), [getSpreadType(lastLeft, right, symbol, objectFlags, readonly)]));
56448                     }
56449                 }
56450                 return getIntersectionType([left, right]);
56451             }
56452             var members = ts.createSymbolTable();
56453             var skippedPrivateMembers = new ts.Set();
56454             var stringIndexInfo;
56455             var numberIndexInfo;
56456             if (left === emptyObjectType) {
56457                 // for the first spread element, left === emptyObjectType, so take the right's string indexer
56458                 stringIndexInfo = getIndexInfoOfType(right, 0 /* String */);
56459                 numberIndexInfo = getIndexInfoOfType(right, 1 /* Number */);
56460             }
56461             else {
56462                 stringIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 0 /* String */), getIndexInfoOfType(right, 0 /* String */));
56463                 numberIndexInfo = unionSpreadIndexInfos(getIndexInfoOfType(left, 1 /* Number */), getIndexInfoOfType(right, 1 /* Number */));
56464             }
56465             for (var _i = 0, _a = getPropertiesOfType(right); _i < _a.length; _i++) {
56466                 var rightProp = _a[_i];
56467                 if (ts.getDeclarationModifierFlagsFromSymbol(rightProp) & (8 /* Private */ | 16 /* Protected */)) {
56468                     skippedPrivateMembers.add(rightProp.escapedName);
56469                 }
56470                 else if (isSpreadableProperty(rightProp)) {
56471                     members.set(rightProp.escapedName, getSpreadSymbol(rightProp, readonly));
56472                 }
56473             }
56474             for (var _b = 0, _c = getPropertiesOfType(left); _b < _c.length; _b++) {
56475                 var leftProp = _c[_b];
56476                 if (skippedPrivateMembers.has(leftProp.escapedName) || !isSpreadableProperty(leftProp)) {
56477                     continue;
56478                 }
56479                 if (members.has(leftProp.escapedName)) {
56480                     var rightProp = members.get(leftProp.escapedName);
56481                     var rightType = getTypeOfSymbol(rightProp);
56482                     if (rightProp.flags & 16777216 /* Optional */) {
56483                         var declarations = ts.concatenate(leftProp.declarations, rightProp.declarations);
56484                         var flags = 4 /* Property */ | (leftProp.flags & 16777216 /* Optional */);
56485                         var result = createSymbol(flags, leftProp.escapedName);
56486                         result.type = getUnionType([getTypeOfSymbol(leftProp), getTypeWithFacts(rightType, 524288 /* NEUndefined */)]);
56487                         result.leftSpread = leftProp;
56488                         result.rightSpread = rightProp;
56489                         result.declarations = declarations;
56490                         result.nameType = getSymbolLinks(leftProp).nameType;
56491                         members.set(leftProp.escapedName, result);
56492                     }
56493                 }
56494                 else {
56495                     members.set(leftProp.escapedName, getSpreadSymbol(leftProp, readonly));
56496                 }
56497             }
56498             var spread = createAnonymousType(symbol, members, ts.emptyArray, ts.emptyArray, getIndexInfoWithReadonly(stringIndexInfo, readonly), getIndexInfoWithReadonly(numberIndexInfo, readonly));
56499             spread.objectFlags |= 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */ | 1024 /* ContainsSpread */ | objectFlags;
56500             return spread;
56501         }
56502         /** We approximate own properties as non-methods plus methods that are inside the object literal */
56503         function isSpreadableProperty(prop) {
56504             return !ts.some(prop.declarations, ts.isPrivateIdentifierPropertyDeclaration) &&
56505                 (!(prop.flags & (8192 /* Method */ | 32768 /* GetAccessor */ | 65536 /* SetAccessor */)) ||
56506                     !prop.declarations.some(function (decl) { return ts.isClassLike(decl.parent); }));
56507         }
56508         function getSpreadSymbol(prop, readonly) {
56509             var isSetonlyAccessor = prop.flags & 65536 /* SetAccessor */ && !(prop.flags & 32768 /* GetAccessor */);
56510             if (!isSetonlyAccessor && readonly === isReadonlySymbol(prop)) {
56511                 return prop;
56512             }
56513             var flags = 4 /* Property */ | (prop.flags & 16777216 /* Optional */);
56514             var result = createSymbol(flags, prop.escapedName, readonly ? 8 /* Readonly */ : 0);
56515             result.type = isSetonlyAccessor ? undefinedType : getTypeOfSymbol(prop);
56516             result.declarations = prop.declarations;
56517             result.nameType = getSymbolLinks(prop).nameType;
56518             result.syntheticOrigin = prop;
56519             return result;
56520         }
56521         function getIndexInfoWithReadonly(info, readonly) {
56522             return info && info.isReadonly !== readonly ? createIndexInfo(info.type, readonly, info.declaration) : info;
56523         }
56524         function createLiteralType(flags, value, symbol) {
56525             var type = createType(flags);
56526             type.symbol = symbol;
56527             type.value = value;
56528             return type;
56529         }
56530         function getFreshTypeOfLiteralType(type) {
56531             if (type.flags & 2944 /* Literal */) {
56532                 if (!type.freshType) {
56533                     var freshType = createLiteralType(type.flags, type.value, type.symbol);
56534                     freshType.regularType = type;
56535                     freshType.freshType = freshType;
56536                     type.freshType = freshType;
56537                 }
56538                 return type.freshType;
56539             }
56540             return type;
56541         }
56542         function getRegularTypeOfLiteralType(type) {
56543             return type.flags & 2944 /* Literal */ ? type.regularType :
56544                 type.flags & 1048576 /* Union */ ? (type.regularType || (type.regularType = getUnionType(ts.sameMap(type.types, getRegularTypeOfLiteralType)))) :
56545                     type;
56546         }
56547         function isFreshLiteralType(type) {
56548             return !!(type.flags & 2944 /* Literal */) && type.freshType === type;
56549         }
56550         function getLiteralType(value, enumId, symbol) {
56551             // We store all literal types in a single map with keys of the form '#NNN' and '@SSS',
56552             // where NNN is the text representation of a numeric literal and SSS are the characters
56553             // of a string literal. For literal enum members we use 'EEE#NNN' and 'EEE@SSS', where
56554             // EEE is a unique id for the containing enum type.
56555             var qualifier = typeof value === "number" ? "#" : typeof value === "string" ? "@" : "n";
56556             var key = (enumId ? enumId : "") + qualifier + (typeof value === "object" ? ts.pseudoBigIntToString(value) : value);
56557             var type = literalTypes.get(key);
56558             if (!type) {
56559                 var flags = (typeof value === "number" ? 256 /* NumberLiteral */ :
56560                     typeof value === "string" ? 128 /* StringLiteral */ : 2048 /* BigIntLiteral */) |
56561                     (enumId ? 1024 /* EnumLiteral */ : 0);
56562                 literalTypes.set(key, type = createLiteralType(flags, value, symbol));
56563                 type.regularType = type;
56564             }
56565             return type;
56566         }
56567         function getTypeFromLiteralTypeNode(node) {
56568             if (node.literal.kind === 103 /* NullKeyword */) {
56569                 return nullType;
56570             }
56571             var links = getNodeLinks(node);
56572             if (!links.resolvedType) {
56573                 links.resolvedType = getRegularTypeOfLiteralType(checkExpression(node.literal));
56574             }
56575             return links.resolvedType;
56576         }
56577         function createUniqueESSymbolType(symbol) {
56578             var type = createType(8192 /* UniqueESSymbol */);
56579             type.symbol = symbol;
56580             type.escapedName = "__@" + type.symbol.escapedName + "@" + getSymbolId(type.symbol);
56581             return type;
56582         }
56583         function getESSymbolLikeTypeForNode(node) {
56584             if (ts.isValidESSymbolDeclaration(node)) {
56585                 var symbol = getSymbolOfNode(node);
56586                 var links = getSymbolLinks(symbol);
56587                 return links.uniqueESSymbolType || (links.uniqueESSymbolType = createUniqueESSymbolType(symbol));
56588             }
56589             return esSymbolType;
56590         }
56591         function getThisType(node) {
56592             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
56593             var parent = container && container.parent;
56594             if (parent && (ts.isClassLike(parent) || parent.kind === 253 /* InterfaceDeclaration */)) {
56595                 if (!ts.hasSyntacticModifier(container, 32 /* Static */) &&
56596                     (!ts.isConstructorDeclaration(container) || ts.isNodeDescendantOf(node, container.body))) {
56597                     return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent)).thisType;
56598                 }
56599             }
56600             // inside x.prototype = { ... }
56601             if (parent && ts.isObjectLiteralExpression(parent) && ts.isBinaryExpression(parent.parent) && ts.getAssignmentDeclarationKind(parent.parent) === 6 /* Prototype */) {
56602                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(parent.parent.left).parent).thisType;
56603             }
56604             // /** @return {this} */
56605             // x.prototype.m = function() { ... }
56606             var host = node.flags & 4194304 /* JSDoc */ ? ts.getHostSignatureFromJSDoc(node) : undefined;
56607             if (host && ts.isFunctionExpression(host) && ts.isBinaryExpression(host.parent) && ts.getAssignmentDeclarationKind(host.parent) === 3 /* PrototypeProperty */) {
56608                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(host.parent.left).parent).thisType;
56609             }
56610             // inside constructor function C() { ... }
56611             if (isJSConstructor(container) && ts.isNodeDescendantOf(node, container.body)) {
56612                 return getDeclaredTypeOfClassOrInterface(getSymbolOfNode(container)).thisType;
56613             }
56614             error(node, ts.Diagnostics.A_this_type_is_available_only_in_a_non_static_member_of_a_class_or_interface);
56615             return errorType;
56616         }
56617         function getTypeFromThisTypeNode(node) {
56618             var links = getNodeLinks(node);
56619             if (!links.resolvedType) {
56620                 links.resolvedType = getThisType(node);
56621             }
56622             return links.resolvedType;
56623         }
56624         function getTypeFromRestTypeNode(node) {
56625             return getTypeFromTypeNode(getArrayElementTypeNode(node.type) || node.type);
56626         }
56627         function getArrayElementTypeNode(node) {
56628             switch (node.kind) {
56629                 case 186 /* ParenthesizedType */:
56630                     return getArrayElementTypeNode(node.type);
56631                 case 179 /* TupleType */:
56632                     if (node.elements.length === 1) {
56633                         node = node.elements[0];
56634                         if (node.kind === 181 /* RestType */ || node.kind === 192 /* NamedTupleMember */ && node.dotDotDotToken) {
56635                             return getArrayElementTypeNode(node.type);
56636                         }
56637                     }
56638                     break;
56639                 case 178 /* ArrayType */:
56640                     return node.elementType;
56641             }
56642             return undefined;
56643         }
56644         function getTypeFromNamedTupleTypeNode(node) {
56645             var links = getNodeLinks(node);
56646             return links.resolvedType || (links.resolvedType =
56647                 node.dotDotDotToken ? getTypeFromRestTypeNode(node) :
56648                     node.questionToken && strictNullChecks ? getOptionalType(getTypeFromTypeNode(node.type)) :
56649                         getTypeFromTypeNode(node.type));
56650         }
56651         function getTypeFromTypeNode(node) {
56652             return getConditionalFlowTypeOfType(getTypeFromTypeNodeWorker(node), node);
56653         }
56654         function getTypeFromTypeNodeWorker(node) {
56655             switch (node.kind) {
56656                 case 128 /* AnyKeyword */:
56657                 case 303 /* JSDocAllType */:
56658                 case 304 /* JSDocUnknownType */:
56659                     return anyType;
56660                 case 152 /* UnknownKeyword */:
56661                     return unknownType;
56662                 case 147 /* StringKeyword */:
56663                     return stringType;
56664                 case 144 /* NumberKeyword */:
56665                     return numberType;
56666                 case 155 /* BigIntKeyword */:
56667                     return bigintType;
56668                 case 131 /* BooleanKeyword */:
56669                     return booleanType;
56670                 case 148 /* SymbolKeyword */:
56671                     return esSymbolType;
56672                 case 113 /* VoidKeyword */:
56673                     return voidType;
56674                 case 150 /* UndefinedKeyword */:
56675                     return undefinedType;
56676                 case 103 /* NullKeyword */:
56677                     // TODO(rbuckton): `NullKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service.
56678                     return nullType;
56679                 case 141 /* NeverKeyword */:
56680                     return neverType;
56681                 case 145 /* ObjectKeyword */:
56682                     return node.flags & 131072 /* JavaScriptFile */ && !noImplicitAny ? anyType : nonPrimitiveType;
56683                 case 136 /* IntrinsicKeyword */:
56684                     return intrinsicMarkerType;
56685                 case 187 /* ThisType */:
56686                 case 107 /* ThisKeyword */:
56687                     // TODO(rbuckton): `ThisKeyword` is no longer a `TypeNode`, but we defensively allow it here because of incorrect casts in the Language Service and because of `isPartOfTypeNode`.
56688                     return getTypeFromThisTypeNode(node);
56689                 case 191 /* LiteralType */:
56690                     return getTypeFromLiteralTypeNode(node);
56691                 case 173 /* TypeReference */:
56692                     return getTypeFromTypeReference(node);
56693                 case 172 /* TypePredicate */:
56694                     return node.assertsModifier ? voidType : booleanType;
56695                 case 223 /* ExpressionWithTypeArguments */:
56696                     return getTypeFromTypeReference(node);
56697                 case 176 /* TypeQuery */:
56698                     return getTypeFromTypeQueryNode(node);
56699                 case 178 /* ArrayType */:
56700                 case 179 /* TupleType */:
56701                     return getTypeFromArrayOrTupleTypeNode(node);
56702                 case 180 /* OptionalType */:
56703                     return getTypeFromOptionalTypeNode(node);
56704                 case 182 /* UnionType */:
56705                     return getTypeFromUnionTypeNode(node);
56706                 case 183 /* IntersectionType */:
56707                     return getTypeFromIntersectionTypeNode(node);
56708                 case 305 /* JSDocNullableType */:
56709                     return getTypeFromJSDocNullableTypeNode(node);
56710                 case 307 /* JSDocOptionalType */:
56711                     return addOptionality(getTypeFromTypeNode(node.type));
56712                 case 192 /* NamedTupleMember */:
56713                     return getTypeFromNamedTupleTypeNode(node);
56714                 case 186 /* ParenthesizedType */:
56715                 case 306 /* JSDocNonNullableType */:
56716                 case 301 /* JSDocTypeExpression */:
56717                     return getTypeFromTypeNode(node.type);
56718                 case 181 /* RestType */:
56719                     return getTypeFromRestTypeNode(node);
56720                 case 309 /* JSDocVariadicType */:
56721                     return getTypeFromJSDocVariadicType(node);
56722                 case 174 /* FunctionType */:
56723                 case 175 /* ConstructorType */:
56724                 case 177 /* TypeLiteral */:
56725                 case 312 /* JSDocTypeLiteral */:
56726                 case 308 /* JSDocFunctionType */:
56727                 case 313 /* JSDocSignature */:
56728                     return getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
56729                 case 188 /* TypeOperator */:
56730                     return getTypeFromTypeOperatorNode(node);
56731                 case 189 /* IndexedAccessType */:
56732                     return getTypeFromIndexedAccessTypeNode(node);
56733                 case 190 /* MappedType */:
56734                     return getTypeFromMappedTypeNode(node);
56735                 case 184 /* ConditionalType */:
56736                     return getTypeFromConditionalTypeNode(node);
56737                 case 185 /* InferType */:
56738                     return getTypeFromInferTypeNode(node);
56739                 case 193 /* TemplateLiteralType */:
56740                     return getTypeFromTemplateTypeNode(node);
56741                 case 195 /* ImportType */:
56742                     return getTypeFromImportTypeNode(node);
56743                 // This function assumes that an identifier, qualified name, or property access expression is a type expression
56744                 // Callers should first ensure this by calling `isPartOfTypeNode`
56745                 // TODO(rbuckton): These aren't valid TypeNodes, but we treat them as such because of `isPartOfTypeNode`, which returns `true` for things that aren't `TypeNode`s.
56746                 case 78 /* Identifier */:
56747                 case 157 /* QualifiedName */:
56748                 case 201 /* PropertyAccessExpression */:
56749                     var symbol = getSymbolAtLocation(node);
56750                     return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
56751                 default:
56752                     return errorType;
56753             }
56754         }
56755         function instantiateList(items, mapper, instantiator) {
56756             if (items && items.length) {
56757                 for (var i = 0; i < items.length; i++) {
56758                     var item = items[i];
56759                     var mapped = instantiator(item, mapper);
56760                     if (item !== mapped) {
56761                         var result = i === 0 ? [] : items.slice(0, i);
56762                         result.push(mapped);
56763                         for (i++; i < items.length; i++) {
56764                             result.push(instantiator(items[i], mapper));
56765                         }
56766                         return result;
56767                     }
56768                 }
56769             }
56770             return items;
56771         }
56772         function instantiateTypes(types, mapper) {
56773             return instantiateList(types, mapper, instantiateType);
56774         }
56775         function instantiateSignatures(signatures, mapper) {
56776             return instantiateList(signatures, mapper, instantiateSignature);
56777         }
56778         function createTypeMapper(sources, targets) {
56779             return sources.length === 1 ? makeUnaryTypeMapper(sources[0], targets ? targets[0] : anyType) : makeArrayTypeMapper(sources, targets);
56780         }
56781         function getMappedType(type, mapper) {
56782             switch (mapper.kind) {
56783                 case 0 /* Simple */:
56784                     return type === mapper.source ? mapper.target : type;
56785                 case 1 /* Array */:
56786                     var sources = mapper.sources;
56787                     var targets = mapper.targets;
56788                     for (var i = 0; i < sources.length; i++) {
56789                         if (type === sources[i]) {
56790                             return targets ? targets[i] : anyType;
56791                         }
56792                     }
56793                     return type;
56794                 case 2 /* Function */:
56795                     return mapper.func(type);
56796                 case 3 /* Composite */:
56797                 case 4 /* Merged */:
56798                     var t1 = getMappedType(type, mapper.mapper1);
56799                     return t1 !== type && mapper.kind === 3 /* Composite */ ? instantiateType(t1, mapper.mapper2) : getMappedType(t1, mapper.mapper2);
56800             }
56801         }
56802         function makeUnaryTypeMapper(source, target) {
56803             return { kind: 0 /* Simple */, source: source, target: target };
56804         }
56805         function makeArrayTypeMapper(sources, targets) {
56806             return { kind: 1 /* Array */, sources: sources, targets: targets };
56807         }
56808         function makeFunctionTypeMapper(func) {
56809             return { kind: 2 /* Function */, func: func };
56810         }
56811         function makeCompositeTypeMapper(kind, mapper1, mapper2) {
56812             return { kind: kind, mapper1: mapper1, mapper2: mapper2 };
56813         }
56814         function createTypeEraser(sources) {
56815             return createTypeMapper(sources, /*targets*/ undefined);
56816         }
56817         /**
56818          * Maps forward-references to later types parameters to the empty object type.
56819          * This is used during inference when instantiating type parameter defaults.
56820          */
56821         function createBackreferenceMapper(context, index) {
56822             return makeFunctionTypeMapper(function (t) { return ts.findIndex(context.inferences, function (info) { return info.typeParameter === t; }) >= index ? unknownType : t; });
56823         }
56824         function combineTypeMappers(mapper1, mapper2) {
56825             return mapper1 ? makeCompositeTypeMapper(3 /* Composite */, mapper1, mapper2) : mapper2;
56826         }
56827         function mergeTypeMappers(mapper1, mapper2) {
56828             return mapper1 ? makeCompositeTypeMapper(4 /* Merged */, mapper1, mapper2) : mapper2;
56829         }
56830         function prependTypeMapping(source, target, mapper) {
56831             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, makeUnaryTypeMapper(source, target), mapper);
56832         }
56833         function appendTypeMapping(mapper, source, target) {
56834             return !mapper ? makeUnaryTypeMapper(source, target) : makeCompositeTypeMapper(4 /* Merged */, mapper, makeUnaryTypeMapper(source, target));
56835         }
56836         function getRestrictiveTypeParameter(tp) {
56837             return tp.constraint === unknownType ? tp : tp.restrictiveInstantiation || (tp.restrictiveInstantiation = createTypeParameter(tp.symbol),
56838                 tp.restrictiveInstantiation.constraint = unknownType,
56839                 tp.restrictiveInstantiation);
56840         }
56841         function cloneTypeParameter(typeParameter) {
56842             var result = createTypeParameter(typeParameter.symbol);
56843             result.target = typeParameter;
56844             return result;
56845         }
56846         function instantiateTypePredicate(predicate, mapper) {
56847             return createTypePredicate(predicate.kind, predicate.parameterName, predicate.parameterIndex, instantiateType(predicate.type, mapper));
56848         }
56849         function instantiateSignature(signature, mapper, eraseTypeParameters) {
56850             var freshTypeParameters;
56851             if (signature.typeParameters && !eraseTypeParameters) {
56852                 // First create a fresh set of type parameters, then include a mapping from the old to the
56853                 // new type parameters in the mapper function. Finally store this mapper in the new type
56854                 // parameters such that we can use it when instantiating constraints.
56855                 freshTypeParameters = ts.map(signature.typeParameters, cloneTypeParameter);
56856                 mapper = combineTypeMappers(createTypeMapper(signature.typeParameters, freshTypeParameters), mapper);
56857                 for (var _i = 0, freshTypeParameters_1 = freshTypeParameters; _i < freshTypeParameters_1.length; _i++) {
56858                     var tp = freshTypeParameters_1[_i];
56859                     tp.mapper = mapper;
56860                 }
56861             }
56862             // Don't compute resolvedReturnType and resolvedTypePredicate now,
56863             // because using `mapper` now could trigger inferences to become fixed. (See `createInferenceContext`.)
56864             // See GH#17600.
56865             var result = createSignature(signature.declaration, freshTypeParameters, signature.thisParameter && instantiateSymbol(signature.thisParameter, mapper), instantiateList(signature.parameters, mapper, instantiateSymbol), 
56866             /*resolvedReturnType*/ undefined, 
56867             /*resolvedTypePredicate*/ undefined, signature.minArgumentCount, signature.flags & 19 /* PropagatingFlags */);
56868             result.target = signature;
56869             result.mapper = mapper;
56870             return result;
56871         }
56872         function instantiateSymbol(symbol, mapper) {
56873             var links = getSymbolLinks(symbol);
56874             if (links.type && !couldContainTypeVariables(links.type)) {
56875                 // If the type of the symbol is already resolved, and if that type could not possibly
56876                 // be affected by instantiation, simply return the symbol itself.
56877                 return symbol;
56878             }
56879             if (ts.getCheckFlags(symbol) & 1 /* Instantiated */) {
56880                 // If symbol being instantiated is itself a instantiation, fetch the original target and combine the
56881                 // type mappers. This ensures that original type identities are properly preserved and that aliases
56882                 // always reference a non-aliases.
56883                 symbol = links.target;
56884                 mapper = combineTypeMappers(links.mapper, mapper);
56885             }
56886             // Keep the flags from the symbol we're instantiating.  Mark that is instantiated, and
56887             // also transient so that we can just store data on it directly.
56888             var result = createSymbol(symbol.flags, symbol.escapedName, 1 /* Instantiated */ | ts.getCheckFlags(symbol) & (8 /* Readonly */ | 4096 /* Late */ | 16384 /* OptionalParameter */ | 32768 /* RestParameter */));
56889             result.declarations = symbol.declarations;
56890             result.parent = symbol.parent;
56891             result.target = symbol;
56892             result.mapper = mapper;
56893             if (symbol.valueDeclaration) {
56894                 result.valueDeclaration = symbol.valueDeclaration;
56895             }
56896             if (links.nameType) {
56897                 result.nameType = links.nameType;
56898             }
56899             return result;
56900         }
56901         function getObjectTypeInstantiation(type, mapper) {
56902             var declaration = type.objectFlags & 4 /* Reference */ ? type.node : type.symbol.declarations[0];
56903             var links = getNodeLinks(declaration);
56904             var target = type.objectFlags & 4 /* Reference */ ? links.resolvedType :
56905                 type.objectFlags & 64 /* Instantiated */ ? type.target : type;
56906             var typeParameters = links.outerTypeParameters;
56907             if (!typeParameters) {
56908                 // The first time an anonymous type is instantiated we compute and store a list of the type
56909                 // parameters that are in scope (and therefore potentially referenced). For type literals that
56910                 // aren't the right hand side of a generic type alias declaration we optimize by reducing the
56911                 // set of type parameters to those that are possibly referenced in the literal.
56912                 var outerTypeParameters = getOuterTypeParameters(declaration, /*includeThisTypes*/ true);
56913                 if (isJSConstructor(declaration)) {
56914                     var templateTagParameters = getTypeParametersFromDeclaration(declaration);
56915                     outerTypeParameters = ts.addRange(outerTypeParameters, templateTagParameters);
56916                 }
56917                 typeParameters = outerTypeParameters || ts.emptyArray;
56918                 typeParameters = (target.objectFlags & 4 /* Reference */ || target.symbol.flags & 2048 /* TypeLiteral */) && !target.aliasTypeArguments ?
56919                     ts.filter(typeParameters, function (tp) { return isTypeParameterPossiblyReferenced(tp, declaration); }) :
56920                     typeParameters;
56921                 links.outerTypeParameters = typeParameters;
56922             }
56923             if (typeParameters.length) {
56924                 // We are instantiating an anonymous type that has one or more type parameters in scope. Apply the
56925                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
56926                 // instantiation cache key from the type IDs of the type arguments.
56927                 var combinedMapper_1 = combineTypeMappers(type.mapper, mapper);
56928                 var typeArguments = ts.map(typeParameters, function (t) { return getMappedType(t, combinedMapper_1); });
56929                 var id = getTypeListId(typeArguments);
56930                 if (!target.instantiations) {
56931                     target.instantiations = new ts.Map();
56932                     target.instantiations.set(getTypeListId(typeParameters), target);
56933                 }
56934                 var result = target.instantiations.get(id);
56935                 if (!result) {
56936                     var newMapper = createTypeMapper(typeParameters, typeArguments);
56937                     result = target.objectFlags & 4 /* Reference */ ? createDeferredTypeReference(type.target, type.node, newMapper) :
56938                         target.objectFlags & 32 /* Mapped */ ? instantiateMappedType(target, newMapper) :
56939                             instantiateAnonymousType(target, newMapper);
56940                     target.instantiations.set(id, result);
56941                 }
56942                 return result;
56943             }
56944             return type;
56945         }
56946         function maybeTypeParameterReference(node) {
56947             return !(node.kind === 157 /* QualifiedName */ ||
56948                 node.parent.kind === 173 /* TypeReference */ && node.parent.typeArguments && node === node.parent.typeName ||
56949                 node.parent.kind === 195 /* ImportType */ && node.parent.typeArguments && node === node.parent.qualifier);
56950         }
56951         function isTypeParameterPossiblyReferenced(tp, node) {
56952             // If the type parameter doesn't have exactly one declaration, if there are invening statement blocks
56953             // between the node and the type parameter declaration, if the node contains actual references to the
56954             // type parameter, or if the node contains type queries, we consider the type parameter possibly referenced.
56955             if (tp.symbol && tp.symbol.declarations && tp.symbol.declarations.length === 1) {
56956                 var container = tp.symbol.declarations[0].parent;
56957                 for (var n = node; n !== container; n = n.parent) {
56958                     if (!n || n.kind === 230 /* Block */ || n.kind === 184 /* ConditionalType */ && ts.forEachChild(n.extendsType, containsReference)) {
56959                         return true;
56960                     }
56961                 }
56962                 return !!ts.forEachChild(node, containsReference);
56963             }
56964             return true;
56965             function containsReference(node) {
56966                 switch (node.kind) {
56967                     case 187 /* ThisType */:
56968                         return !!tp.isThisType;
56969                     case 78 /* Identifier */:
56970                         return !tp.isThisType && ts.isPartOfTypeNode(node) && maybeTypeParameterReference(node) &&
56971                             getTypeFromTypeNodeWorker(node) === tp; // use worker because we're looking for === equality
56972                     case 176 /* TypeQuery */:
56973                         return true;
56974                 }
56975                 return !!ts.forEachChild(node, containsReference);
56976             }
56977         }
56978         function getHomomorphicTypeVariable(type) {
56979             var constraintType = getConstraintTypeFromMappedType(type);
56980             if (constraintType.flags & 4194304 /* Index */) {
56981                 var typeVariable = getActualTypeVariable(constraintType.type);
56982                 if (typeVariable.flags & 262144 /* TypeParameter */) {
56983                     return typeVariable;
56984                 }
56985             }
56986             return undefined;
56987         }
56988         function instantiateMappedType(type, mapper) {
56989             // For a homomorphic mapped type { [P in keyof T]: X }, where T is some type variable, the mapping
56990             // operation depends on T as follows:
56991             // * If T is a primitive type no mapping is performed and the result is simply T.
56992             // * If T is a union type we distribute the mapped type over the union.
56993             // * If T is an array we map to an array where the element type has been transformed.
56994             // * If T is a tuple we map to a tuple where the element types have been transformed.
56995             // * Otherwise we map to an object type where the type of each property has been transformed.
56996             // For example, when T is instantiated to a union type A | B, we produce { [P in keyof A]: X } |
56997             // { [P in keyof B]: X }, and when when T is instantiated to a union type A | undefined, we produce
56998             // { [P in keyof A]: X } | undefined.
56999             var typeVariable = getHomomorphicTypeVariable(type);
57000             if (typeVariable) {
57001                 var mappedTypeVariable = instantiateType(typeVariable, mapper);
57002                 if (typeVariable !== mappedTypeVariable) {
57003                     return mapType(getReducedType(mappedTypeVariable), function (t) {
57004                         if (t.flags & (3 /* AnyOrUnknown */ | 58982400 /* InstantiableNonPrimitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && t !== wildcardType && t !== errorType) {
57005                             if (!type.declaration.nameType) {
57006                                 if (isArrayType(t)) {
57007                                     return instantiateMappedArrayType(t, type, prependTypeMapping(typeVariable, t, mapper));
57008                                 }
57009                                 if (isGenericTupleType(t)) {
57010                                     return instantiateMappedGenericTupleType(t, type, typeVariable, mapper);
57011                                 }
57012                                 if (isTupleType(t)) {
57013                                     return instantiateMappedTupleType(t, type, prependTypeMapping(typeVariable, t, mapper));
57014                                 }
57015                             }
57016                             return instantiateAnonymousType(type, prependTypeMapping(typeVariable, t, mapper));
57017                         }
57018                         return t;
57019                     });
57020                 }
57021             }
57022             return instantiateAnonymousType(type, mapper);
57023         }
57024         function getModifiedReadonlyState(state, modifiers) {
57025             return modifiers & 1 /* IncludeReadonly */ ? true : modifiers & 2 /* ExcludeReadonly */ ? false : state;
57026         }
57027         function instantiateMappedGenericTupleType(tupleType, mappedType, typeVariable, mapper) {
57028             // When a tuple type is generic (i.e. when it contains variadic elements), we want to eagerly map the
57029             // non-generic elements and defer mapping the generic elements. In order to facilitate this, we transform
57030             // M<[A, B?, ...T, ...C[]] into [...M<[A]>, ...M<[B?]>, ...M<T>, ...M<C[]>] and then rely on tuple type
57031             // normalization to resolve the non-generic parts of the resulting tuple.
57032             var elementFlags = tupleType.target.elementFlags;
57033             var elementTypes = ts.map(getTypeArguments(tupleType), function (t, i) {
57034                 var singleton = elementFlags[i] & 8 /* Variadic */ ? t :
57035                     elementFlags[i] & 4 /* Rest */ ? createArrayType(t) :
57036                         createTupleType([t], [elementFlags[i]]);
57037                 // The singleton is never a generic tuple type, so it is safe to recurse here.
57038                 return instantiateMappedType(mappedType, prependTypeMapping(typeVariable, singleton, mapper));
57039             });
57040             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, getMappedTypeModifiers(mappedType));
57041             return createTupleType(elementTypes, ts.map(elementTypes, function (_) { return 8 /* Variadic */; }), newReadonly);
57042         }
57043         function instantiateMappedArrayType(arrayType, mappedType, mapper) {
57044             var elementType = instantiateMappedTypeTemplate(mappedType, numberType, /*isOptional*/ true, mapper);
57045             return elementType === errorType ? errorType :
57046                 createArrayType(elementType, getModifiedReadonlyState(isReadonlyArrayType(arrayType), getMappedTypeModifiers(mappedType)));
57047         }
57048         function instantiateMappedTupleType(tupleType, mappedType, mapper) {
57049             var elementFlags = tupleType.target.elementFlags;
57050             var elementTypes = ts.map(getTypeArguments(tupleType), function (_, i) {
57051                 return instantiateMappedTypeTemplate(mappedType, getLiteralType("" + i), !!(elementFlags[i] & 2 /* Optional */), mapper);
57052             });
57053             var modifiers = getMappedTypeModifiers(mappedType);
57054             var newTupleModifiers = modifiers & 4 /* IncludeOptional */ ? ts.map(elementFlags, function (f) { return f & 1 /* Required */ ? 2 /* Optional */ : f; }) :
57055                 modifiers & 8 /* ExcludeOptional */ ? ts.map(elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
57056                     elementFlags;
57057             var newReadonly = getModifiedReadonlyState(tupleType.target.readonly, modifiers);
57058             return ts.contains(elementTypes, errorType) ? errorType :
57059                 createTupleType(elementTypes, newTupleModifiers, newReadonly, tupleType.target.labeledElementDeclarations);
57060         }
57061         function instantiateMappedTypeTemplate(type, key, isOptional, mapper) {
57062             var templateMapper = appendTypeMapping(mapper, getTypeParameterFromMappedType(type), key);
57063             var propType = instantiateType(getTemplateTypeFromMappedType(type.target || type), templateMapper);
57064             var modifiers = getMappedTypeModifiers(type);
57065             return strictNullChecks && modifiers & 4 /* IncludeOptional */ && !maybeTypeOfKind(propType, 32768 /* Undefined */ | 16384 /* Void */) ? getOptionalType(propType) :
57066                 strictNullChecks && modifiers & 8 /* ExcludeOptional */ && isOptional ? getTypeWithFacts(propType, 524288 /* NEUndefined */) :
57067                     propType;
57068         }
57069         function instantiateAnonymousType(type, mapper) {
57070             var result = createObjectType(type.objectFlags | 64 /* Instantiated */, type.symbol);
57071             if (type.objectFlags & 32 /* Mapped */) {
57072                 result.declaration = type.declaration;
57073                 // C.f. instantiateSignature
57074                 var origTypeParameter = getTypeParameterFromMappedType(type);
57075                 var freshTypeParameter = cloneTypeParameter(origTypeParameter);
57076                 result.typeParameter = freshTypeParameter;
57077                 mapper = combineTypeMappers(makeUnaryTypeMapper(origTypeParameter, freshTypeParameter), mapper);
57078                 freshTypeParameter.mapper = mapper;
57079             }
57080             result.target = type;
57081             result.mapper = mapper;
57082             result.aliasSymbol = type.aliasSymbol;
57083             result.aliasTypeArguments = instantiateTypes(type.aliasTypeArguments, mapper);
57084             return result;
57085         }
57086         function getConditionalTypeInstantiation(type, mapper) {
57087             var root = type.root;
57088             if (root.outerTypeParameters) {
57089                 // We are instantiating a conditional type that has one or more type parameters in scope. Apply the
57090                 // mapper to the type parameters to produce the effective list of type arguments, and compute the
57091                 // instantiation cache key from the type IDs of the type arguments.
57092                 var typeArguments = ts.map(root.outerTypeParameters, function (t) { return getMappedType(t, mapper); });
57093                 var id = getTypeListId(typeArguments);
57094                 var result = root.instantiations.get(id);
57095                 if (!result) {
57096                     var newMapper = createTypeMapper(root.outerTypeParameters, typeArguments);
57097                     result = instantiateConditionalType(root, newMapper);
57098                     root.instantiations.set(id, result);
57099                 }
57100                 return result;
57101             }
57102             return type;
57103         }
57104         function instantiateConditionalType(root, mapper) {
57105             // Check if we have a conditional type where the check type is a naked type parameter. If so,
57106             // the conditional type is distributive over union types and when T is instantiated to a union
57107             // type A | B, we produce (A extends U ? X : Y) | (B extends U ? X : Y).
57108             if (root.isDistributive) {
57109                 var checkType_1 = root.checkType;
57110                 var instantiatedType = getMappedType(checkType_1, mapper);
57111                 if (checkType_1 !== instantiatedType && instantiatedType.flags & (1048576 /* Union */ | 131072 /* Never */)) {
57112                     return mapType(instantiatedType, function (t) { return getConditionalType(root, prependTypeMapping(checkType_1, t, mapper)); });
57113                 }
57114             }
57115             return getConditionalType(root, mapper);
57116         }
57117         function instantiateType(type, mapper) {
57118             if (!(type && mapper && couldContainTypeVariables(type))) {
57119                 return type;
57120             }
57121             if (instantiationDepth === 50 || instantiationCount >= 5000000) {
57122                 // We have reached 50 recursive type instantiations and there is a very high likelyhood we're dealing
57123                 // with a combination of infinite generic types that perpetually generate new type identities. We stop
57124                 // the recursion here by yielding the error type.
57125                 ts.tracing.instant("check" /* Check */, "instantiateType_DepthLimit", { typeId: type.id, instantiationDepth: instantiationDepth, instantiationCount: instantiationCount });
57126                 error(currentNode, ts.Diagnostics.Type_instantiation_is_excessively_deep_and_possibly_infinite);
57127                 return errorType;
57128             }
57129             totalInstantiationCount++;
57130             instantiationCount++;
57131             instantiationDepth++;
57132             var result = instantiateTypeWorker(type, mapper);
57133             instantiationDepth--;
57134             return result;
57135         }
57136         function instantiateTypeWorker(type, mapper) {
57137             var flags = type.flags;
57138             if (flags & 262144 /* TypeParameter */) {
57139                 return getMappedType(type, mapper);
57140             }
57141             if (flags & 524288 /* Object */) {
57142                 var objectFlags = type.objectFlags;
57143                 if (objectFlags & (4 /* Reference */ | 16 /* Anonymous */ | 32 /* Mapped */)) {
57144                     if (objectFlags & 4 /* Reference */ && !(type.node)) {
57145                         var resolvedTypeArguments = type.resolvedTypeArguments;
57146                         var newTypeArguments = instantiateTypes(resolvedTypeArguments, mapper);
57147                         return newTypeArguments !== resolvedTypeArguments ? createNormalizedTypeReference(type.target, newTypeArguments) : type;
57148                     }
57149                     return getObjectTypeInstantiation(type, mapper);
57150                 }
57151                 return type;
57152             }
57153             if (flags & 3145728 /* UnionOrIntersection */) {
57154                 var types = type.types;
57155                 var newTypes = instantiateTypes(types, mapper);
57156                 return newTypes === types ? type :
57157                     flags & 2097152 /* Intersection */ ?
57158                         getIntersectionType(newTypes, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper)) :
57159                         getUnionType(newTypes, 1 /* Literal */, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
57160             }
57161             if (flags & 4194304 /* Index */) {
57162                 return getIndexType(instantiateType(type.type, mapper));
57163             }
57164             if (flags & 134217728 /* TemplateLiteral */) {
57165                 return getTemplateLiteralType(type.texts, instantiateTypes(type.types, mapper));
57166             }
57167             if (flags & 268435456 /* StringMapping */) {
57168                 return getStringMappingType(type.symbol, instantiateType(type.type, mapper));
57169             }
57170             if (flags & 8388608 /* IndexedAccess */) {
57171                 return getIndexedAccessType(instantiateType(type.objectType, mapper), instantiateType(type.indexType, mapper), type.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, type.aliasSymbol, instantiateTypes(type.aliasTypeArguments, mapper));
57172             }
57173             if (flags & 16777216 /* Conditional */) {
57174                 return getConditionalTypeInstantiation(type, combineTypeMappers(type.mapper, mapper));
57175             }
57176             if (flags & 33554432 /* Substitution */) {
57177                 var maybeVariable = instantiateType(type.baseType, mapper);
57178                 if (maybeVariable.flags & 8650752 /* TypeVariable */) {
57179                     return getSubstitutionType(maybeVariable, instantiateType(type.substitute, mapper));
57180                 }
57181                 else {
57182                     var sub = instantiateType(type.substitute, mapper);
57183                     if (sub.flags & 3 /* AnyOrUnknown */ || isTypeAssignableTo(getRestrictiveInstantiation(maybeVariable), getRestrictiveInstantiation(sub))) {
57184                         return maybeVariable;
57185                     }
57186                     return sub;
57187                 }
57188             }
57189             return type;
57190         }
57191         function getPermissiveInstantiation(type) {
57192             return type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */) ? type :
57193                 type.permissiveInstantiation || (type.permissiveInstantiation = instantiateType(type, permissiveMapper));
57194         }
57195         function getRestrictiveInstantiation(type) {
57196             if (type.flags & (131068 /* Primitive */ | 3 /* AnyOrUnknown */ | 131072 /* Never */)) {
57197                 return type;
57198             }
57199             if (type.restrictiveInstantiation) {
57200                 return type.restrictiveInstantiation;
57201             }
57202             type.restrictiveInstantiation = instantiateType(type, restrictiveMapper);
57203             // We set the following so we don't attempt to set the restrictive instance of a restrictive instance
57204             // which is redundant - we'll produce new type identities, but all type params have already been mapped.
57205             // This also gives us a way to detect restrictive instances upon comparisons and _disable_ the "distributeive constraint"
57206             // assignability check for them, which is distinctly unsafe, as once you have a restrctive instance, all the type parameters
57207             // are constrained to `unknown` and produce tons of false positives/negatives!
57208             type.restrictiveInstantiation.restrictiveInstantiation = type.restrictiveInstantiation;
57209             return type.restrictiveInstantiation;
57210         }
57211         function instantiateIndexInfo(info, mapper) {
57212             return info && createIndexInfo(instantiateType(info.type, mapper), info.isReadonly, info.declaration);
57213         }
57214         // Returns true if the given expression contains (at any level of nesting) a function or arrow expression
57215         // that is subject to contextual typing.
57216         function isContextSensitive(node) {
57217             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
57218             switch (node.kind) {
57219                 case 208 /* FunctionExpression */:
57220                 case 209 /* ArrowFunction */:
57221                 case 165 /* MethodDeclaration */:
57222                 case 251 /* FunctionDeclaration */: // Function declarations can have context when annotated with a jsdoc @type
57223                     return isContextSensitiveFunctionLikeDeclaration(node);
57224                 case 200 /* ObjectLiteralExpression */:
57225                     return ts.some(node.properties, isContextSensitive);
57226                 case 199 /* ArrayLiteralExpression */:
57227                     return ts.some(node.elements, isContextSensitive);
57228                 case 217 /* ConditionalExpression */:
57229                     return isContextSensitive(node.whenTrue) ||
57230                         isContextSensitive(node.whenFalse);
57231                 case 216 /* BinaryExpression */:
57232                     return (node.operatorToken.kind === 56 /* BarBarToken */ || node.operatorToken.kind === 60 /* QuestionQuestionToken */) &&
57233                         (isContextSensitive(node.left) || isContextSensitive(node.right));
57234                 case 288 /* PropertyAssignment */:
57235                     return isContextSensitive(node.initializer);
57236                 case 207 /* ParenthesizedExpression */:
57237                     return isContextSensitive(node.expression);
57238                 case 281 /* JsxAttributes */:
57239                     return ts.some(node.properties, isContextSensitive) || ts.isJsxOpeningElement(node.parent) && ts.some(node.parent.parent.children, isContextSensitive);
57240                 case 280 /* JsxAttribute */: {
57241                     // If there is no initializer, JSX attribute has a boolean value of true which is not context sensitive.
57242                     var initializer = node.initializer;
57243                     return !!initializer && isContextSensitive(initializer);
57244                 }
57245                 case 283 /* JsxExpression */: {
57246                     // It is possible to that node.expression is undefined (e.g <div x={} />)
57247                     var expression = node.expression;
57248                     return !!expression && isContextSensitive(expression);
57249                 }
57250             }
57251             return false;
57252         }
57253         function isContextSensitiveFunctionLikeDeclaration(node) {
57254             return (!ts.isFunctionDeclaration(node) || ts.isInJSFile(node) && !!getTypeForDeclarationFromJSDocComment(node)) &&
57255                 (hasContextSensitiveParameters(node) || hasContextSensitiveReturnExpression(node));
57256         }
57257         function hasContextSensitiveParameters(node) {
57258             // Functions with type parameters are not context sensitive.
57259             if (!node.typeParameters) {
57260                 // Functions with any parameters that lack type annotations are context sensitive.
57261                 if (ts.some(node.parameters, function (p) { return !ts.getEffectiveTypeAnnotationNode(p); })) {
57262                     return true;
57263                 }
57264                 if (node.kind !== 209 /* ArrowFunction */) {
57265                     // If the first parameter is not an explicit 'this' parameter, then the function has
57266                     // an implicit 'this' parameter which is subject to contextual typing.
57267                     var parameter = ts.firstOrUndefined(node.parameters);
57268                     if (!(parameter && ts.parameterIsThisKeyword(parameter))) {
57269                         return true;
57270                     }
57271                 }
57272             }
57273             return false;
57274         }
57275         function hasContextSensitiveReturnExpression(node) {
57276             // TODO(anhans): A block should be context-sensitive if it has a context-sensitive return value.
57277             return !node.typeParameters && !ts.getEffectiveReturnTypeNode(node) && !!node.body && node.body.kind !== 230 /* Block */ && isContextSensitive(node.body);
57278         }
57279         function isContextSensitiveFunctionOrObjectLiteralMethod(func) {
57280             return (ts.isInJSFile(func) && ts.isFunctionDeclaration(func) || isFunctionExpressionOrArrowFunction(func) || ts.isObjectLiteralMethod(func)) &&
57281                 isContextSensitiveFunctionLikeDeclaration(func);
57282         }
57283         function getTypeWithoutSignatures(type) {
57284             if (type.flags & 524288 /* Object */) {
57285                 var resolved = resolveStructuredTypeMembers(type);
57286                 if (resolved.constructSignatures.length || resolved.callSignatures.length) {
57287                     var result = createObjectType(16 /* Anonymous */, type.symbol);
57288                     result.members = resolved.members;
57289                     result.properties = resolved.properties;
57290                     result.callSignatures = ts.emptyArray;
57291                     result.constructSignatures = ts.emptyArray;
57292                     return result;
57293                 }
57294             }
57295             else if (type.flags & 2097152 /* Intersection */) {
57296                 return getIntersectionType(ts.map(type.types, getTypeWithoutSignatures));
57297             }
57298             return type;
57299         }
57300         // TYPE CHECKING
57301         function isTypeIdenticalTo(source, target) {
57302             return isTypeRelatedTo(source, target, identityRelation);
57303         }
57304         function compareTypesIdentical(source, target) {
57305             return isTypeRelatedTo(source, target, identityRelation) ? -1 /* True */ : 0 /* False */;
57306         }
57307         function compareTypesAssignable(source, target) {
57308             return isTypeRelatedTo(source, target, assignableRelation) ? -1 /* True */ : 0 /* False */;
57309         }
57310         function compareTypesSubtypeOf(source, target) {
57311             return isTypeRelatedTo(source, target, subtypeRelation) ? -1 /* True */ : 0 /* False */;
57312         }
57313         function isTypeSubtypeOf(source, target) {
57314             return isTypeRelatedTo(source, target, subtypeRelation);
57315         }
57316         function isTypeAssignableTo(source, target) {
57317             return isTypeRelatedTo(source, target, assignableRelation);
57318         }
57319         // An object type S is considered to be derived from an object type T if
57320         // S is a union type and every constituent of S is derived from T,
57321         // T is a union type and S is derived from at least one constituent of T, or
57322         // S is a type variable with a base constraint that is derived from T,
57323         // T is one of the global types Object and Function and S is a subtype of T, or
57324         // T occurs directly or indirectly in an 'extends' clause of S.
57325         // Note that this check ignores type parameters and only considers the
57326         // inheritance hierarchy.
57327         function isTypeDerivedFrom(source, target) {
57328             return source.flags & 1048576 /* Union */ ? ts.every(source.types, function (t) { return isTypeDerivedFrom(t, target); }) :
57329                 target.flags & 1048576 /* Union */ ? ts.some(target.types, function (t) { return isTypeDerivedFrom(source, t); }) :
57330                     source.flags & 58982400 /* InstantiableNonPrimitive */ ? isTypeDerivedFrom(getBaseConstraintOfType(source) || unknownType, target) :
57331                         target === globalObjectType ? !!(source.flags & (524288 /* Object */ | 67108864 /* NonPrimitive */)) :
57332                             target === globalFunctionType ? !!(source.flags & 524288 /* Object */) && isFunctionObjectType(source) :
57333                                 hasBaseType(source, getTargetType(target)) || (isArrayType(target) && !isReadonlyArrayType(target) && isTypeDerivedFrom(source, globalReadonlyArrayType));
57334         }
57335         /**
57336          * This is *not* a bi-directional relationship.
57337          * If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
57338          *
57339          * 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.
57340          * It is used to check following cases:
57341          *   - the types of the left and right sides of equality/inequality operators (`===`, `!==`, `==`, `!=`).
57342          *   - the types of `case` clause expressions and their respective `switch` expressions.
57343          *   - the type of an expression in a type assertion with the type being asserted.
57344          */
57345         function isTypeComparableTo(source, target) {
57346             return isTypeRelatedTo(source, target, comparableRelation);
57347         }
57348         function areTypesComparable(type1, type2) {
57349             return isTypeComparableTo(type1, type2) || isTypeComparableTo(type2, type1);
57350         }
57351         function checkTypeAssignableTo(source, target, errorNode, headMessage, containingMessageChain, errorOutputObject) {
57352             return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain, errorOutputObject);
57353         }
57354         /**
57355          * Like `checkTypeAssignableTo`, but if it would issue an error, instead performs structural comparisons of the types using the given expression node to
57356          * attempt to issue more specific errors on, for example, specific object literal properties or tuple members.
57357          */
57358         function checkTypeAssignableToAndOptionallyElaborate(source, target, errorNode, expr, headMessage, containingMessageChain) {
57359             return checkTypeRelatedToAndOptionallyElaborate(source, target, assignableRelation, errorNode, expr, headMessage, containingMessageChain, /*errorOutputContainer*/ undefined);
57360         }
57361         function checkTypeRelatedToAndOptionallyElaborate(source, target, relation, errorNode, expr, headMessage, containingMessageChain, errorOutputContainer) {
57362             if (isTypeRelatedTo(source, target, relation))
57363                 return true;
57364             if (!errorNode || !elaborateError(expr, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
57365                 return checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer);
57366             }
57367             return false;
57368         }
57369         function isOrHasGenericConditional(type) {
57370             return !!(type.flags & 16777216 /* Conditional */ || (type.flags & 2097152 /* Intersection */ && ts.some(type.types, isOrHasGenericConditional)));
57371         }
57372         function elaborateError(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
57373             if (!node || isOrHasGenericConditional(target))
57374                 return false;
57375             if (!checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined)
57376                 && elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer)) {
57377                 return true;
57378             }
57379             switch (node.kind) {
57380                 case 283 /* JsxExpression */:
57381                 case 207 /* ParenthesizedExpression */:
57382                     return elaborateError(node.expression, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
57383                 case 216 /* BinaryExpression */:
57384                     switch (node.operatorToken.kind) {
57385                         case 62 /* EqualsToken */:
57386                         case 27 /* CommaToken */:
57387                             return elaborateError(node.right, source, target, relation, headMessage, containingMessageChain, errorOutputContainer);
57388                     }
57389                     break;
57390                 case 200 /* ObjectLiteralExpression */:
57391                     return elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
57392                 case 199 /* ArrayLiteralExpression */:
57393                     return elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer);
57394                 case 281 /* JsxAttributes */:
57395                     return elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer);
57396                 case 209 /* ArrowFunction */:
57397                     return elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer);
57398             }
57399             return false;
57400         }
57401         function elaborateDidYouMeanToCallOrConstruct(node, source, target, relation, headMessage, containingMessageChain, errorOutputContainer) {
57402             var callSignatures = getSignaturesOfType(source, 0 /* Call */);
57403             var constructSignatures = getSignaturesOfType(source, 1 /* Construct */);
57404             for (var _i = 0, _a = [constructSignatures, callSignatures]; _i < _a.length; _i++) {
57405                 var signatures = _a[_i];
57406                 if (ts.some(signatures, function (s) {
57407                     var returnType = getReturnTypeOfSignature(s);
57408                     return !(returnType.flags & (1 /* Any */ | 131072 /* Never */)) && checkTypeRelatedTo(returnType, target, relation, /*errorNode*/ undefined);
57409                 })) {
57410                     var resultObj = errorOutputContainer || {};
57411                     checkTypeAssignableTo(source, target, node, headMessage, containingMessageChain, resultObj);
57412                     var diagnostic = resultObj.errors[resultObj.errors.length - 1];
57413                     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));
57414                     return true;
57415                 }
57416             }
57417             return false;
57418         }
57419         function elaborateArrowFunction(node, source, target, relation, containingMessageChain, errorOutputContainer) {
57420             // Don't elaborate blocks
57421             if (ts.isBlock(node.body)) {
57422                 return false;
57423             }
57424             // Or functions with annotated parameter types
57425             if (ts.some(node.parameters, ts.hasType)) {
57426                 return false;
57427             }
57428             var sourceSig = getSingleCallSignature(source);
57429             if (!sourceSig) {
57430                 return false;
57431             }
57432             var targetSignatures = getSignaturesOfType(target, 0 /* Call */);
57433             if (!ts.length(targetSignatures)) {
57434                 return false;
57435             }
57436             var returnExpression = node.body;
57437             var sourceReturn = getReturnTypeOfSignature(sourceSig);
57438             var targetReturn = getUnionType(ts.map(targetSignatures, getReturnTypeOfSignature));
57439             if (!checkTypeRelatedTo(sourceReturn, targetReturn, relation, /*errorNode*/ undefined)) {
57440                 var elaborated = returnExpression && elaborateError(returnExpression, sourceReturn, targetReturn, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57441                 if (elaborated) {
57442                     return elaborated;
57443                 }
57444                 var resultObj = errorOutputContainer || {};
57445                 checkTypeRelatedTo(sourceReturn, targetReturn, relation, returnExpression, /*message*/ undefined, containingMessageChain, resultObj);
57446                 if (resultObj.errors) {
57447                     if (target.symbol && ts.length(target.symbol.declarations)) {
57448                         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));
57449                     }
57450                     if ((ts.getFunctionFlags(node) & 2 /* Async */) === 0
57451                         // exclude cases where source itself is promisy - this way we don't make a suggestion when relating
57452                         // an IPromise and a Promise that are slightly different
57453                         && !getTypeOfPropertyOfType(sourceReturn, "then")
57454                         && checkTypeRelatedTo(createPromiseType(sourceReturn), targetReturn, relation, /*errorNode*/ undefined)) {
57455                         ts.addRelatedInfo(resultObj.errors[resultObj.errors.length - 1], ts.createDiagnosticForNode(node, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async));
57456                     }
57457                     return true;
57458                 }
57459             }
57460             return false;
57461         }
57462         function getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType) {
57463             var idx = getIndexedAccessTypeOrUndefined(target, nameType);
57464             if (idx) {
57465                 return idx;
57466             }
57467             if (target.flags & 1048576 /* Union */) {
57468                 var best = getBestMatchingType(source, target);
57469                 if (best) {
57470                     return getIndexedAccessTypeOrUndefined(best, nameType);
57471                 }
57472             }
57473         }
57474         function checkExpressionForMutableLocationWithContextualType(next, sourcePropType) {
57475             next.contextualType = sourcePropType;
57476             try {
57477                 return checkExpressionForMutableLocation(next, 1 /* Contextual */, sourcePropType);
57478             }
57479             finally {
57480                 next.contextualType = undefined;
57481             }
57482         }
57483         /**
57484          * For every element returned from the iterator, checks that element to issue an error on a property of that element's type
57485          * 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`
57486          * Otherwise, we issue an error on _every_ element which fail the assignability check
57487          */
57488         function elaborateElementwise(iterator, source, target, relation, containingMessageChain, errorOutputContainer) {
57489             // Assignability failure - check each prop individually, and if that fails, fall back on the bad error span
57490             var reportedError = false;
57491             for (var status = iterator.next(); !status.done; status = iterator.next()) {
57492                 var _a = status.value, prop = _a.errorNode, next = _a.innerExpression, nameType = _a.nameType, errorMessage = _a.errorMessage;
57493                 var targetPropType = getBestMatchIndexedAccessTypeOrUndefined(source, target, nameType);
57494                 if (!targetPropType || targetPropType.flags & 8388608 /* IndexedAccess */)
57495                     continue; // Don't elaborate on indexes on generic variables
57496                 var sourcePropType = getIndexedAccessTypeOrUndefined(source, nameType);
57497                 if (sourcePropType && !checkTypeRelatedTo(sourcePropType, targetPropType, relation, /*errorNode*/ undefined)) {
57498                     var elaborated = next && elaborateError(next, sourcePropType, targetPropType, relation, /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
57499                     if (elaborated) {
57500                         reportedError = true;
57501                     }
57502                     else {
57503                         // Issue error on the prop itself, since the prop couldn't elaborate the error
57504                         var resultObj = errorOutputContainer || {};
57505                         // Use the expression type, if available
57506                         var specificSource = next ? checkExpressionForMutableLocationWithContextualType(next, sourcePropType) : sourcePropType;
57507                         var result = checkTypeRelatedTo(specificSource, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
57508                         if (result && specificSource !== sourcePropType) {
57509                             // If for whatever reason the expression type doesn't yield an error, make sure we still issue an error on the sourcePropType
57510                             checkTypeRelatedTo(sourcePropType, targetPropType, relation, prop, errorMessage, containingMessageChain, resultObj);
57511                         }
57512                         if (resultObj.errors) {
57513                             var reportedDiag = resultObj.errors[resultObj.errors.length - 1];
57514                             var propertyName = isTypeUsableAsPropertyName(nameType) ? getPropertyNameFromType(nameType) : undefined;
57515                             var targetProp = propertyName !== undefined ? getPropertyOfType(target, propertyName) : undefined;
57516                             var issuedElaboration = false;
57517                             if (!targetProp) {
57518                                 var indexInfo = isTypeAssignableToKind(nameType, 296 /* NumberLike */) && getIndexInfoOfType(target, 1 /* Number */) ||
57519                                     getIndexInfoOfType(target, 0 /* String */) ||
57520                                     undefined;
57521                                 if (indexInfo && indexInfo.declaration && !ts.getSourceFileOfNode(indexInfo.declaration).hasNoDefaultLib) {
57522                                     issuedElaboration = true;
57523                                     ts.addRelatedInfo(reportedDiag, ts.createDiagnosticForNode(indexInfo.declaration, ts.Diagnostics.The_expected_type_comes_from_this_index_signature));
57524                                 }
57525                             }
57526                             if (!issuedElaboration && (targetProp && ts.length(targetProp.declarations) || target.symbol && ts.length(target.symbol.declarations))) {
57527                                 var targetNode = targetProp && ts.length(targetProp.declarations) ? targetProp.declarations[0] : target.symbol.declarations[0];
57528                                 if (!ts.getSourceFileOfNode(targetNode).hasNoDefaultLib) {
57529                                     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)));
57530                                 }
57531                             }
57532                         }
57533                         reportedError = true;
57534                     }
57535                 }
57536             }
57537             return reportedError;
57538         }
57539         function generateJsxAttributes(node) {
57540             var _i, _a, prop;
57541             return __generator(this, function (_b) {
57542                 switch (_b.label) {
57543                     case 0:
57544                         if (!ts.length(node.properties))
57545                             return [2 /*return*/];
57546                         _i = 0, _a = node.properties;
57547                         _b.label = 1;
57548                     case 1:
57549                         if (!(_i < _a.length)) return [3 /*break*/, 4];
57550                         prop = _a[_i];
57551                         if (ts.isJsxSpreadAttribute(prop))
57552                             return [3 /*break*/, 3];
57553                         return [4 /*yield*/, { errorNode: prop.name, innerExpression: prop.initializer, nameType: getLiteralType(ts.idText(prop.name)) }];
57554                     case 2:
57555                         _b.sent();
57556                         _b.label = 3;
57557                     case 3:
57558                         _i++;
57559                         return [3 /*break*/, 1];
57560                     case 4: return [2 /*return*/];
57561                 }
57562             });
57563         }
57564         function generateJsxChildren(node, getInvalidTextDiagnostic) {
57565             var memberOffset, i, child, nameType, elem;
57566             return __generator(this, function (_a) {
57567                 switch (_a.label) {
57568                     case 0:
57569                         if (!ts.length(node.children))
57570                             return [2 /*return*/];
57571                         memberOffset = 0;
57572                         i = 0;
57573                         _a.label = 1;
57574                     case 1:
57575                         if (!(i < node.children.length)) return [3 /*break*/, 5];
57576                         child = node.children[i];
57577                         nameType = getLiteralType(i - memberOffset);
57578                         elem = getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic);
57579                         if (!elem) return [3 /*break*/, 3];
57580                         return [4 /*yield*/, elem];
57581                     case 2:
57582                         _a.sent();
57583                         return [3 /*break*/, 4];
57584                     case 3:
57585                         memberOffset++;
57586                         _a.label = 4;
57587                     case 4:
57588                         i++;
57589                         return [3 /*break*/, 1];
57590                     case 5: return [2 /*return*/];
57591                 }
57592             });
57593         }
57594         function getElaborationElementForJsxChild(child, nameType, getInvalidTextDiagnostic) {
57595             switch (child.kind) {
57596                 case 283 /* JsxExpression */:
57597                     // child is of the type of the expression
57598                     return { errorNode: child, innerExpression: child.expression, nameType: nameType };
57599                 case 11 /* JsxText */:
57600                     if (child.containsOnlyTriviaWhiteSpaces) {
57601                         break; // Whitespace only jsx text isn't real jsx text
57602                     }
57603                     // child is a string
57604                     return { errorNode: child, innerExpression: undefined, nameType: nameType, errorMessage: getInvalidTextDiagnostic() };
57605                 case 273 /* JsxElement */:
57606                 case 274 /* JsxSelfClosingElement */:
57607                 case 277 /* JsxFragment */:
57608                     // child is of type JSX.Element
57609                     return { errorNode: child, innerExpression: child, nameType: nameType };
57610                 default:
57611                     return ts.Debug.assertNever(child, "Found invalid jsx child");
57612             }
57613         }
57614         function elaborateJsxComponents(node, source, target, relation, containingMessageChain, errorOutputContainer) {
57615             var result = elaborateElementwise(generateJsxAttributes(node), source, target, relation, containingMessageChain, errorOutputContainer);
57616             var invalidTextDiagnostic;
57617             if (ts.isJsxOpeningElement(node.parent) && ts.isJsxElement(node.parent.parent)) {
57618                 var containingElement = node.parent.parent;
57619                 var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
57620                 var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
57621                 var childrenNameType = getLiteralType(childrenPropName);
57622                 var childrenTargetType = getIndexedAccessType(target, childrenNameType);
57623                 var validChildren = ts.getSemanticJsxChildren(containingElement.children);
57624                 if (!ts.length(validChildren)) {
57625                     return result;
57626                 }
57627                 var moreThanOneRealChildren = ts.length(validChildren) > 1;
57628                 var arrayLikeTargetParts = filterType(childrenTargetType, isArrayOrTupleLikeType);
57629                 var nonArrayLikeTargetParts = filterType(childrenTargetType, function (t) { return !isArrayOrTupleLikeType(t); });
57630                 if (moreThanOneRealChildren) {
57631                     if (arrayLikeTargetParts !== neverType) {
57632                         var realSource = createTupleType(checkJsxChildren(containingElement, 0 /* Normal */));
57633                         var children = generateJsxChildren(containingElement, getInvalidTextualChildDiagnostic);
57634                         result = elaborateElementwise(children, realSource, arrayLikeTargetParts, relation, containingMessageChain, errorOutputContainer) || result;
57635                     }
57636                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
57637                         // arity mismatch
57638                         result = true;
57639                         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));
57640                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
57641                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
57642                         }
57643                     }
57644                 }
57645                 else {
57646                     if (nonArrayLikeTargetParts !== neverType) {
57647                         var child = validChildren[0];
57648                         var elem_1 = getElaborationElementForJsxChild(child, childrenNameType, getInvalidTextualChildDiagnostic);
57649                         if (elem_1) {
57650                             result = elaborateElementwise((function () { return __generator(this, function (_a) {
57651                                 switch (_a.label) {
57652                                     case 0: return [4 /*yield*/, elem_1];
57653                                     case 1:
57654                                         _a.sent();
57655                                         return [2 /*return*/];
57656                                 }
57657                             }); })(), source, target, relation, containingMessageChain, errorOutputContainer) || result;
57658                         }
57659                     }
57660                     else if (!isTypeRelatedTo(getIndexedAccessType(source, childrenNameType), childrenTargetType, relation)) {
57661                         // arity mismatch
57662                         result = true;
57663                         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));
57664                         if (errorOutputContainer && errorOutputContainer.skipLogging) {
57665                             (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
57666                         }
57667                     }
57668                 }
57669             }
57670             return result;
57671             function getInvalidTextualChildDiagnostic() {
57672                 if (!invalidTextDiagnostic) {
57673                     var tagNameText = ts.getTextOfNode(node.parent.tagName);
57674                     var childPropName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
57675                     var childrenPropName = childPropName === undefined ? "children" : ts.unescapeLeadingUnderscores(childPropName);
57676                     var childrenTargetType = getIndexedAccessType(target, getLiteralType(childrenPropName));
57677                     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;
57678                     invalidTextDiagnostic = __assign(__assign({}, diagnostic), { key: "!!ALREADY FORMATTED!!", message: ts.formatMessage(/*_dummy*/ undefined, diagnostic, tagNameText, childrenPropName, typeToString(childrenTargetType)) });
57679                 }
57680                 return invalidTextDiagnostic;
57681             }
57682         }
57683         function generateLimitedTupleElements(node, target) {
57684             var len, i, elem, nameType;
57685             return __generator(this, function (_a) {
57686                 switch (_a.label) {
57687                     case 0:
57688                         len = ts.length(node.elements);
57689                         if (!len)
57690                             return [2 /*return*/];
57691                         i = 0;
57692                         _a.label = 1;
57693                     case 1:
57694                         if (!(i < len)) return [3 /*break*/, 4];
57695                         // 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
57696                         if (isTupleLikeType(target) && !getPropertyOfType(target, ("" + i)))
57697                             return [3 /*break*/, 3];
57698                         elem = node.elements[i];
57699                         if (ts.isOmittedExpression(elem))
57700                             return [3 /*break*/, 3];
57701                         nameType = getLiteralType(i);
57702                         return [4 /*yield*/, { errorNode: elem, innerExpression: elem, nameType: nameType }];
57703                     case 2:
57704                         _a.sent();
57705                         _a.label = 3;
57706                     case 3:
57707                         i++;
57708                         return [3 /*break*/, 1];
57709                     case 4: return [2 /*return*/];
57710                 }
57711             });
57712         }
57713         function elaborateArrayLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
57714             if (target.flags & 131068 /* Primitive */)
57715                 return false;
57716             if (isTupleLikeType(source)) {
57717                 return elaborateElementwise(generateLimitedTupleElements(node, target), source, target, relation, containingMessageChain, errorOutputContainer);
57718             }
57719             // recreate a tuple from the elements, if possible
57720             // Since we're re-doing the expression type, we need to reapply the contextual type
57721             var oldContext = node.contextualType;
57722             node.contextualType = target;
57723             try {
57724                 var tupleizedType = checkArrayLiteral(node, 1 /* Contextual */, /*forceTuple*/ true);
57725                 node.contextualType = oldContext;
57726                 if (isTupleLikeType(tupleizedType)) {
57727                     return elaborateElementwise(generateLimitedTupleElements(node, target), tupleizedType, target, relation, containingMessageChain, errorOutputContainer);
57728                 }
57729                 return false;
57730             }
57731             finally {
57732                 node.contextualType = oldContext;
57733             }
57734         }
57735         function generateObjectLiteralElements(node) {
57736             var _i, _a, prop, type, _b;
57737             return __generator(this, function (_c) {
57738                 switch (_c.label) {
57739                     case 0:
57740                         if (!ts.length(node.properties))
57741                             return [2 /*return*/];
57742                         _i = 0, _a = node.properties;
57743                         _c.label = 1;
57744                     case 1:
57745                         if (!(_i < _a.length)) return [3 /*break*/, 8];
57746                         prop = _a[_i];
57747                         if (ts.isSpreadAssignment(prop))
57748                             return [3 /*break*/, 7];
57749                         type = getLiteralTypeFromProperty(getSymbolOfNode(prop), 8576 /* StringOrNumberLiteralOrUnique */);
57750                         if (!type || (type.flags & 131072 /* Never */)) {
57751                             return [3 /*break*/, 7];
57752                         }
57753                         _b = prop.kind;
57754                         switch (_b) {
57755                             case 168 /* SetAccessor */: return [3 /*break*/, 2];
57756                             case 167 /* GetAccessor */: return [3 /*break*/, 2];
57757                             case 165 /* MethodDeclaration */: return [3 /*break*/, 2];
57758                             case 289 /* ShorthandPropertyAssignment */: return [3 /*break*/, 2];
57759                             case 288 /* PropertyAssignment */: return [3 /*break*/, 4];
57760                         }
57761                         return [3 /*break*/, 6];
57762                     case 2: return [4 /*yield*/, { errorNode: prop.name, innerExpression: undefined, nameType: type }];
57763                     case 3:
57764                         _c.sent();
57765                         return [3 /*break*/, 7];
57766                     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 }];
57767                     case 5:
57768                         _c.sent();
57769                         return [3 /*break*/, 7];
57770                     case 6:
57771                         ts.Debug.assertNever(prop);
57772                         _c.label = 7;
57773                     case 7:
57774                         _i++;
57775                         return [3 /*break*/, 1];
57776                     case 8: return [2 /*return*/];
57777                 }
57778             });
57779         }
57780         function elaborateObjectLiteral(node, source, target, relation, containingMessageChain, errorOutputContainer) {
57781             if (target.flags & 131068 /* Primitive */)
57782                 return false;
57783             return elaborateElementwise(generateObjectLiteralElements(node), source, target, relation, containingMessageChain, errorOutputContainer);
57784         }
57785         /**
57786          * This is *not* a bi-directional relationship.
57787          * If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
57788          */
57789         function checkTypeComparableTo(source, target, errorNode, headMessage, containingMessageChain) {
57790             return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
57791         }
57792         function isSignatureAssignableTo(source, target, ignoreReturnTypes) {
57793             return compareSignaturesRelated(source, target, ignoreReturnTypes ? 4 /* IgnoreReturnTypes */ : 0, /*reportErrors*/ false, 
57794             /*errorReporter*/ undefined, /*errorReporter*/ undefined, compareTypesAssignable, /*reportUnreliableMarkers*/ undefined) !== 0 /* False */;
57795         }
57796         /**
57797          * Returns true if `s` is `(...args: any[]) => any` or `(this: any, ...args: any[]) => any`
57798          */
57799         function isAnySignature(s) {
57800             return !s.typeParameters && (!s.thisParameter || isTypeAny(getTypeOfParameter(s.thisParameter))) && s.parameters.length === 1 &&
57801                 signatureHasRestParameter(s) && (getTypeOfParameter(s.parameters[0]) === anyArrayType || isTypeAny(getTypeOfParameter(s.parameters[0]))) &&
57802                 isTypeAny(getReturnTypeOfSignature(s));
57803         }
57804         /**
57805          * See signatureRelatedTo, compareSignaturesIdentical
57806          */
57807         function compareSignaturesRelated(source, target, checkMode, reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) {
57808             // TODO (drosen): De-duplicate code between related functions.
57809             if (source === target) {
57810                 return -1 /* True */;
57811             }
57812             if (isAnySignature(target)) {
57813                 return -1 /* True */;
57814             }
57815             var targetCount = getParameterCount(target);
57816             var sourceHasMoreParameters = !hasEffectiveRestParameter(target) &&
57817                 (checkMode & 8 /* StrictArity */ ? hasEffectiveRestParameter(source) || getParameterCount(source) > targetCount : getMinArgumentCount(source) > targetCount);
57818             if (sourceHasMoreParameters) {
57819                 return 0 /* False */;
57820             }
57821             if (source.typeParameters && source.typeParameters !== target.typeParameters) {
57822                 target = getCanonicalSignature(target);
57823                 source = instantiateSignatureInContextOf(source, target, /*inferenceContext*/ undefined, compareTypes);
57824             }
57825             var sourceCount = getParameterCount(source);
57826             var sourceRestType = getNonArrayRestType(source);
57827             var targetRestType = getNonArrayRestType(target);
57828             if (sourceRestType || targetRestType) {
57829                 void instantiateType(sourceRestType || targetRestType, reportUnreliableMarkers);
57830             }
57831             if (sourceRestType && targetRestType && sourceCount !== targetCount) {
57832                 // We're not able to relate misaligned complex rest parameters
57833                 return 0 /* False */;
57834             }
57835             var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
57836             var strictVariance = !(checkMode & 3 /* Callback */) && strictFunctionTypes && kind !== 165 /* MethodDeclaration */ &&
57837                 kind !== 164 /* MethodSignature */ && kind !== 166 /* Constructor */;
57838             var result = -1 /* True */;
57839             var sourceThisType = getThisTypeOfSignature(source);
57840             if (sourceThisType && sourceThisType !== voidType) {
57841                 var targetThisType = getThisTypeOfSignature(target);
57842                 if (targetThisType) {
57843                     // void sources are assignable to anything.
57844                     var related = !strictVariance && compareTypes(sourceThisType, targetThisType, /*reportErrors*/ false)
57845                         || compareTypes(targetThisType, sourceThisType, reportErrors);
57846                     if (!related) {
57847                         if (reportErrors) {
57848                             errorReporter(ts.Diagnostics.The_this_types_of_each_signature_are_incompatible);
57849                         }
57850                         return 0 /* False */;
57851                     }
57852                     result &= related;
57853                 }
57854             }
57855             var paramCount = sourceRestType || targetRestType ? Math.min(sourceCount, targetCount) : Math.max(sourceCount, targetCount);
57856             var restIndex = sourceRestType || targetRestType ? paramCount - 1 : -1;
57857             for (var i = 0; i < paramCount; i++) {
57858                 var sourceType = i === restIndex ? getRestTypeAtPosition(source, i) : tryGetTypeAtPosition(source, i);
57859                 var targetType = i === restIndex ? getRestTypeAtPosition(target, i) : tryGetTypeAtPosition(target, i);
57860                 if (sourceType && targetType) {
57861                     // In order to ensure that any generic type Foo<T> is at least co-variant with respect to T no matter
57862                     // how Foo uses T, we need to relate parameters bi-variantly (given that parameters are input positions,
57863                     // they naturally relate only contra-variantly). However, if the source and target parameters both have
57864                     // function types with a single call signature, we know we are relating two callback parameters. In
57865                     // that case it is sufficient to only relate the parameters of the signatures co-variantly because,
57866                     // similar to return values, callback parameters are output positions. This means that a Promise<T>,
57867                     // where T is used only in callback parameter positions, will be co-variant (as opposed to bi-variant)
57868                     // with respect to T.
57869                     var sourceSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(sourceType));
57870                     var targetSig = checkMode & 3 /* Callback */ ? undefined : getSingleCallSignature(getNonNullableType(targetType));
57871                     var callbacks = sourceSig && targetSig && !getTypePredicateOfSignature(sourceSig) && !getTypePredicateOfSignature(targetSig) &&
57872                         (getFalsyFlags(sourceType) & 98304 /* Nullable */) === (getFalsyFlags(targetType) & 98304 /* Nullable */);
57873                     var related = callbacks ?
57874                         compareSignaturesRelated(targetSig, sourceSig, (checkMode & 8 /* StrictArity */) | (strictVariance ? 2 /* StrictCallback */ : 1 /* BivariantCallback */), reportErrors, errorReporter, incompatibleErrorReporter, compareTypes, reportUnreliableMarkers) :
57875                         !(checkMode & 3 /* Callback */) && !strictVariance && compareTypes(sourceType, targetType, /*reportErrors*/ false) || compareTypes(targetType, sourceType, reportErrors);
57876                     // With strict arity, (x: number | undefined) => void is a subtype of (x?: number | undefined) => void
57877                     if (related && checkMode & 8 /* StrictArity */ && i >= getMinArgumentCount(source) && i < getMinArgumentCount(target) && compareTypes(sourceType, targetType, /*reportErrors*/ false)) {
57878                         related = 0 /* False */;
57879                     }
57880                     if (!related) {
57881                         if (reportErrors) {
57882                             errorReporter(ts.Diagnostics.Types_of_parameters_0_and_1_are_incompatible, ts.unescapeLeadingUnderscores(getParameterNameAtPosition(source, i)), ts.unescapeLeadingUnderscores(getParameterNameAtPosition(target, i)));
57883                         }
57884                         return 0 /* False */;
57885                     }
57886                     result &= related;
57887                 }
57888             }
57889             if (!(checkMode & 4 /* IgnoreReturnTypes */)) {
57890                 // If a signature resolution is already in-flight, skip issuing a circularity error
57891                 // here and just use the `any` type directly
57892                 var targetReturnType = isResolvingReturnTypeOfSignature(target) ? anyType
57893                     : target.declaration && isJSConstructor(target.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(target.declaration.symbol))
57894                         : getReturnTypeOfSignature(target);
57895                 if (targetReturnType === voidType) {
57896                     return result;
57897                 }
57898                 var sourceReturnType = isResolvingReturnTypeOfSignature(source) ? anyType
57899                     : source.declaration && isJSConstructor(source.declaration) ? getDeclaredTypeOfClassOrInterface(getMergedSymbol(source.declaration.symbol))
57900                         : getReturnTypeOfSignature(source);
57901                 // The following block preserves behavior forbidding boolean returning functions from being assignable to type guard returning functions
57902                 var targetTypePredicate = getTypePredicateOfSignature(target);
57903                 if (targetTypePredicate) {
57904                     var sourceTypePredicate = getTypePredicateOfSignature(source);
57905                     if (sourceTypePredicate) {
57906                         result &= compareTypePredicateRelatedTo(sourceTypePredicate, targetTypePredicate, reportErrors, errorReporter, compareTypes);
57907                     }
57908                     else if (ts.isIdentifierTypePredicate(targetTypePredicate)) {
57909                         if (reportErrors) {
57910                             errorReporter(ts.Diagnostics.Signature_0_must_be_a_type_predicate, signatureToString(source));
57911                         }
57912                         return 0 /* False */;
57913                     }
57914                 }
57915                 else {
57916                     // When relating callback signatures, we still need to relate return types bi-variantly as otherwise
57917                     // the containing type wouldn't be co-variant. For example, interface Foo<T> { add(cb: () => T): void }
57918                     // wouldn't be co-variant for T without this rule.
57919                     result &= checkMode & 1 /* BivariantCallback */ && compareTypes(targetReturnType, sourceReturnType, /*reportErrors*/ false) ||
57920                         compareTypes(sourceReturnType, targetReturnType, reportErrors);
57921                     if (!result && reportErrors && incompatibleErrorReporter) {
57922                         incompatibleErrorReporter(sourceReturnType, targetReturnType);
57923                     }
57924                 }
57925             }
57926             return result;
57927         }
57928         function compareTypePredicateRelatedTo(source, target, reportErrors, errorReporter, compareTypes) {
57929             if (source.kind !== target.kind) {
57930                 if (reportErrors) {
57931                     errorReporter(ts.Diagnostics.A_this_based_type_guard_is_not_compatible_with_a_parameter_based_type_guard);
57932                     errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
57933                 }
57934                 return 0 /* False */;
57935             }
57936             if (source.kind === 1 /* Identifier */ || source.kind === 3 /* AssertsIdentifier */) {
57937                 if (source.parameterIndex !== target.parameterIndex) {
57938                     if (reportErrors) {
57939                         errorReporter(ts.Diagnostics.Parameter_0_is_not_in_the_same_position_as_parameter_1, source.parameterName, target.parameterName);
57940                         errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
57941                     }
57942                     return 0 /* False */;
57943                 }
57944             }
57945             var related = source.type === target.type ? -1 /* True */ :
57946                 source.type && target.type ? compareTypes(source.type, target.type, reportErrors) :
57947                     0 /* False */;
57948             if (related === 0 /* False */ && reportErrors) {
57949                 errorReporter(ts.Diagnostics.Type_predicate_0_is_not_assignable_to_1, typePredicateToString(source), typePredicateToString(target));
57950             }
57951             return related;
57952         }
57953         function isImplementationCompatibleWithOverload(implementation, overload) {
57954             var erasedSource = getErasedSignature(implementation);
57955             var erasedTarget = getErasedSignature(overload);
57956             // First see if the return types are compatible in either direction.
57957             var sourceReturnType = getReturnTypeOfSignature(erasedSource);
57958             var targetReturnType = getReturnTypeOfSignature(erasedTarget);
57959             if (targetReturnType === voidType
57960                 || isTypeRelatedTo(targetReturnType, sourceReturnType, assignableRelation)
57961                 || isTypeRelatedTo(sourceReturnType, targetReturnType, assignableRelation)) {
57962                 return isSignatureAssignableTo(erasedSource, erasedTarget, /*ignoreReturnTypes*/ true);
57963             }
57964             return false;
57965         }
57966         function isEmptyResolvedType(t) {
57967             return t !== anyFunctionType &&
57968                 t.properties.length === 0 &&
57969                 t.callSignatures.length === 0 &&
57970                 t.constructSignatures.length === 0 &&
57971                 !t.stringIndexInfo &&
57972                 !t.numberIndexInfo;
57973         }
57974         function isEmptyObjectType(type) {
57975             return type.flags & 524288 /* Object */ ? !isGenericMappedType(type) && isEmptyResolvedType(resolveStructuredTypeMembers(type)) :
57976                 type.flags & 67108864 /* NonPrimitive */ ? true :
57977                     type.flags & 1048576 /* Union */ ? ts.some(type.types, isEmptyObjectType) :
57978                         type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isEmptyObjectType) :
57979                             false;
57980         }
57981         function isEmptyAnonymousObjectType(type) {
57982             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */ && (type.members && isEmptyResolvedType(type) ||
57983                 type.symbol && type.symbol.flags & 2048 /* TypeLiteral */ && getMembersOfSymbol(type.symbol).size === 0));
57984         }
57985         function isStringIndexSignatureOnlyType(type) {
57986             return type.flags & 524288 /* Object */ && !isGenericMappedType(type) && getPropertiesOfType(type).length === 0 && getIndexInfoOfType(type, 0 /* String */) && !getIndexInfoOfType(type, 1 /* Number */) ||
57987                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isStringIndexSignatureOnlyType) ||
57988                 false;
57989         }
57990         function isEnumTypeRelatedTo(sourceSymbol, targetSymbol, errorReporter) {
57991             if (sourceSymbol === targetSymbol) {
57992                 return true;
57993             }
57994             var id = getSymbolId(sourceSymbol) + "," + getSymbolId(targetSymbol);
57995             var entry = enumRelation.get(id);
57996             if (entry !== undefined && !(!(entry & 4 /* Reported */) && entry & 2 /* Failed */ && errorReporter)) {
57997                 return !!(entry & 1 /* Succeeded */);
57998             }
57999             if (sourceSymbol.escapedName !== targetSymbol.escapedName || !(sourceSymbol.flags & 256 /* RegularEnum */) || !(targetSymbol.flags & 256 /* RegularEnum */)) {
58000                 enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
58001                 return false;
58002             }
58003             var targetEnumType = getTypeOfSymbol(targetSymbol);
58004             for (var _i = 0, _a = getPropertiesOfType(getTypeOfSymbol(sourceSymbol)); _i < _a.length; _i++) {
58005                 var property = _a[_i];
58006                 if (property.flags & 8 /* EnumMember */) {
58007                     var targetProperty = getPropertyOfType(targetEnumType, property.escapedName);
58008                     if (!targetProperty || !(targetProperty.flags & 8 /* EnumMember */)) {
58009                         if (errorReporter) {
58010                             errorReporter(ts.Diagnostics.Property_0_is_missing_in_type_1, ts.symbolName(property), typeToString(getDeclaredTypeOfSymbol(targetSymbol), /*enclosingDeclaration*/ undefined, 64 /* UseFullyQualifiedType */));
58011                             enumRelation.set(id, 2 /* Failed */ | 4 /* Reported */);
58012                         }
58013                         else {
58014                             enumRelation.set(id, 2 /* Failed */);
58015                         }
58016                         return false;
58017                     }
58018                 }
58019             }
58020             enumRelation.set(id, 1 /* Succeeded */);
58021             return true;
58022         }
58023         function isSimpleTypeRelatedTo(source, target, relation, errorReporter) {
58024             var s = source.flags;
58025             var t = target.flags;
58026             if (t & 3 /* AnyOrUnknown */ || s & 131072 /* Never */ || source === wildcardType)
58027                 return true;
58028             if (t & 131072 /* Never */)
58029                 return false;
58030             if (s & 402653316 /* StringLike */ && t & 4 /* String */)
58031                 return true;
58032             if (s & 128 /* StringLiteral */ && s & 1024 /* EnumLiteral */ &&
58033                 t & 128 /* StringLiteral */ && !(t & 1024 /* EnumLiteral */) &&
58034                 source.value === target.value)
58035                 return true;
58036             if (s & 296 /* NumberLike */ && t & 8 /* Number */)
58037                 return true;
58038             if (s & 256 /* NumberLiteral */ && s & 1024 /* EnumLiteral */ &&
58039                 t & 256 /* NumberLiteral */ && !(t & 1024 /* EnumLiteral */) &&
58040                 source.value === target.value)
58041                 return true;
58042             if (s & 2112 /* BigIntLike */ && t & 64 /* BigInt */)
58043                 return true;
58044             if (s & 528 /* BooleanLike */ && t & 16 /* Boolean */)
58045                 return true;
58046             if (s & 12288 /* ESSymbolLike */ && t & 4096 /* ESSymbol */)
58047                 return true;
58048             if (s & 32 /* Enum */ && t & 32 /* Enum */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
58049                 return true;
58050             if (s & 1024 /* EnumLiteral */ && t & 1024 /* EnumLiteral */) {
58051                 if (s & 1048576 /* Union */ && t & 1048576 /* Union */ && isEnumTypeRelatedTo(source.symbol, target.symbol, errorReporter))
58052                     return true;
58053                 if (s & 2944 /* Literal */ && t & 2944 /* Literal */ &&
58054                     source.value === target.value &&
58055                     isEnumTypeRelatedTo(getParentOfSymbol(source.symbol), getParentOfSymbol(target.symbol), errorReporter))
58056                     return true;
58057             }
58058             if (s & 32768 /* Undefined */ && (!strictNullChecks || t & (32768 /* Undefined */ | 16384 /* Void */)))
58059                 return true;
58060             if (s & 65536 /* Null */ && (!strictNullChecks || t & 65536 /* Null */))
58061                 return true;
58062             if (s & 524288 /* Object */ && t & 67108864 /* NonPrimitive */)
58063                 return true;
58064             if (relation === assignableRelation || relation === comparableRelation) {
58065                 if (s & 1 /* Any */)
58066                     return true;
58067                 // Type number or any numeric literal type is assignable to any numeric enum type or any
58068                 // numeric enum literal type. This rule exists for backwards compatibility reasons because
58069                 // bit-flag enum types sometimes look like literal enum types with numeric literal values.
58070                 if (s & (8 /* Number */ | 256 /* NumberLiteral */) && !(s & 1024 /* EnumLiteral */) && (t & 32 /* Enum */ || t & 256 /* NumberLiteral */ && t & 1024 /* EnumLiteral */))
58071                     return true;
58072             }
58073             return false;
58074         }
58075         function isTypeRelatedTo(source, target, relation) {
58076             if (isFreshLiteralType(source)) {
58077                 source = source.regularType;
58078             }
58079             if (isFreshLiteralType(target)) {
58080                 target = target.regularType;
58081             }
58082             if (source === target) {
58083                 return true;
58084             }
58085             if (relation !== identityRelation) {
58086                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) || isSimpleTypeRelatedTo(source, target, relation)) {
58087                     return true;
58088                 }
58089             }
58090             else {
58091                 if (!(source.flags & 3145728 /* UnionOrIntersection */) && !(target.flags & 3145728 /* UnionOrIntersection */) &&
58092                     source.flags !== target.flags && !(source.flags & 469237760 /* Substructure */))
58093                     return false;
58094             }
58095             if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
58096                 var related = relation.get(getRelationKey(source, target, 0 /* None */, relation));
58097                 if (related !== undefined) {
58098                     return !!(related & 1 /* Succeeded */);
58099                 }
58100             }
58101             if (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */) {
58102                 return checkTypeRelatedTo(source, target, relation, /*errorNode*/ undefined);
58103             }
58104             return false;
58105         }
58106         function isIgnoredJsxProperty(source, sourceProp) {
58107             return ts.getObjectFlags(source) & 4096 /* JsxAttributes */ && !isUnhyphenatedJsxName(sourceProp.escapedName);
58108         }
58109         function getNormalizedType(type, writing) {
58110             while (true) {
58111                 var t = isFreshLiteralType(type) ? type.regularType :
58112                     ts.getObjectFlags(type) & 4 /* Reference */ && type.node ? createTypeReference(type.target, getTypeArguments(type)) :
58113                         type.flags & 3145728 /* UnionOrIntersection */ ? getReducedType(type) :
58114                             type.flags & 33554432 /* Substitution */ ? writing ? type.baseType : type.substitute :
58115                                 type.flags & 25165824 /* Simplifiable */ ? getSimplifiedType(type, writing) :
58116                                     type;
58117                 if (t === type)
58118                     break;
58119                 type = t;
58120             }
58121             return type;
58122         }
58123         /**
58124          * Checks if 'source' is related to 'target' (e.g.: is a assignable to).
58125          * @param source The left-hand-side of the relation.
58126          * @param target The right-hand-side of the relation.
58127          * @param relation The relation considered. One of 'identityRelation', 'subtypeRelation', 'assignableRelation', or 'comparableRelation'.
58128          * Used as both to determine which checks are performed and as a cache of previously computed results.
58129          * @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
58130          * @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
58131          * @param containingMessageChain A chain of errors to prepend any new errors found.
58132          * @param errorOutputContainer Return the diagnostic. Do not log if 'skipLogging' is truthy.
58133          */
58134         function checkTypeRelatedTo(source, target, relation, errorNode, headMessage, containingMessageChain, errorOutputContainer) {
58135             var errorInfo;
58136             var relatedInfo;
58137             var maybeKeys;
58138             var sourceStack;
58139             var targetStack;
58140             var maybeCount = 0;
58141             var depth = 0;
58142             var expandingFlags = 0 /* None */;
58143             var overflow = false;
58144             var overrideNextErrorInfo = 0; // How many `reportRelationError` calls should be skipped in the elaboration pyramid
58145             var lastSkippedInfo;
58146             var incompatibleStack = [];
58147             var inPropertyCheck = false;
58148             ts.Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");
58149             var result = isRelatedTo(source, target, /*reportErrors*/ !!errorNode, headMessage);
58150             if (incompatibleStack.length) {
58151                 reportIncompatibleStack();
58152             }
58153             if (overflow) {
58154                 ts.tracing.instant("check" /* Check */, "checkTypeRelatedTo_DepthLimit", { sourceId: source.id, targetId: target.id, depth: depth });
58155                 var diag = error(errorNode || currentNode, ts.Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
58156                 if (errorOutputContainer) {
58157                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
58158                 }
58159             }
58160             else if (errorInfo) {
58161                 if (containingMessageChain) {
58162                     var chain = containingMessageChain();
58163                     if (chain) {
58164                         ts.concatenateDiagnosticMessageChains(chain, errorInfo);
58165                         errorInfo = chain;
58166                     }
58167                 }
58168                 var relatedInformation = void 0;
58169                 // Check if we should issue an extra diagnostic to produce a quickfix for a slightly incorrect import statement
58170                 if (headMessage && errorNode && !result && source.symbol) {
58171                     var links = getSymbolLinks(source.symbol);
58172                     if (links.originatingImport && !ts.isImportCall(links.originatingImport)) {
58173                         var helpfulRetry = checkTypeRelatedTo(getTypeOfSymbol(links.target), target, relation, /*errorNode*/ undefined);
58174                         if (helpfulRetry) {
58175                             // Likely an incorrect import. Issue a helpful diagnostic to produce a quickfix to change the import
58176                             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);
58177                             relatedInformation = ts.append(relatedInformation, diag_1); // Cause the error to appear with the error that triggered it
58178                         }
58179                     }
58180                 }
58181                 var diag = ts.createDiagnosticForNodeFromMessageChain(errorNode, errorInfo, relatedInformation);
58182                 if (relatedInfo) {
58183                     ts.addRelatedInfo.apply(void 0, __spreadArrays([diag], relatedInfo));
58184                 }
58185                 if (errorOutputContainer) {
58186                     (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
58187                 }
58188                 if (!errorOutputContainer || !errorOutputContainer.skipLogging) {
58189                     diagnostics.add(diag);
58190                 }
58191             }
58192             if (errorNode && errorOutputContainer && errorOutputContainer.skipLogging && result === 0 /* False */) {
58193                 ts.Debug.assert(!!errorOutputContainer.errors, "missed opportunity to interact with error.");
58194             }
58195             return result !== 0 /* False */;
58196             function resetErrorInfo(saved) {
58197                 errorInfo = saved.errorInfo;
58198                 lastSkippedInfo = saved.lastSkippedInfo;
58199                 incompatibleStack = saved.incompatibleStack;
58200                 overrideNextErrorInfo = saved.overrideNextErrorInfo;
58201                 relatedInfo = saved.relatedInfo;
58202             }
58203             function captureErrorCalculationState() {
58204                 return {
58205                     errorInfo: errorInfo,
58206                     lastSkippedInfo: lastSkippedInfo,
58207                     incompatibleStack: incompatibleStack.slice(),
58208                     overrideNextErrorInfo: overrideNextErrorInfo,
58209                     relatedInfo: !relatedInfo ? undefined : relatedInfo.slice()
58210                 };
58211             }
58212             function reportIncompatibleError(message, arg0, arg1, arg2, arg3) {
58213                 overrideNextErrorInfo++; // Suppress the next relation error
58214                 lastSkippedInfo = undefined; // Reset skipped info cache
58215                 incompatibleStack.push([message, arg0, arg1, arg2, arg3]);
58216             }
58217             function reportIncompatibleStack() {
58218                 var stack = incompatibleStack;
58219                 incompatibleStack = [];
58220                 var info = lastSkippedInfo;
58221                 lastSkippedInfo = undefined;
58222                 if (stack.length === 1) {
58223                     reportError.apply(void 0, stack[0]);
58224                     if (info) {
58225                         // Actually do the last relation error
58226                         reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
58227                     }
58228                     return;
58229                 }
58230                 // The first error will be the innermost, while the last will be the outermost - so by popping off the end,
58231                 // we can build from left to right
58232                 var path = "";
58233                 var secondaryRootErrors = [];
58234                 while (stack.length) {
58235                     var _a = stack.pop(), msg = _a[0], args = _a.slice(1);
58236                     switch (msg.code) {
58237                         case ts.Diagnostics.Types_of_property_0_are_incompatible.code: {
58238                             // Parenthesize a `new` if there is one
58239                             if (path.indexOf("new ") === 0) {
58240                                 path = "(" + path + ")";
58241                             }
58242                             var str = "" + args[0];
58243                             // If leading, just print back the arg (irrespective of if it's a valid identifier)
58244                             if (path.length === 0) {
58245                                 path = "" + str;
58246                             }
58247                             // Otherwise write a dotted name if possible
58248                             else if (ts.isIdentifierText(str, compilerOptions.target)) {
58249                                 path = path + "." + str;
58250                             }
58251                             // Failing that, check if the name is already a computed name
58252                             else if (str[0] === "[" && str[str.length - 1] === "]") {
58253                                 path = "" + path + str;
58254                             }
58255                             // And finally write out a computed name as a last resort
58256                             else {
58257                                 path = path + "[" + str + "]";
58258                             }
58259                             break;
58260                         }
58261                         case ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible.code:
58262                         case ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code:
58263                         case ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code:
58264                         case ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code: {
58265                             if (path.length === 0) {
58266                                 // Don't flatten signature compatability errors at the start of a chain - instead prefer
58267                                 // to unify (the with no arguments bit is excessive for printback) and print them back
58268                                 var mappedMsg = msg;
58269                                 if (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
58270                                     mappedMsg = ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible;
58271                                 }
58272                                 else if (msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code) {
58273                                     mappedMsg = ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible;
58274                                 }
58275                                 secondaryRootErrors.unshift([mappedMsg, args[0], args[1]]);
58276                             }
58277                             else {
58278                                 var prefix = (msg.code === ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible.code ||
58279                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
58280                                     ? "new "
58281                                     : "";
58282                                 var params = (msg.code === ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code ||
58283                                     msg.code === ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1.code)
58284                                     ? ""
58285                                     : "...";
58286                                 path = "" + prefix + path + "(" + params + ")";
58287                             }
58288                             break;
58289                         }
58290                         default:
58291                             return ts.Debug.fail("Unhandled Diagnostic: " + msg.code);
58292                     }
58293                 }
58294                 if (path) {
58295                     reportError(path[path.length - 1] === ")"
58296                         ? ts.Diagnostics.The_types_returned_by_0_are_incompatible_between_these_types
58297                         : ts.Diagnostics.The_types_of_0_are_incompatible_between_these_types, path);
58298                 }
58299                 else {
58300                     // Remove the innermost secondary error as it will duplicate the error already reported by `reportRelationError` on entry
58301                     secondaryRootErrors.shift();
58302                 }
58303                 for (var _i = 0, secondaryRootErrors_1 = secondaryRootErrors; _i < secondaryRootErrors_1.length; _i++) {
58304                     var _b = secondaryRootErrors_1[_i], msg = _b[0], args = _b.slice(1);
58305                     var originalValue = msg.elidedInCompatabilityPyramid;
58306                     msg.elidedInCompatabilityPyramid = false; // Teporarily override elision to ensure error is reported
58307                     reportError.apply(void 0, __spreadArrays([msg], args));
58308                     msg.elidedInCompatabilityPyramid = originalValue;
58309                 }
58310                 if (info) {
58311                     // Actually do the last relation error
58312                     reportRelationError.apply(void 0, __spreadArrays([/*headMessage*/ undefined], info));
58313                 }
58314             }
58315             function reportError(message, arg0, arg1, arg2, arg3) {
58316                 ts.Debug.assert(!!errorNode);
58317                 if (incompatibleStack.length)
58318                     reportIncompatibleStack();
58319                 if (message.elidedInCompatabilityPyramid)
58320                     return;
58321                 errorInfo = ts.chainDiagnosticMessages(errorInfo, message, arg0, arg1, arg2, arg3);
58322             }
58323             function associateRelatedInfo(info) {
58324                 ts.Debug.assert(!!errorInfo);
58325                 if (!relatedInfo) {
58326                     relatedInfo = [info];
58327                 }
58328                 else {
58329                     relatedInfo.push(info);
58330                 }
58331             }
58332             function reportRelationError(message, source, target) {
58333                 if (incompatibleStack.length)
58334                     reportIncompatibleStack();
58335                 var _a = getTypeNamesForErrorDisplay(source, target), sourceType = _a[0], targetType = _a[1];
58336                 var generalizedSource = source;
58337                 var generalizedSourceType = sourceType;
58338                 if (isLiteralType(source) && !typeCouldHaveTopLevelSingletonTypes(target)) {
58339                     generalizedSource = getBaseTypeOfLiteralType(source);
58340                     ts.Debug.assert(!isTypeAssignableTo(generalizedSource, target), "generalized source shouldn't be assignable");
58341                     generalizedSourceType = getTypeNameForErrorDisplay(generalizedSource);
58342                 }
58343                 if (target.flags & 262144 /* TypeParameter */) {
58344                     var constraint = getBaseConstraintOfType(target);
58345                     var needsOriginalSource = void 0;
58346                     if (constraint && (isTypeAssignableTo(generalizedSource, constraint) || (needsOriginalSource = isTypeAssignableTo(source, constraint)))) {
58347                         reportError(ts.Diagnostics._0_is_assignable_to_the_constraint_of_type_1_but_1_could_be_instantiated_with_a_different_subtype_of_constraint_2, needsOriginalSource ? sourceType : generalizedSourceType, targetType, typeToString(constraint));
58348                     }
58349                     else {
58350                         reportError(ts.Diagnostics._0_could_be_instantiated_with_an_arbitrary_type_which_could_be_unrelated_to_1, targetType, generalizedSourceType);
58351                     }
58352                 }
58353                 if (!message) {
58354                     if (relation === comparableRelation) {
58355                         message = ts.Diagnostics.Type_0_is_not_comparable_to_type_1;
58356                     }
58357                     else if (sourceType === targetType) {
58358                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1_Two_different_types_with_this_name_exist_but_they_are_unrelated;
58359                     }
58360                     else {
58361                         message = ts.Diagnostics.Type_0_is_not_assignable_to_type_1;
58362                     }
58363                 }
58364                 reportError(message, generalizedSourceType, targetType);
58365             }
58366             function tryElaborateErrorsForPrimitivesAndObjects(source, target) {
58367                 var sourceType = symbolValueDeclarationIsContextSensitive(source.symbol) ? typeToString(source, source.symbol.valueDeclaration) : typeToString(source);
58368                 var targetType = symbolValueDeclarationIsContextSensitive(target.symbol) ? typeToString(target, target.symbol.valueDeclaration) : typeToString(target);
58369                 if ((globalStringType === source && stringType === target) ||
58370                     (globalNumberType === source && numberType === target) ||
58371                     (globalBooleanType === source && booleanType === target) ||
58372                     (getGlobalESSymbolType(/*reportErrors*/ false) === source && esSymbolType === target)) {
58373                     reportError(ts.Diagnostics._0_is_a_primitive_but_1_is_a_wrapper_object_Prefer_using_0_when_possible, targetType, sourceType);
58374                 }
58375             }
58376             /**
58377              * Try and elaborate array and tuple errors. Returns false
58378              * if we have found an elaboration, or we should ignore
58379              * any other elaborations when relating the `source` and
58380              * `target` types.
58381              */
58382             function tryElaborateArrayLikeErrors(source, target, reportErrors) {
58383                 /**
58384                  * The spec for elaboration is:
58385                  * - If the source is a readonly tuple and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
58386                  * - If the source is a tuple then skip property elaborations if the target is an array or tuple.
58387                  * - If the source is a readonly array and the target is a mutable array or tuple, elaborate on mutability and skip property elaborations.
58388                  * - If the source an array then skip property elaborations if the target is a tuple.
58389                  */
58390                 if (isTupleType(source)) {
58391                     if (source.target.readonly && isMutableArrayOrTuple(target)) {
58392                         if (reportErrors) {
58393                             reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
58394                         }
58395                         return false;
58396                     }
58397                     return isTupleType(target) || isArrayType(target);
58398                 }
58399                 if (isReadonlyArrayType(source) && isMutableArrayOrTuple(target)) {
58400                     if (reportErrors) {
58401                         reportError(ts.Diagnostics.The_type_0_is_readonly_and_cannot_be_assigned_to_the_mutable_type_1, typeToString(source), typeToString(target));
58402                     }
58403                     return false;
58404                 }
58405                 if (isTupleType(target)) {
58406                     return isArrayType(source);
58407                 }
58408                 return true;
58409             }
58410             /**
58411              * Compare two types and return
58412              * * Ternary.True if they are related with no assumptions,
58413              * * Ternary.Maybe if they are related with assumptions of other relationships, or
58414              * * Ternary.False if they are not related.
58415              */
58416             function isRelatedTo(originalSource, originalTarget, reportErrors, headMessage, intersectionState) {
58417                 if (reportErrors === void 0) { reportErrors = false; }
58418                 if (intersectionState === void 0) { intersectionState = 0 /* None */; }
58419                 // Before normalization: if `source` is type an object type, and `target` is primitive,
58420                 // skip all the checks we don't need and just return `isSimpleTypeRelatedTo` result
58421                 if (originalSource.flags & 524288 /* Object */ && originalTarget.flags & 131068 /* Primitive */) {
58422                     if (isSimpleTypeRelatedTo(originalSource, originalTarget, relation, reportErrors ? reportError : undefined)) {
58423                         return -1 /* True */;
58424                     }
58425                     reportErrorResults(originalSource, originalTarget, 0 /* False */, !!(ts.getObjectFlags(originalSource) & 4096 /* JsxAttributes */));
58426                     return 0 /* False */;
58427                 }
58428                 // Normalize the source and target types: Turn fresh literal types into regular literal types,
58429                 // turn deferred type references into regular type references, simplify indexed access and
58430                 // conditional types, and resolve substitution types to either the substitution (on the source
58431                 // side) or the type variable (on the target side).
58432                 var source = getNormalizedType(originalSource, /*writing*/ false);
58433                 var target = getNormalizedType(originalTarget, /*writing*/ true);
58434                 if (source === target)
58435                     return -1 /* True */;
58436                 if (relation === identityRelation) {
58437                     return isIdenticalTo(source, target);
58438                 }
58439                 // We fastpath comparing a type parameter to exactly its constraint, as this is _super_ common,
58440                 // and otherwise, for type parameters in large unions, causes us to need to compare the union to itself,
58441                 // as we break down the _target_ union first, _then_ get the source constraint - so for every
58442                 // member of the target, we attempt to find a match in the source. This avoids that in cases where
58443                 // the target is exactly the constraint.
58444                 if (source.flags & 262144 /* TypeParameter */ && getConstraintOfType(source) === target) {
58445                     return -1 /* True */;
58446                 }
58447                 // Try to see if we're relating something like `Foo` -> `Bar | null | undefined`.
58448                 // If so, reporting the `null` and `undefined` in the type is hardly useful.
58449                 // First, see if we're even relating an object type to a union.
58450                 // Then see if the target is stripped down to a single non-union type.
58451                 // Note
58452                 //  * We actually want to remove null and undefined naively here (rather than using getNonNullableType),
58453                 //    since we don't want to end up with a worse error like "`Foo` is not assignable to `NonNullable<T>`"
58454                 //    when dealing with generics.
58455                 //  * We also don't deal with primitive source types, since we already halt elaboration below.
58456                 if (target.flags & 1048576 /* Union */ && source.flags & 524288 /* Object */ &&
58457                     target.types.length <= 3 && maybeTypeOfKind(target, 98304 /* Nullable */)) {
58458                     var nullStrippedTarget = extractTypesOfKind(target, ~98304 /* Nullable */);
58459                     if (!(nullStrippedTarget.flags & (1048576 /* Union */ | 131072 /* Never */))) {
58460                         if (source === nullStrippedTarget)
58461                             return -1 /* True */;
58462                         target = nullStrippedTarget;
58463                     }
58464                 }
58465                 if (relation === comparableRelation && !(target.flags & 131072 /* Never */) && isSimpleTypeRelatedTo(target, source, relation) ||
58466                     isSimpleTypeRelatedTo(source, target, relation, reportErrors ? reportError : undefined))
58467                     return -1 /* True */;
58468                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
58469                 var isPerformingExcessPropertyChecks = !(intersectionState & 2 /* Target */) && (isObjectLiteralType(source) && ts.getObjectFlags(source) & 32768 /* FreshLiteral */);
58470                 if (isPerformingExcessPropertyChecks) {
58471                     if (hasExcessProperties(source, target, reportErrors)) {
58472                         if (reportErrors) {
58473                             reportRelationError(headMessage, source, target);
58474                         }
58475                         return 0 /* False */;
58476                     }
58477                 }
58478                 var isPerformingCommonPropertyChecks = relation !== comparableRelation && !(intersectionState & 2 /* Target */) &&
58479                     source.flags & (131068 /* Primitive */ | 524288 /* Object */ | 2097152 /* Intersection */) && source !== globalObjectType &&
58480                     target.flags & (524288 /* Object */ | 2097152 /* Intersection */) && isWeakType(target) &&
58481                     (getPropertiesOfType(source).length > 0 || typeHasCallOrConstructSignatures(source));
58482                 if (isPerformingCommonPropertyChecks && !hasCommonProperties(source, target, isComparingJsxAttributes)) {
58483                     if (reportErrors) {
58484                         var calls = getSignaturesOfType(source, 0 /* Call */);
58485                         var constructs = getSignaturesOfType(source, 1 /* Construct */);
58486                         if (calls.length > 0 && isRelatedTo(getReturnTypeOfSignature(calls[0]), target, /*reportErrors*/ false) ||
58487                             constructs.length > 0 && isRelatedTo(getReturnTypeOfSignature(constructs[0]), target, /*reportErrors*/ false)) {
58488                             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));
58489                         }
58490                         else {
58491                             reportError(ts.Diagnostics.Type_0_has_no_properties_in_common_with_type_1, typeToString(source), typeToString(target));
58492                         }
58493                     }
58494                     return 0 /* False */;
58495                 }
58496                 var result = 0 /* False */;
58497                 var saveErrorInfo = captureErrorCalculationState();
58498                 // Note that these checks are specifically ordered to produce correct results. In particular,
58499                 // we need to deconstruct unions before intersections (because unions are always at the top),
58500                 // and we need to handle "each" relations before "some" relations for the same kind of type.
58501                 if (source.flags & 1048576 /* Union */) {
58502                     result = relation === comparableRelation ?
58503                         someTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState) :
58504                         eachTypeRelatedToType(source, target, reportErrors && !(source.flags & 131068 /* Primitive */), intersectionState);
58505                 }
58506                 else {
58507                     if (target.flags & 1048576 /* Union */) {
58508                         result = typeRelatedToSomeType(getRegularTypeOfObjectLiteral(source), target, reportErrors && !(source.flags & 131068 /* Primitive */) && !(target.flags & 131068 /* Primitive */));
58509                     }
58510                     else if (target.flags & 2097152 /* Intersection */) {
58511                         result = typeRelatedToEachType(getRegularTypeOfObjectLiteral(source), target, reportErrors, 2 /* Target */);
58512                     }
58513                     else if (source.flags & 2097152 /* Intersection */) {
58514                         // Check to see if any constituents of the intersection are immediately related to the target.
58515                         //
58516                         // Don't report errors though. Checking whether a constituent is related to the source is not actually
58517                         // useful and leads to some confusing error messages. Instead it is better to let the below checks
58518                         // take care of this, or to not elaborate at all. For instance,
58519                         //
58520                         //    - For an object type (such as 'C = A & B'), users are usually more interested in structural errors.
58521                         //
58522                         //    - For a union type (such as '(A | B) = (C & D)'), it's better to hold onto the whole intersection
58523                         //          than to report that 'D' is not assignable to 'A' or 'B'.
58524                         //
58525                         //    - For a primitive type or type parameter (such as 'number = A & B') there is no point in
58526                         //          breaking the intersection apart.
58527                         result = someTypeRelatedToType(source, target, /*reportErrors*/ false, 1 /* Source */);
58528                     }
58529                     if (!result && (source.flags & 469499904 /* StructuredOrInstantiable */ || target.flags & 469499904 /* StructuredOrInstantiable */)) {
58530                         if (result = recursiveTypeRelatedTo(source, target, reportErrors, intersectionState)) {
58531                             resetErrorInfo(saveErrorInfo);
58532                         }
58533                     }
58534                 }
58535                 if (!result && source.flags & (2097152 /* Intersection */ | 262144 /* TypeParameter */)) {
58536                     // The combined constraint of an intersection type is the intersection of the constraints of
58537                     // the constituents. When an intersection type contains instantiable types with union type
58538                     // constraints, there are situations where we need to examine the combined constraint. One is
58539                     // when the target is a union type. Another is when the intersection contains types belonging
58540                     // to one of the disjoint domains. For example, given type variables T and U, each with the
58541                     // constraint 'string | number', the combined constraint of 'T & U' is 'string | number' and
58542                     // we need to check this constraint against a union on the target side. Also, given a type
58543                     // variable V constrained to 'string | number', 'V & number' has a combined constraint of
58544                     // 'string & number | number & number' which reduces to just 'number'.
58545                     // This also handles type parameters, as a type parameter with a union constraint compared against a union
58546                     // needs to have its constraint hoisted into an intersection with said type parameter, this way
58547                     // the type param can be compared with itself in the target (with the influence of its constraint to match other parts)
58548                     // For example, if `T extends 1 | 2` and `U extends 2 | 3` and we compare `T & U` to `T & U & (1 | 2 | 3)`
58549                     var constraint = getEffectiveConstraintOfIntersection(source.flags & 2097152 /* Intersection */ ? source.types : [source], !!(target.flags & 1048576 /* Union */));
58550                     if (constraint && (source.flags & 2097152 /* Intersection */ || target.flags & 1048576 /* Union */)) {
58551                         if (everyType(constraint, function (c) { return c !== source; })) { // Skip comparison if expansion contains the source itself
58552                             // TODO: Stack errors so we get a pyramid for the "normal" comparison above, _and_ a second for this
58553                             if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
58554                                 resetErrorInfo(saveErrorInfo);
58555                             }
58556                         }
58557                     }
58558                 }
58559                 // For certain combinations involving intersections and optional, excess, or mismatched properties we need
58560                 // an extra property check where the intersection is viewed as a single object. The following are motivating
58561                 // examples that all should be errors, but aren't without this extra property check:
58562                 //
58563                 //   let obj: { a: { x: string } } & { c: number } = { a: { x: 'hello', y: 2 }, c: 5 };  // Nested excess property
58564                 //
58565                 //   declare let wrong: { a: { y: string } };
58566                 //   let weak: { a?: { x?: number } } & { c?: string } = wrong;  // Nested weak object type
58567                 //
58568                 //   function foo<T extends object>(x: { a?: string }, y: T & { a: boolean }) {
58569                 //     x = y;  // Mismatched property in source intersection
58570                 //   }
58571                 //
58572                 // We suppress recursive intersection property checks because they can generate lots of work when relating
58573                 // recursive intersections that are structurally similar but not exactly identical. See #37854.
58574                 if (result && !inPropertyCheck && (target.flags & 2097152 /* Intersection */ && (isPerformingExcessPropertyChecks || isPerformingCommonPropertyChecks) ||
58575                     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 */); }))) {
58576                     inPropertyCheck = true;
58577                     result &= recursiveTypeRelatedTo(source, target, reportErrors, 4 /* PropertyCheck */);
58578                     inPropertyCheck = false;
58579                 }
58580                 reportErrorResults(source, target, result, isComparingJsxAttributes);
58581                 return result;
58582                 function reportErrorResults(source, target, result, isComparingJsxAttributes) {
58583                     if (!result && reportErrors) {
58584                         source = originalSource.aliasSymbol ? originalSource : source;
58585                         target = originalTarget.aliasSymbol ? originalTarget : target;
58586                         var maybeSuppress = overrideNextErrorInfo > 0;
58587                         if (maybeSuppress) {
58588                             overrideNextErrorInfo--;
58589                         }
58590                         if (source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */) {
58591                             var currentError = errorInfo;
58592                             tryElaborateArrayLikeErrors(source, target, reportErrors);
58593                             if (errorInfo !== currentError) {
58594                                 maybeSuppress = !!errorInfo;
58595                             }
58596                         }
58597                         if (source.flags & 524288 /* Object */ && target.flags & 131068 /* Primitive */) {
58598                             tryElaborateErrorsForPrimitivesAndObjects(source, target);
58599                         }
58600                         else if (source.symbol && source.flags & 524288 /* Object */ && globalObjectType === source) {
58601                             reportError(ts.Diagnostics.The_Object_type_is_assignable_to_very_few_other_types_Did_you_mean_to_use_the_any_type_instead);
58602                         }
58603                         else if (isComparingJsxAttributes && target.flags & 2097152 /* Intersection */) {
58604                             var targetTypes = target.types;
58605                             var intrinsicAttributes = getJsxType(JsxNames.IntrinsicAttributes, errorNode);
58606                             var intrinsicClassAttributes = getJsxType(JsxNames.IntrinsicClassAttributes, errorNode);
58607                             if (intrinsicAttributes !== errorType && intrinsicClassAttributes !== errorType &&
58608                                 (ts.contains(targetTypes, intrinsicAttributes) || ts.contains(targetTypes, intrinsicClassAttributes))) {
58609                                 // do not report top error
58610                                 return result;
58611                             }
58612                         }
58613                         else {
58614                             errorInfo = elaborateNeverIntersection(errorInfo, originalTarget);
58615                         }
58616                         if (!headMessage && maybeSuppress) {
58617                             lastSkippedInfo = [source, target];
58618                             // Used by, eg, missing property checking to replace the top-level message with a more informative one
58619                             return result;
58620                         }
58621                         reportRelationError(headMessage, source, target);
58622                     }
58623                 }
58624             }
58625             function isIdenticalTo(source, target) {
58626                 var flags = source.flags & target.flags;
58627                 if (!(flags & 469237760 /* Substructure */)) {
58628                     return 0 /* False */;
58629                 }
58630                 if (flags & 3145728 /* UnionOrIntersection */) {
58631                     var result_6 = eachTypeRelatedToSomeType(source, target);
58632                     if (result_6) {
58633                         result_6 &= eachTypeRelatedToSomeType(target, source);
58634                     }
58635                     return result_6;
58636                 }
58637                 return recursiveTypeRelatedTo(source, target, /*reportErrors*/ false, 0 /* None */);
58638             }
58639             function getTypeOfPropertyInTypes(types, name) {
58640                 var appendPropType = function (propTypes, type) {
58641                     type = getApparentType(type);
58642                     var prop = type.flags & 3145728 /* UnionOrIntersection */ ? getPropertyOfUnionOrIntersectionType(type, name) : getPropertyOfObjectType(type, name);
58643                     var propType = prop && getTypeOfSymbol(prop) || isNumericLiteralName(name) && getIndexTypeOfType(type, 1 /* Number */) || getIndexTypeOfType(type, 0 /* String */) || undefinedType;
58644                     return ts.append(propTypes, propType);
58645                 };
58646                 return getUnionType(ts.reduceLeft(types, appendPropType, /*initial*/ undefined) || ts.emptyArray);
58647             }
58648             function hasExcessProperties(source, target, reportErrors) {
58649                 if (!isExcessPropertyCheckTarget(target) || !noImplicitAny && ts.getObjectFlags(target) & 16384 /* JSLiteral */) {
58650                     return false; // Disable excess property checks on JS literals to simulate having an implicit "index signature" - but only outside of noImplicitAny
58651                 }
58652                 var isComparingJsxAttributes = !!(ts.getObjectFlags(source) & 4096 /* JsxAttributes */);
58653                 if ((relation === assignableRelation || relation === comparableRelation) &&
58654                     (isTypeSubsetOf(globalObjectType, target) || (!isComparingJsxAttributes && isEmptyObjectType(target)))) {
58655                     return false;
58656                 }
58657                 var reducedTarget = target;
58658                 var checkTypes;
58659                 if (target.flags & 1048576 /* Union */) {
58660                     reducedTarget = findMatchingDiscriminantType(source, target, isRelatedTo) || filterPrimitivesIfContainsNonPrimitive(target);
58661                     checkTypes = reducedTarget.flags & 1048576 /* Union */ ? reducedTarget.types : [reducedTarget];
58662                 }
58663                 var _loop_16 = function (prop) {
58664                     if (shouldCheckAsExcessProperty(prop, source.symbol) && !isIgnoredJsxProperty(source, prop)) {
58665                         if (!isKnownProperty(reducedTarget, prop.escapedName, isComparingJsxAttributes)) {
58666                             if (reportErrors) {
58667                                 // Report error in terms of object types in the target as those are the only ones
58668                                 // we check in isKnownProperty.
58669                                 var errorTarget = filterType(reducedTarget, isExcessPropertyCheckTarget);
58670                                 // We know *exactly* where things went wrong when comparing the types.
58671                                 // Use this property as the error node as this will be more helpful in
58672                                 // reasoning about what went wrong.
58673                                 if (!errorNode)
58674                                     return { value: ts.Debug.fail() };
58675                                 if (ts.isJsxAttributes(errorNode) || ts.isJsxOpeningLikeElement(errorNode) || ts.isJsxOpeningLikeElement(errorNode.parent)) {
58676                                     // JsxAttributes has an object-literal flag and undergo same type-assignablity check as normal object-literal.
58677                                     // However, using an object-literal error message will be very confusing to the users so we give different a message.
58678                                     if (prop.valueDeclaration && ts.isJsxAttribute(prop.valueDeclaration) && ts.getSourceFileOfNode(errorNode) === ts.getSourceFileOfNode(prop.valueDeclaration.name)) {
58679                                         // Note that extraneous children (as in `<NoChild>extra</NoChild>`) don't pass this check,
58680                                         // since `children` is a SyntaxKind.PropertySignature instead of a SyntaxKind.JsxAttribute.
58681                                         errorNode = prop.valueDeclaration.name;
58682                                     }
58683                                     var propName = symbolToString(prop);
58684                                     var suggestionSymbol = getSuggestedSymbolForNonexistentJSXAttribute(propName, errorTarget);
58685                                     var suggestion = suggestionSymbol ? symbolToString(suggestionSymbol) : undefined;
58686                                     if (suggestion) {
58687                                         reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, propName, typeToString(errorTarget), suggestion);
58688                                     }
58689                                     else {
58690                                         reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, propName, typeToString(errorTarget));
58691                                     }
58692                                 }
58693                                 else {
58694                                     // use the property's value declaration if the property is assigned inside the literal itself
58695                                     var objectLiteralDeclaration_1 = source.symbol && ts.firstOrUndefined(source.symbol.declarations);
58696                                     var suggestion = void 0;
58697                                     if (prop.valueDeclaration && ts.findAncestor(prop.valueDeclaration, function (d) { return d === objectLiteralDeclaration_1; }) && ts.getSourceFileOfNode(objectLiteralDeclaration_1) === ts.getSourceFileOfNode(errorNode)) {
58698                                         var propDeclaration = prop.valueDeclaration;
58699                                         ts.Debug.assertNode(propDeclaration, ts.isObjectLiteralElementLike);
58700                                         errorNode = propDeclaration;
58701                                         var name = propDeclaration.name;
58702                                         if (ts.isIdentifier(name)) {
58703                                             suggestion = getSuggestionForNonexistentProperty(name, errorTarget);
58704                                         }
58705                                     }
58706                                     if (suggestion !== undefined) {
58707                                         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);
58708                                     }
58709                                     else {
58710                                         reportError(ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(prop), typeToString(errorTarget));
58711                                     }
58712                                 }
58713                             }
58714                             return { value: true };
58715                         }
58716                         if (checkTypes && !isRelatedTo(getTypeOfSymbol(prop), getTypeOfPropertyInTypes(checkTypes, prop.escapedName), reportErrors)) {
58717                             if (reportErrors) {
58718                                 reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(prop));
58719                             }
58720                             return { value: true };
58721                         }
58722                     }
58723                 };
58724                 for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
58725                     var prop = _a[_i];
58726                     var state_5 = _loop_16(prop);
58727                     if (typeof state_5 === "object")
58728                         return state_5.value;
58729                 }
58730                 return false;
58731             }
58732             function shouldCheckAsExcessProperty(prop, container) {
58733                 return prop.valueDeclaration && container.valueDeclaration && prop.valueDeclaration.parent === container.valueDeclaration;
58734             }
58735             function eachTypeRelatedToSomeType(source, target) {
58736                 var result = -1 /* True */;
58737                 var sourceTypes = source.types;
58738                 for (var _i = 0, sourceTypes_1 = sourceTypes; _i < sourceTypes_1.length; _i++) {
58739                     var sourceType = sourceTypes_1[_i];
58740                     var related = typeRelatedToSomeType(sourceType, target, /*reportErrors*/ false);
58741                     if (!related) {
58742                         return 0 /* False */;
58743                     }
58744                     result &= related;
58745                 }
58746                 return result;
58747             }
58748             function typeRelatedToSomeType(source, target, reportErrors) {
58749                 var targetTypes = target.types;
58750                 if (target.flags & 1048576 /* Union */ && containsType(targetTypes, source)) {
58751                     return -1 /* True */;
58752                 }
58753                 for (var _i = 0, targetTypes_1 = targetTypes; _i < targetTypes_1.length; _i++) {
58754                     var type = targetTypes_1[_i];
58755                     var related = isRelatedTo(source, type, /*reportErrors*/ false);
58756                     if (related) {
58757                         return related;
58758                     }
58759                 }
58760                 if (reportErrors) {
58761                     var bestMatchingType = getBestMatchingType(source, target, isRelatedTo);
58762                     isRelatedTo(source, bestMatchingType || targetTypes[targetTypes.length - 1], /*reportErrors*/ true);
58763                 }
58764                 return 0 /* False */;
58765             }
58766             function typeRelatedToEachType(source, target, reportErrors, intersectionState) {
58767                 var result = -1 /* True */;
58768                 var targetTypes = target.types;
58769                 for (var _i = 0, targetTypes_2 = targetTypes; _i < targetTypes_2.length; _i++) {
58770                     var targetType = targetTypes_2[_i];
58771                     var related = isRelatedTo(source, targetType, reportErrors, /*headMessage*/ undefined, intersectionState);
58772                     if (!related) {
58773                         return 0 /* False */;
58774                     }
58775                     result &= related;
58776                 }
58777                 return result;
58778             }
58779             function someTypeRelatedToType(source, target, reportErrors, intersectionState) {
58780                 var sourceTypes = source.types;
58781                 if (source.flags & 1048576 /* Union */ && containsType(sourceTypes, target)) {
58782                     return -1 /* True */;
58783                 }
58784                 var len = sourceTypes.length;
58785                 for (var i = 0; i < len; i++) {
58786                     var related = isRelatedTo(sourceTypes[i], target, reportErrors && i === len - 1, /*headMessage*/ undefined, intersectionState);
58787                     if (related) {
58788                         return related;
58789                     }
58790                 }
58791                 return 0 /* False */;
58792             }
58793             function eachTypeRelatedToType(source, target, reportErrors, intersectionState) {
58794                 var result = -1 /* True */;
58795                 var sourceTypes = source.types;
58796                 for (var i = 0; i < sourceTypes.length; i++) {
58797                     var sourceType = sourceTypes[i];
58798                     if (target.flags & 1048576 /* Union */ && target.types.length === sourceTypes.length) {
58799                         // many unions are mappings of one another; in such cases, simply comparing members at the same index can shortcut the comparison
58800                         var related_1 = isRelatedTo(sourceType, target.types[i], /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState);
58801                         if (related_1) {
58802                             result &= related_1;
58803                             continue;
58804                         }
58805                     }
58806                     var related = isRelatedTo(sourceType, target, reportErrors, /*headMessage*/ undefined, intersectionState);
58807                     if (!related) {
58808                         return 0 /* False */;
58809                     }
58810                     result &= related;
58811                 }
58812                 return result;
58813             }
58814             function typeArgumentsRelatedTo(sources, targets, variances, reportErrors, intersectionState) {
58815                 if (sources === void 0) { sources = ts.emptyArray; }
58816                 if (targets === void 0) { targets = ts.emptyArray; }
58817                 if (variances === void 0) { variances = ts.emptyArray; }
58818                 if (sources.length !== targets.length && relation === identityRelation) {
58819                     return 0 /* False */;
58820                 }
58821                 var length = sources.length <= targets.length ? sources.length : targets.length;
58822                 var result = -1 /* True */;
58823                 for (var i = 0; i < length; i++) {
58824                     // When variance information isn't available we default to covariance. This happens
58825                     // in the process of computing variance information for recursive types and when
58826                     // comparing 'this' type arguments.
58827                     var varianceFlags = i < variances.length ? variances[i] : 1 /* Covariant */;
58828                     var variance = varianceFlags & 7 /* VarianceMask */;
58829                     // We ignore arguments for independent type parameters (because they're never witnessed).
58830                     if (variance !== 4 /* Independent */) {
58831                         var s = sources[i];
58832                         var t = targets[i];
58833                         var related = -1 /* True */;
58834                         if (varianceFlags & 8 /* Unmeasurable */) {
58835                             // Even an `Unmeasurable` variance works out without a structural check if the source and target are _identical_.
58836                             // We can't simply assume invariance, because `Unmeasurable` marks nonlinear relations, for example, a relation tained by
58837                             // the `-?` modifier in a mapped type (where, no matter how the inputs are related, the outputs still might not be)
58838                             related = relation === identityRelation ? isRelatedTo(s, t, /*reportErrors*/ false) : compareTypesIdentical(s, t);
58839                         }
58840                         else if (variance === 1 /* Covariant */) {
58841                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
58842                         }
58843                         else if (variance === 2 /* Contravariant */) {
58844                             related = isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
58845                         }
58846                         else if (variance === 3 /* Bivariant */) {
58847                             // In the bivariant case we first compare contravariantly without reporting
58848                             // errors. Then, if that doesn't succeed, we compare covariantly with error
58849                             // reporting. Thus, error elaboration will be based on the the covariant check,
58850                             // which is generally easier to reason about.
58851                             related = isRelatedTo(t, s, /*reportErrors*/ false);
58852                             if (!related) {
58853                                 related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
58854                             }
58855                         }
58856                         else {
58857                             // In the invariant case we first compare covariantly, and only when that
58858                             // succeeds do we proceed to compare contravariantly. Thus, error elaboration
58859                             // will typically be based on the covariant check.
58860                             related = isRelatedTo(s, t, reportErrors, /*headMessage*/ undefined, intersectionState);
58861                             if (related) {
58862                                 related &= isRelatedTo(t, s, reportErrors, /*headMessage*/ undefined, intersectionState);
58863                             }
58864                         }
58865                         if (!related) {
58866                             return 0 /* False */;
58867                         }
58868                         result &= related;
58869                     }
58870                 }
58871                 return result;
58872             }
58873             // Determine if possibly recursive types are related. First, check if the result is already available in the global cache.
58874             // Second, check if we have already started a comparison of the given two types in which case we assume the result to be true.
58875             // Third, check if both types are part of deeply nested chains of generic type instantiations and if so assume the types are
58876             // equal and infinitely expanding. Fourth, if we have reached a depth of 100 nested comparisons, assume we have runaway recursion
58877             // and issue an error. Otherwise, actually compare the structure of the two types.
58878             function recursiveTypeRelatedTo(source, target, reportErrors, intersectionState) {
58879                 if (overflow) {
58880                     return 0 /* False */;
58881                 }
58882                 var id = getRelationKey(source, target, intersectionState | (inPropertyCheck ? 8 /* InPropertyCheck */ : 0), relation);
58883                 var entry = relation.get(id);
58884                 if (entry !== undefined) {
58885                     if (reportErrors && entry & 2 /* Failed */ && !(entry & 4 /* Reported */)) {
58886                         // We are elaborating errors and the cached result is an unreported failure. The result will be reported
58887                         // as a failure, and should be updated as a reported failure by the bottom of this function.
58888                     }
58889                     else {
58890                         if (outofbandVarianceMarkerHandler) {
58891                             // We're in the middle of variance checking - integrate any unmeasurable/unreliable flags from this cached component
58892                             var saved = entry & 24 /* ReportsMask */;
58893                             if (saved & 8 /* ReportsUnmeasurable */) {
58894                                 instantiateType(source, makeFunctionTypeMapper(reportUnmeasurableMarkers));
58895                             }
58896                             if (saved & 16 /* ReportsUnreliable */) {
58897                                 instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers));
58898                             }
58899                         }
58900                         return entry & 1 /* Succeeded */ ? -1 /* True */ : 0 /* False */;
58901                     }
58902                 }
58903                 if (!maybeKeys) {
58904                     maybeKeys = [];
58905                     sourceStack = [];
58906                     targetStack = [];
58907                 }
58908                 else {
58909                     for (var i = 0; i < maybeCount; i++) {
58910                         // If source and target are already being compared, consider them related with assumptions
58911                         if (id === maybeKeys[i]) {
58912                             return 3 /* Maybe */;
58913                         }
58914                     }
58915                     if (depth === 100) {
58916                         overflow = true;
58917                         return 0 /* False */;
58918                     }
58919                 }
58920                 var maybeStart = maybeCount;
58921                 maybeKeys[maybeCount] = id;
58922                 maybeCount++;
58923                 sourceStack[depth] = source;
58924                 targetStack[depth] = target;
58925                 depth++;
58926                 var saveExpandingFlags = expandingFlags;
58927                 if (!(expandingFlags & 1 /* Source */) && isDeeplyNestedType(source, sourceStack, depth))
58928                     expandingFlags |= 1 /* Source */;
58929                 if (!(expandingFlags & 2 /* Target */) && isDeeplyNestedType(target, targetStack, depth))
58930                     expandingFlags |= 2 /* Target */;
58931                 var originalHandler;
58932                 var propagatingVarianceFlags = 0;
58933                 if (outofbandVarianceMarkerHandler) {
58934                     originalHandler = outofbandVarianceMarkerHandler;
58935                     outofbandVarianceMarkerHandler = function (onlyUnreliable) {
58936                         propagatingVarianceFlags |= onlyUnreliable ? 16 /* ReportsUnreliable */ : 8 /* ReportsUnmeasurable */;
58937                         return originalHandler(onlyUnreliable);
58938                     };
58939                 }
58940                 if (expandingFlags === 3 /* Both */) {
58941                     ts.tracing.instant("check" /* Check */, "recursiveTypeRelatedTo_DepthLimit", {
58942                         sourceId: source.id,
58943                         sourceIdStack: sourceStack.map(function (t) { return t.id; }),
58944                         targetId: target.id,
58945                         targetIdStack: targetStack.map(function (t) { return t.id; }),
58946                         depth: depth,
58947                     });
58948                 }
58949                 var result = expandingFlags !== 3 /* Both */ ? structuredTypeRelatedTo(source, target, reportErrors, intersectionState) : 3 /* Maybe */;
58950                 if (outofbandVarianceMarkerHandler) {
58951                     outofbandVarianceMarkerHandler = originalHandler;
58952                 }
58953                 expandingFlags = saveExpandingFlags;
58954                 depth--;
58955                 if (result) {
58956                     if (result === -1 /* True */ || depth === 0) {
58957                         if (result === -1 /* True */ || result === 3 /* Maybe */) {
58958                             // If result is definitely true, record all maybe keys as having succeeded. Also, record Ternary.Maybe
58959                             // results as having succeeded once we reach depth 0, but never record Ternary.Unknown results.
58960                             for (var i = maybeStart; i < maybeCount; i++) {
58961                                 relation.set(maybeKeys[i], 1 /* Succeeded */ | propagatingVarianceFlags);
58962                             }
58963                         }
58964                         maybeCount = maybeStart;
58965                     }
58966                 }
58967                 else {
58968                     // A false result goes straight into global cache (when something is false under
58969                     // assumptions it will also be false without assumptions)
58970                     relation.set(id, (reportErrors ? 4 /* Reported */ : 0) | 2 /* Failed */ | propagatingVarianceFlags);
58971                     maybeCount = maybeStart;
58972                 }
58973                 return result;
58974             }
58975             function structuredTypeRelatedTo(source, target, reportErrors, intersectionState) {
58976                 ts.tracing.push("check" /* Check */, "structuredTypeRelatedTo", { sourceId: source.id, targetId: target.id });
58977                 var result = structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState);
58978                 ts.tracing.pop();
58979                 return result;
58980             }
58981             function structuredTypeRelatedToWorker(source, target, reportErrors, intersectionState) {
58982                 if (intersectionState & 4 /* PropertyCheck */) {
58983                     return propertiesRelatedTo(source, target, reportErrors, /*excludedProperties*/ undefined, 0 /* None */);
58984                 }
58985                 var flags = source.flags & target.flags;
58986                 if (relation === identityRelation && !(flags & 524288 /* Object */)) {
58987                     if (flags & 4194304 /* Index */) {
58988                         return isRelatedTo(source.type, target.type, /*reportErrors*/ false);
58989                     }
58990                     var result_7 = 0 /* False */;
58991                     if (flags & 8388608 /* IndexedAccess */) {
58992                         if (result_7 = isRelatedTo(source.objectType, target.objectType, /*reportErrors*/ false)) {
58993                             if (result_7 &= isRelatedTo(source.indexType, target.indexType, /*reportErrors*/ false)) {
58994                                 return result_7;
58995                             }
58996                         }
58997                     }
58998                     if (flags & 16777216 /* Conditional */) {
58999                         if (source.root.isDistributive === target.root.isDistributive) {
59000                             if (result_7 = isRelatedTo(source.checkType, target.checkType, /*reportErrors*/ false)) {
59001                                 if (result_7 &= isRelatedTo(source.extendsType, target.extendsType, /*reportErrors*/ false)) {
59002                                     if (result_7 &= isRelatedTo(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target), /*reportErrors*/ false)) {
59003                                         if (result_7 &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), /*reportErrors*/ false)) {
59004                                             return result_7;
59005                                         }
59006                                     }
59007                                 }
59008                             }
59009                         }
59010                     }
59011                     if (flags & 33554432 /* Substitution */) {
59012                         return isRelatedTo(source.substitute, target.substitute, /*reportErrors*/ false);
59013                     }
59014                     return 0 /* False */;
59015                 }
59016                 var result;
59017                 var originalErrorInfo;
59018                 var varianceCheckFailed = false;
59019                 var saveErrorInfo = captureErrorCalculationState();
59020                 // We limit alias variance probing to only object and conditional types since their alias behavior
59021                 // is more predictable than other, interned types, which may or may not have an alias depending on
59022                 // the order in which things were checked.
59023                 if (source.flags & (524288 /* Object */ | 16777216 /* Conditional */) && source.aliasSymbol &&
59024                     source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol &&
59025                     !(source.aliasTypeArgumentsContainsMarker || target.aliasTypeArgumentsContainsMarker)) {
59026                     var variances = getAliasVariances(source.aliasSymbol);
59027                     if (variances === ts.emptyArray) {
59028                         return 1 /* Unknown */;
59029                     }
59030                     var varianceResult = relateVariances(source.aliasTypeArguments, target.aliasTypeArguments, variances, intersectionState);
59031                     if (varianceResult !== undefined) {
59032                         return varianceResult;
59033                     }
59034                 }
59035                 // For a generic type T and a type U that is assignable to T, [...U] is assignable to T, U is assignable to readonly [...T],
59036                 // and U is assignable to [...T] when U is constrained to a mutable array or tuple type.
59037                 if (isSingleElementGenericTupleType(source) && !source.target.readonly && (result = isRelatedTo(getTypeArguments(source)[0], target)) ||
59038                     isSingleElementGenericTupleType(target) && (target.target.readonly || isMutableArrayOrTuple(getBaseConstraintOfType(source) || source)) && (result = isRelatedTo(source, getTypeArguments(target)[0]))) {
59039                     return result;
59040                 }
59041                 if (target.flags & 262144 /* TypeParameter */) {
59042                     // 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].
59043                     if (ts.getObjectFlags(source) & 32 /* Mapped */ && !source.declaration.nameType && isRelatedTo(getIndexType(target), getConstraintTypeFromMappedType(source))) {
59044                         if (!(getMappedTypeModifiers(source) & 4 /* IncludeOptional */)) {
59045                             var templateType = getTemplateTypeFromMappedType(source);
59046                             var indexedAccessType = getIndexedAccessType(target, getTypeParameterFromMappedType(source));
59047                             if (result = isRelatedTo(templateType, indexedAccessType, reportErrors)) {
59048                                 return result;
59049                             }
59050                         }
59051                     }
59052                 }
59053                 else if (target.flags & 4194304 /* Index */) {
59054                     var targetType = target.type;
59055                     // A keyof S is related to a keyof T if T is related to S.
59056                     if (source.flags & 4194304 /* Index */) {
59057                         if (result = isRelatedTo(targetType, source.type, /*reportErrors*/ false)) {
59058                             return result;
59059                         }
59060                     }
59061                     if (isTupleType(targetType)) {
59062                         // An index type can have a tuple type target when the tuple type contains variadic elements.
59063                         // Check if the source is related to the known keys of the tuple type.
59064                         if (result = isRelatedTo(source, getKnownKeysOfTupleType(targetType), reportErrors)) {
59065                             return result;
59066                         }
59067                     }
59068                     else {
59069                         // A type S is assignable to keyof T if S is assignable to keyof C, where C is the
59070                         // simplified form of T or, if T doesn't simplify, the constraint of T.
59071                         var constraint = getSimplifiedTypeOrConstraint(targetType);
59072                         if (constraint) {
59073                             // We require Ternary.True here such that circular constraints don't cause
59074                             // false positives. For example, given 'T extends { [K in keyof T]: string }',
59075                             // 'keyof T' has itself as its constraint and produces a Ternary.Maybe when
59076                             // related to other types.
59077                             if (isRelatedTo(source, getIndexType(constraint, target.stringsOnly), reportErrors) === -1 /* True */) {
59078                                 return -1 /* True */;
59079                             }
59080                         }
59081                     }
59082                 }
59083                 else if (target.flags & 8388608 /* IndexedAccess */) {
59084                     // A type S is related to a type T[K] if S is related to C, where C is the base
59085                     // constraint of T[K] for writing.
59086                     if (relation === assignableRelation || relation === comparableRelation) {
59087                         var objectType = target.objectType;
59088                         var indexType = target.indexType;
59089                         var baseObjectType = getBaseConstraintOfType(objectType) || objectType;
59090                         var baseIndexType = getBaseConstraintOfType(indexType) || indexType;
59091                         if (!isGenericObjectType(baseObjectType) && !isGenericIndexType(baseIndexType)) {
59092                             var accessFlags = 2 /* Writing */ | (baseObjectType !== objectType ? 1 /* NoIndexSignatures */ : 0);
59093                             var constraint = getIndexedAccessTypeOrUndefined(baseObjectType, baseIndexType, target.noUncheckedIndexedAccessCandidate, /*accessNode*/ undefined, accessFlags);
59094                             if (constraint && (result = isRelatedTo(source, constraint, reportErrors))) {
59095                                 return result;
59096                             }
59097                         }
59098                     }
59099                 }
59100                 else if (isGenericMappedType(target) && !target.declaration.nameType) {
59101                     // A source type T is related to a target type { [P in X]: T[P] }
59102                     var template = getTemplateTypeFromMappedType(target);
59103                     var modifiers = getMappedTypeModifiers(target);
59104                     if (!(modifiers & 8 /* ExcludeOptional */)) {
59105                         if (template.flags & 8388608 /* IndexedAccess */ && template.objectType === source &&
59106                             template.indexType === getTypeParameterFromMappedType(target)) {
59107                             return -1 /* True */;
59108                         }
59109                         if (!isGenericMappedType(source)) {
59110                             var targetConstraint = getConstraintTypeFromMappedType(target);
59111                             var sourceKeys = getIndexType(source, /*stringsOnly*/ undefined, /*noIndexSignatures*/ true);
59112                             var includeOptional = modifiers & 4 /* IncludeOptional */;
59113                             var filteredByApplicability = includeOptional ? intersectTypes(targetConstraint, sourceKeys) : undefined;
59114                             // 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.
59115                             // 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.
59116                             if (includeOptional
59117                                 ? !(filteredByApplicability.flags & 131072 /* Never */)
59118                                 : isRelatedTo(targetConstraint, sourceKeys)) {
59119                                 var templateType = getTemplateTypeFromMappedType(target);
59120                                 var typeParameter = getTypeParameterFromMappedType(target);
59121                                 // Fastpath: When the template has the form Obj[P] where P is the mapped type parameter, directly compare `source` with `Obj`
59122                                 // to avoid creating the (potentially very large) number of new intermediate types made by manufacturing `source[P]`
59123                                 var nonNullComponent = extractTypesOfKind(templateType, ~98304 /* Nullable */);
59124                                 if (nonNullComponent.flags & 8388608 /* IndexedAccess */ && nonNullComponent.indexType === typeParameter) {
59125                                     if (result = isRelatedTo(source, nonNullComponent.objectType, reportErrors)) {
59126                                         return result;
59127                                     }
59128                                 }
59129                                 else {
59130                                     var indexingType = filteredByApplicability ? getIntersectionType([filteredByApplicability, typeParameter]) : typeParameter;
59131                                     var indexedAccessType = getIndexedAccessType(source, indexingType);
59132                                     if (result = isRelatedTo(indexedAccessType, templateType, reportErrors)) {
59133                                         return result;
59134                                     }
59135                                 }
59136                             }
59137                             originalErrorInfo = errorInfo;
59138                             resetErrorInfo(saveErrorInfo);
59139                         }
59140                     }
59141                 }
59142                 else if (target.flags & 134217728 /* TemplateLiteral */ && source.flags & 128 /* StringLiteral */) {
59143                     if (isPatternLiteralType(target)) {
59144                         // match all non-`string` segments
59145                         var result_8 = inferLiteralsFromTemplateLiteralType(source, target);
59146                         if (result_8 && ts.every(result_8, function (r, i) { return isStringLiteralTypeValueParsableAsType(r, target.types[i]); })) {
59147                             return -1 /* True */;
59148                         }
59149                     }
59150                 }
59151                 if (source.flags & 8650752 /* TypeVariable */) {
59152                     if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
59153                         // A type S[K] is related to a type T[J] if S is related to T and K is related to J.
59154                         if (result = isRelatedTo(source.objectType, target.objectType, reportErrors)) {
59155                             result &= isRelatedTo(source.indexType, target.indexType, reportErrors);
59156                         }
59157                         if (result) {
59158                             resetErrorInfo(saveErrorInfo);
59159                             return result;
59160                         }
59161                     }
59162                     else {
59163                         var constraint = getConstraintOfType(source);
59164                         if (!constraint || (source.flags & 262144 /* TypeParameter */ && constraint.flags & 1 /* Any */)) {
59165                             // A type variable with no constraint is not related to the non-primitive object type.
59166                             if (result = isRelatedTo(emptyObjectType, extractTypesOfKind(target, ~67108864 /* NonPrimitive */))) {
59167                                 resetErrorInfo(saveErrorInfo);
59168                                 return result;
59169                             }
59170                         }
59171                         // 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
59172                         else if (result = isRelatedTo(constraint, target, /*reportErrors*/ false, /*headMessage*/ undefined, intersectionState)) {
59173                             resetErrorInfo(saveErrorInfo);
59174                             return result;
59175                         }
59176                         // slower, fuller, this-instantiated check (necessary when comparing raw `this` types from base classes), see `subclassWithPolymorphicThisIsAssignable.ts` test for example
59177                         else if (result = isRelatedTo(getTypeWithThisArgument(constraint, source), target, reportErrors, /*headMessage*/ undefined, intersectionState)) {
59178                             resetErrorInfo(saveErrorInfo);
59179                             return result;
59180                         }
59181                     }
59182                 }
59183                 else if (source.flags & 4194304 /* Index */) {
59184                     if (result = isRelatedTo(keyofConstraintType, target, reportErrors)) {
59185                         resetErrorInfo(saveErrorInfo);
59186                         return result;
59187                     }
59188                 }
59189                 else if (source.flags & 134217728 /* TemplateLiteral */) {
59190                     if (target.flags & 134217728 /* TemplateLiteral */ &&
59191                         source.texts.length === target.texts.length &&
59192                         source.types.length === target.types.length &&
59193                         ts.every(source.texts, function (t, i) { return t === target.texts[i]; }) &&
59194                         ts.every(instantiateType(source, makeFunctionTypeMapper(reportUnreliableMarkers)).types, function (t, i) { return !!(target.types[i].flags & (1 /* Any */ | 4 /* String */)) || !!isRelatedTo(t, target.types[i], /*reportErrors*/ false); })) {
59195                         return -1 /* True */;
59196                     }
59197                     var constraint = getBaseConstraintOfType(source);
59198                     if (constraint && constraint !== source && (result = isRelatedTo(constraint, target, reportErrors))) {
59199                         resetErrorInfo(saveErrorInfo);
59200                         return result;
59201                     }
59202                 }
59203                 else if (source.flags & 268435456 /* StringMapping */) {
59204                     if (target.flags & 268435456 /* StringMapping */ && source.symbol === target.symbol) {
59205                         if (result = isRelatedTo(source.type, target.type, reportErrors)) {
59206                             resetErrorInfo(saveErrorInfo);
59207                             return result;
59208                         }
59209                     }
59210                     else {
59211                         var constraint = getBaseConstraintOfType(source);
59212                         if (constraint && (result = isRelatedTo(constraint, target, reportErrors))) {
59213                             resetErrorInfo(saveErrorInfo);
59214                             return result;
59215                         }
59216                     }
59217                 }
59218                 else if (source.flags & 16777216 /* Conditional */) {
59219                     if (target.flags & 16777216 /* Conditional */) {
59220                         // Two conditional types 'T1 extends U1 ? X1 : Y1' and 'T2 extends U2 ? X2 : Y2' are related if
59221                         // one of T1 and T2 is related to the other, U1 and U2 are identical types, X1 is related to X2,
59222                         // and Y1 is related to Y2.
59223                         var sourceParams = source.root.inferTypeParameters;
59224                         var sourceExtends = source.extendsType;
59225                         var mapper = void 0;
59226                         if (sourceParams) {
59227                             // If the source has infer type parameters, we instantiate them in the context of the target
59228                             var ctx = createInferenceContext(sourceParams, /*signature*/ undefined, 0 /* None */, isRelatedTo);
59229                             inferTypes(ctx.inferences, target.extendsType, sourceExtends, 256 /* NoConstraints */ | 512 /* AlwaysStrict */);
59230                             sourceExtends = instantiateType(sourceExtends, ctx.mapper);
59231                             mapper = ctx.mapper;
59232                         }
59233                         if (isTypeIdenticalTo(sourceExtends, target.extendsType) &&
59234                             (isRelatedTo(source.checkType, target.checkType) || isRelatedTo(target.checkType, source.checkType))) {
59235                             if (result = isRelatedTo(instantiateType(getTrueTypeFromConditionalType(source), mapper), getTrueTypeFromConditionalType(target), reportErrors)) {
59236                                 result &= isRelatedTo(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target), reportErrors);
59237                             }
59238                             if (result) {
59239                                 resetErrorInfo(saveErrorInfo);
59240                                 return result;
59241                             }
59242                         }
59243                     }
59244                     else {
59245                         // conditionals aren't related to one another via distributive constraint as it is much too inaccurate and allows way
59246                         // more assignments than are desirable (since it maps the source check type to its constraint, it loses information)
59247                         var distributiveConstraint = getConstraintOfDistributiveConditionalType(source);
59248                         if (distributiveConstraint) {
59249                             if (result = isRelatedTo(distributiveConstraint, target, reportErrors)) {
59250                                 resetErrorInfo(saveErrorInfo);
59251                                 return result;
59252                             }
59253                         }
59254                     }
59255                     // conditionals _can_ be related to one another via normal constraint, as, eg, `A extends B ? O : never` should be assignable to `O`
59256                     // when `O` is a conditional (`never` is trivially aissgnable to `O`, as is `O`!).
59257                     var defaultConstraint = getDefaultConstraintOfConditionalType(source);
59258                     if (defaultConstraint) {
59259                         if (result = isRelatedTo(defaultConstraint, target, reportErrors)) {
59260                             resetErrorInfo(saveErrorInfo);
59261                             return result;
59262                         }
59263                     }
59264                 }
59265                 else {
59266                     // An empty object type is related to any mapped type that includes a '?' modifier.
59267                     if (relation !== subtypeRelation && relation !== strictSubtypeRelation && isPartialMappedType(target) && isEmptyObjectType(source)) {
59268                         return -1 /* True */;
59269                     }
59270                     if (isGenericMappedType(target)) {
59271                         if (isGenericMappedType(source)) {
59272                             if (result = mappedTypeRelatedTo(source, target, reportErrors)) {
59273                                 resetErrorInfo(saveErrorInfo);
59274                                 return result;
59275                             }
59276                         }
59277                         return 0 /* False */;
59278                     }
59279                     var sourceIsPrimitive = !!(source.flags & 131068 /* Primitive */);
59280                     if (relation !== identityRelation) {
59281                         source = getApparentType(source);
59282                     }
59283                     else if (isGenericMappedType(source)) {
59284                         return 0 /* False */;
59285                     }
59286                     if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && source.target === target.target &&
59287                         !(ts.getObjectFlags(source) & 8192 /* MarkerType */ || ts.getObjectFlags(target) & 8192 /* MarkerType */)) {
59288                         // We have type references to the same generic type, and the type references are not marker
59289                         // type references (which are intended by be compared structurally). Obtain the variance
59290                         // information for the type parameters and relate the type arguments accordingly.
59291                         var variances = getVariances(source.target);
59292                         // We return Ternary.Maybe for a recursive invocation of getVariances (signalled by emptyArray). This
59293                         // effectively means we measure variance only from type parameter occurrences that aren't nested in
59294                         // recursive instantiations of the generic type.
59295                         if (variances === ts.emptyArray) {
59296                             return 1 /* Unknown */;
59297                         }
59298                         var varianceResult = relateVariances(getTypeArguments(source), getTypeArguments(target), variances, intersectionState);
59299                         if (varianceResult !== undefined) {
59300                             return varianceResult;
59301                         }
59302                     }
59303                     else if (isReadonlyArrayType(target) ? isArrayType(source) || isTupleType(source) : isArrayType(target) && isTupleType(source) && !source.target.readonly) {
59304                         if (relation !== identityRelation) {
59305                             return isRelatedTo(getIndexTypeOfType(source, 1 /* Number */) || anyType, getIndexTypeOfType(target, 1 /* Number */) || anyType, reportErrors);
59306                         }
59307                         else {
59308                             // By flags alone, we know that the `target` is a readonly array while the source is a normal array or tuple
59309                             // or `target` is an array and source is a tuple - in both cases the types cannot be identical, by construction
59310                             return 0 /* False */;
59311                         }
59312                     }
59313                     // Consider a fresh empty object literal type "closed" under the subtype relationship - this way `{} <- {[idx: string]: any} <- fresh({})`
59314                     // and not `{} <- fresh({}) <- {[idx: string]: any}`
59315                     else if ((relation === subtypeRelation || relation === strictSubtypeRelation) && isEmptyObjectType(target) && ts.getObjectFlags(target) & 32768 /* FreshLiteral */ && !isEmptyObjectType(source)) {
59316                         return 0 /* False */;
59317                     }
59318                     // Even if relationship doesn't hold for unions, intersections, or generic type references,
59319                     // it may hold in a structural comparison.
59320                     // In a check of the form X = A & B, we will have previously checked if A relates to X or B relates
59321                     // to X. Failing both of those we want to check if the aggregation of A and B's members structurally
59322                     // relates to X. Thus, we include intersection types on the source side here.
59323                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 524288 /* Object */) {
59324                         // Report structural errors only if we haven't reported any errors yet
59325                         var reportStructuralErrors = reportErrors && errorInfo === saveErrorInfo.errorInfo && !sourceIsPrimitive;
59326                         result = propertiesRelatedTo(source, target, reportStructuralErrors, /*excludedProperties*/ undefined, intersectionState);
59327                         if (result) {
59328                             result &= signaturesRelatedTo(source, target, 0 /* Call */, reportStructuralErrors);
59329                             if (result) {
59330                                 result &= signaturesRelatedTo(source, target, 1 /* Construct */, reportStructuralErrors);
59331                                 if (result) {
59332                                     result &= indexTypesRelatedTo(source, target, 0 /* String */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
59333                                     if (result) {
59334                                         result &= indexTypesRelatedTo(source, target, 1 /* Number */, sourceIsPrimitive, reportStructuralErrors, intersectionState);
59335                                     }
59336                                 }
59337                             }
59338                         }
59339                         if (varianceCheckFailed && result) {
59340                             errorInfo = originalErrorInfo || errorInfo || saveErrorInfo.errorInfo; // Use variance error (there is no structural one) and return false
59341                         }
59342                         else if (result) {
59343                             return result;
59344                         }
59345                     }
59346                     // If S is an object type and T is a discriminated union, S may be related to T if
59347                     // there exists a constituent of T for every combination of the discriminants of S
59348                     // with respect to T. We do not report errors here, as we will use the existing
59349                     // error result from checking each constituent of the union.
59350                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */) && target.flags & 1048576 /* Union */) {
59351                         var objectOnlyTarget = extractTypesOfKind(target, 524288 /* Object */ | 2097152 /* Intersection */ | 33554432 /* Substitution */);
59352                         if (objectOnlyTarget.flags & 1048576 /* Union */) {
59353                             var result_9 = typeRelatedToDiscriminatedType(source, objectOnlyTarget);
59354                             if (result_9) {
59355                                 return result_9;
59356                             }
59357                         }
59358                     }
59359                 }
59360                 return 0 /* False */;
59361                 function relateVariances(sourceTypeArguments, targetTypeArguments, variances, intersectionState) {
59362                     if (result = typeArgumentsRelatedTo(sourceTypeArguments, targetTypeArguments, variances, reportErrors, intersectionState)) {
59363                         return result;
59364                     }
59365                     if (ts.some(variances, function (v) { return !!(v & 24 /* AllowsStructuralFallback */); })) {
59366                         // If some type parameter was `Unmeasurable` or `Unreliable`, and we couldn't pass by assuming it was identical, then we
59367                         // have to allow a structural fallback check
59368                         // We elide the variance-based error elaborations, since those might not be too helpful, since we'll potentially
59369                         // be assuming identity of the type parameter.
59370                         originalErrorInfo = undefined;
59371                         resetErrorInfo(saveErrorInfo);
59372                         return undefined;
59373                     }
59374                     var allowStructuralFallback = targetTypeArguments && hasCovariantVoidArgument(targetTypeArguments, variances);
59375                     varianceCheckFailed = !allowStructuralFallback;
59376                     // The type arguments did not relate appropriately, but it may be because we have no variance
59377                     // information (in which case typeArgumentsRelatedTo defaulted to covariance for all type
59378                     // arguments). It might also be the case that the target type has a 'void' type argument for
59379                     // a covariant type parameter that is only used in return positions within the generic type
59380                     // (in which case any type argument is permitted on the source side). In those cases we proceed
59381                     // with a structural comparison. Otherwise, we know for certain the instantiations aren't
59382                     // related and we can return here.
59383                     if (variances !== ts.emptyArray && !allowStructuralFallback) {
59384                         // In some cases generic types that are covariant in regular type checking mode become
59385                         // invariant in --strictFunctionTypes mode because one or more type parameters are used in
59386                         // both co- and contravariant positions. In order to make it easier to diagnose *why* such
59387                         // types are invariant, if any of the type parameters are invariant we reset the reported
59388                         // errors and instead force a structural comparison (which will include elaborations that
59389                         // reveal the reason).
59390                         // We can switch on `reportErrors` here, since varianceCheckFailed guarantees we return `False`,
59391                         // we can return `False` early here to skip calculating the structural error message we don't need.
59392                         if (varianceCheckFailed && !(reportErrors && ts.some(variances, function (v) { return (v & 7 /* VarianceMask */) === 0 /* Invariant */; }))) {
59393                             return 0 /* False */;
59394                         }
59395                         // We remember the original error information so we can restore it in case the structural
59396                         // comparison unexpectedly succeeds. This can happen when the structural comparison result
59397                         // is a Ternary.Maybe for example caused by the recursion depth limiter.
59398                         originalErrorInfo = errorInfo;
59399                         resetErrorInfo(saveErrorInfo);
59400                     }
59401                 }
59402             }
59403             function reportUnmeasurableMarkers(p) {
59404                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
59405                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ false);
59406                 }
59407                 return p;
59408             }
59409             function reportUnreliableMarkers(p) {
59410                 if (outofbandVarianceMarkerHandler && (p === markerSuperType || p === markerSubType || p === markerOtherType)) {
59411                     outofbandVarianceMarkerHandler(/*onlyUnreliable*/ true);
59412                 }
59413                 return p;
59414             }
59415             // A type [P in S]: X is related to a type [Q in T]: Y if T is related to S and X' is
59416             // related to Y, where X' is an instantiation of X in which P is replaced with Q. Notice
59417             // that S and T are contra-variant whereas X and Y are co-variant.
59418             function mappedTypeRelatedTo(source, target, reportErrors) {
59419                 var modifiersRelated = relation === comparableRelation || (relation === identityRelation ? getMappedTypeModifiers(source) === getMappedTypeModifiers(target) :
59420                     getCombinedMappedTypeOptionality(source) <= getCombinedMappedTypeOptionality(target));
59421                 if (modifiersRelated) {
59422                     var result_10;
59423                     var targetConstraint = getConstraintTypeFromMappedType(target);
59424                     var sourceConstraint = instantiateType(getConstraintTypeFromMappedType(source), makeFunctionTypeMapper(getCombinedMappedTypeOptionality(source) < 0 ? reportUnmeasurableMarkers : reportUnreliableMarkers));
59425                     if (result_10 = isRelatedTo(targetConstraint, sourceConstraint, reportErrors)) {
59426                         var mapper = createTypeMapper([getTypeParameterFromMappedType(source)], [getTypeParameterFromMappedType(target)]);
59427                         if (instantiateType(getNameTypeFromMappedType(source), mapper) === instantiateType(getNameTypeFromMappedType(target), mapper)) {
59428                             return result_10 & isRelatedTo(instantiateType(getTemplateTypeFromMappedType(source), mapper), getTemplateTypeFromMappedType(target), reportErrors);
59429                         }
59430                     }
59431                 }
59432                 return 0 /* False */;
59433             }
59434             function typeRelatedToDiscriminatedType(source, target) {
59435                 // 1. Generate the combinations of discriminant properties & types 'source' can satisfy.
59436                 //    a. If the number of combinations is above a set limit, the comparison is too complex.
59437                 // 2. Filter 'target' to the subset of types whose discriminants exist in the matrix.
59438                 //    a. If 'target' does not satisfy all discriminants in the matrix, 'source' is not related.
59439                 // 3. For each type in the filtered 'target', determine if all non-discriminant properties of
59440                 //    'target' are related to a property in 'source'.
59441                 //
59442                 // NOTE: See ~/tests/cases/conformance/types/typeRelationships/assignmentCompatibility/assignmentCompatWithDiscriminatedUnion.ts
59443                 //       for examples.
59444                 var sourceProperties = getPropertiesOfType(source);
59445                 var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
59446                 if (!sourcePropertiesFiltered)
59447                     return 0 /* False */;
59448                 // Though we could compute the number of combinations as we generate
59449                 // the matrix, this would incur additional memory overhead due to
59450                 // array allocations. To reduce this overhead, we first compute
59451                 // the number of combinations to ensure we will not surpass our
59452                 // fixed limit before incurring the cost of any allocations:
59453                 var numCombinations = 1;
59454                 for (var _i = 0, sourcePropertiesFiltered_1 = sourcePropertiesFiltered; _i < sourcePropertiesFiltered_1.length; _i++) {
59455                     var sourceProperty = sourcePropertiesFiltered_1[_i];
59456                     numCombinations *= countTypes(getTypeOfSymbol(sourceProperty));
59457                     if (numCombinations > 25) {
59458                         // We've reached the complexity limit.
59459                         ts.tracing.instant("check" /* Check */, "typeRelatedToDiscriminatedType_DepthLimit", { sourceId: source.id, targetId: target.id, numCombinations: numCombinations });
59460                         return 0 /* False */;
59461                     }
59462                 }
59463                 // Compute the set of types for each discriminant property.
59464                 var sourceDiscriminantTypes = new Array(sourcePropertiesFiltered.length);
59465                 var excludedProperties = new ts.Set();
59466                 for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
59467                     var sourceProperty = sourcePropertiesFiltered[i];
59468                     var sourcePropertyType = getTypeOfSymbol(sourceProperty);
59469                     sourceDiscriminantTypes[i] = sourcePropertyType.flags & 1048576 /* Union */
59470                         ? sourcePropertyType.types
59471                         : [sourcePropertyType];
59472                     excludedProperties.add(sourceProperty.escapedName);
59473                 }
59474                 // Match each combination of the cartesian product of discriminant properties to one or more
59475                 // constituents of 'target'. If any combination does not have a match then 'source' is not relatable.
59476                 var discriminantCombinations = ts.cartesianProduct(sourceDiscriminantTypes);
59477                 var matchingTypes = [];
59478                 var _loop_17 = function (combination) {
59479                     var hasMatch = false;
59480                     outer: for (var _i = 0, _a = target.types; _i < _a.length; _i++) {
59481                         var type = _a[_i];
59482                         var _loop_18 = function (i) {
59483                             var sourceProperty = sourcePropertiesFiltered[i];
59484                             var targetProperty = getPropertyOfType(type, sourceProperty.escapedName);
59485                             if (!targetProperty)
59486                                 return "continue-outer";
59487                             if (sourceProperty === targetProperty)
59488                                 return "continue";
59489                             // We compare the source property to the target in the context of a single discriminant type.
59490                             var related = propertyRelatedTo(source, target, sourceProperty, targetProperty, function (_) { return combination[i]; }, /*reportErrors*/ false, 0 /* None */, /*skipOptional*/ strictNullChecks || relation === comparableRelation);
59491                             // If the target property could not be found, or if the properties were not related,
59492                             // then this constituent is not a match.
59493                             if (!related) {
59494                                 return "continue-outer";
59495                             }
59496                         };
59497                         for (var i = 0; i < sourcePropertiesFiltered.length; i++) {
59498                             var state_7 = _loop_18(i);
59499                             switch (state_7) {
59500                                 case "continue-outer": continue outer;
59501                             }
59502                         }
59503                         ts.pushIfUnique(matchingTypes, type, ts.equateValues);
59504                         hasMatch = true;
59505                     }
59506                     if (!hasMatch) {
59507                         return { value: 0 /* False */ };
59508                     }
59509                 };
59510                 for (var _a = 0, discriminantCombinations_1 = discriminantCombinations; _a < discriminantCombinations_1.length; _a++) {
59511                     var combination = discriminantCombinations_1[_a];
59512                     var state_6 = _loop_17(combination);
59513                     if (typeof state_6 === "object")
59514                         return state_6.value;
59515                 }
59516                 // Compare the remaining non-discriminant properties of each match.
59517                 var result = -1 /* True */;
59518                 for (var _b = 0, matchingTypes_1 = matchingTypes; _b < matchingTypes_1.length; _b++) {
59519                     var type = matchingTypes_1[_b];
59520                     result &= propertiesRelatedTo(source, type, /*reportErrors*/ false, excludedProperties, 0 /* None */);
59521                     if (result) {
59522                         result &= signaturesRelatedTo(source, type, 0 /* Call */, /*reportStructuralErrors*/ false);
59523                         if (result) {
59524                             result &= signaturesRelatedTo(source, type, 1 /* Construct */, /*reportStructuralErrors*/ false);
59525                             if (result) {
59526                                 result &= indexTypesRelatedTo(source, type, 0 /* String */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
59527                                 // Comparing numeric index types when both `source` and `type` are tuples is unnecessary as the
59528                                 // element types should be sufficiently covered by `propertiesRelatedTo`. It also causes problems
59529                                 // with index type assignability as the types for the excluded discriminants are still included
59530                                 // in the index type.
59531                                 if (result && !(isTupleType(source) && isTupleType(type))) {
59532                                     result &= indexTypesRelatedTo(source, type, 1 /* Number */, /*sourceIsPrimitive*/ false, /*reportStructuralErrors*/ false, 0 /* None */);
59533                                 }
59534                             }
59535                         }
59536                     }
59537                     if (!result) {
59538                         return result;
59539                     }
59540                 }
59541                 return result;
59542             }
59543             function excludeProperties(properties, excludedProperties) {
59544                 if (!excludedProperties || properties.length === 0)
59545                     return properties;
59546                 var result;
59547                 for (var i = 0; i < properties.length; i++) {
59548                     if (!excludedProperties.has(properties[i].escapedName)) {
59549                         if (result) {
59550                             result.push(properties[i]);
59551                         }
59552                     }
59553                     else if (!result) {
59554                         result = properties.slice(0, i);
59555                     }
59556                 }
59557                 return result || properties;
59558             }
59559             function isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState) {
59560                 var targetIsOptional = strictNullChecks && !!(ts.getCheckFlags(targetProp) & 48 /* Partial */);
59561                 var source = getTypeOfSourceProperty(sourceProp);
59562                 if (ts.getCheckFlags(targetProp) & 65536 /* DeferredType */ && !getSymbolLinks(targetProp).type) {
59563                     // Rather than resolving (and normalizing) the type, relate constituent-by-constituent without performing normalization or seconadary passes
59564                     var links = getSymbolLinks(targetProp);
59565                     ts.Debug.assertIsDefined(links.deferralParent);
59566                     ts.Debug.assertIsDefined(links.deferralConstituents);
59567                     var unionParent = !!(links.deferralParent.flags & 1048576 /* Union */);
59568                     var result_11 = unionParent ? 0 /* False */ : -1 /* True */;
59569                     var targetTypes = links.deferralConstituents;
59570                     for (var _i = 0, targetTypes_3 = targetTypes; _i < targetTypes_3.length; _i++) {
59571                         var targetType = targetTypes_3[_i];
59572                         var related = isRelatedTo(source, targetType, /*reportErrors*/ false, /*headMessage*/ undefined, unionParent ? 0 : 2 /* Target */);
59573                         if (!unionParent) {
59574                             if (!related) {
59575                                 // Can't assign to a target individually - have to fallback to assigning to the _whole_ intersection (which forces normalization)
59576                                 return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
59577                             }
59578                             result_11 &= related;
59579                         }
59580                         else {
59581                             if (related) {
59582                                 return related;
59583                             }
59584                         }
59585                     }
59586                     if (unionParent && !result_11 && targetIsOptional) {
59587                         result_11 = isRelatedTo(source, undefinedType);
59588                     }
59589                     if (unionParent && !result_11 && reportErrors) {
59590                         // The easiest way to get the right errors here is to un-defer (which may be costly)
59591                         // If it turns out this is too costly too often, we can replicate the error handling logic within
59592                         // typeRelatedToSomeType without the discriminatable type branch (as that requires a manifest union
59593                         // type on which to hand discriminable properties, which we are expressly trying to avoid here)
59594                         return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors);
59595                     }
59596                     return result_11;
59597                 }
59598                 else {
59599                     return isRelatedTo(source, addOptionality(getTypeOfSymbol(targetProp), targetIsOptional), reportErrors, /*headMessage*/ undefined, intersectionState);
59600                 }
59601             }
59602             function propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState, skipOptional) {
59603                 var sourcePropFlags = ts.getDeclarationModifierFlagsFromSymbol(sourceProp);
59604                 var targetPropFlags = ts.getDeclarationModifierFlagsFromSymbol(targetProp);
59605                 if (sourcePropFlags & 8 /* Private */ || targetPropFlags & 8 /* Private */) {
59606                     if (sourceProp.valueDeclaration !== targetProp.valueDeclaration) {
59607                         if (reportErrors) {
59608                             if (sourcePropFlags & 8 /* Private */ && targetPropFlags & 8 /* Private */) {
59609                                 reportError(ts.Diagnostics.Types_have_separate_declarations_of_a_private_property_0, symbolToString(targetProp));
59610                             }
59611                             else {
59612                                 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));
59613                             }
59614                         }
59615                         return 0 /* False */;
59616                     }
59617                 }
59618                 else if (targetPropFlags & 16 /* Protected */) {
59619                     if (!isValidOverrideOf(sourceProp, targetProp)) {
59620                         if (reportErrors) {
59621                             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));
59622                         }
59623                         return 0 /* False */;
59624                     }
59625                 }
59626                 else if (sourcePropFlags & 16 /* Protected */) {
59627                     if (reportErrors) {
59628                         reportError(ts.Diagnostics.Property_0_is_protected_in_type_1_but_public_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
59629                     }
59630                     return 0 /* False */;
59631                 }
59632                 // If the target comes from a partial union prop, allow `undefined` in the target type
59633                 var related = isPropertySymbolTypeRelated(sourceProp, targetProp, getTypeOfSourceProperty, reportErrors, intersectionState);
59634                 if (!related) {
59635                     if (reportErrors) {
59636                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, symbolToString(targetProp));
59637                     }
59638                     return 0 /* False */;
59639                 }
59640                 // When checking for comparability, be more lenient with optional properties.
59641                 if (!skipOptional && sourceProp.flags & 16777216 /* Optional */ && !(targetProp.flags & 16777216 /* Optional */)) {
59642                     // TypeScript 1.0 spec (April 2014): 3.8.3
59643                     // S is a subtype of a type T, and T is a supertype of S if ...
59644                     // S' and T are object types and, for each member M in T..
59645                     // M is a property and S' contains a property N where
59646                     // if M is a required property, N is also a required property
59647                     // (M - property in T)
59648                     // (N - property in S)
59649                     if (reportErrors) {
59650                         reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, symbolToString(targetProp), typeToString(source), typeToString(target));
59651                     }
59652                     return 0 /* False */;
59653                 }
59654                 return related;
59655             }
59656             function reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties) {
59657                 var shouldSkipElaboration = false;
59658                 // give specific error in case where private names have the same description
59659                 if (unmatchedProperty.valueDeclaration
59660                     && ts.isNamedDeclaration(unmatchedProperty.valueDeclaration)
59661                     && ts.isPrivateIdentifier(unmatchedProperty.valueDeclaration.name)
59662                     && source.symbol
59663                     && source.symbol.flags & 32 /* Class */) {
59664                     var privateIdentifierDescription = unmatchedProperty.valueDeclaration.name.escapedText;
59665                     var symbolTableKey = ts.getSymbolNameForPrivateIdentifier(source.symbol, privateIdentifierDescription);
59666                     if (symbolTableKey && getPropertyOfType(source, symbolTableKey)) {
59667                         var sourceName = ts.factory.getDeclarationName(source.symbol.valueDeclaration);
59668                         var targetName = ts.factory.getDeclarationName(target.symbol.valueDeclaration);
59669                         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));
59670                         return;
59671                     }
59672                 }
59673                 var props = ts.arrayFrom(getUnmatchedProperties(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false));
59674                 if (!headMessage || (headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_interface_1.code &&
59675                     headMessage.code !== ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass.code)) {
59676                     shouldSkipElaboration = true; // Retain top-level error for interface implementing issues, otherwise omit it
59677                 }
59678                 if (props.length === 1) {
59679                     var propName = symbolToString(unmatchedProperty);
59680                     reportError.apply(void 0, __spreadArrays([ts.Diagnostics.Property_0_is_missing_in_type_1_but_required_in_type_2, propName], getTypeNamesForErrorDisplay(source, target)));
59681                     if (ts.length(unmatchedProperty.declarations)) {
59682                         associateRelatedInfo(ts.createDiagnosticForNode(unmatchedProperty.declarations[0], ts.Diagnostics._0_is_declared_here, propName));
59683                     }
59684                     if (shouldSkipElaboration && errorInfo) {
59685                         overrideNextErrorInfo++;
59686                     }
59687                 }
59688                 else if (tryElaborateArrayLikeErrors(source, target, /*reportErrors*/ false)) {
59689                     if (props.length > 5) { // arbitrary cutoff for too-long list form
59690                         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);
59691                     }
59692                     else {
59693                         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(", "));
59694                     }
59695                     if (shouldSkipElaboration && errorInfo) {
59696                         overrideNextErrorInfo++;
59697                     }
59698                 }
59699                 // No array like or unmatched property error - just issue top level error (errorInfo = undefined)
59700             }
59701             function propertiesRelatedTo(source, target, reportErrors, excludedProperties, intersectionState) {
59702                 if (relation === identityRelation) {
59703                     return propertiesIdenticalTo(source, target, excludedProperties);
59704                 }
59705                 var result = -1 /* True */;
59706                 if (isTupleType(target)) {
59707                     if (isArrayType(source) || isTupleType(source)) {
59708                         if (!target.target.readonly && (isReadonlyArrayType(source) || isTupleType(source) && source.target.readonly)) {
59709                             return 0 /* False */;
59710                         }
59711                         var sourceArity = getTypeReferenceArity(source);
59712                         var targetArity = getTypeReferenceArity(target);
59713                         var sourceRestFlag = isTupleType(source) ? source.target.combinedFlags & 4 /* Rest */ : 4 /* Rest */;
59714                         var targetRestFlag = target.target.combinedFlags & 4 /* Rest */;
59715                         var sourceMinLength = isTupleType(source) ? source.target.minLength : 0;
59716                         var targetMinLength = target.target.minLength;
59717                         if (!sourceRestFlag && sourceArity < targetMinLength) {
59718                             if (reportErrors) {
59719                                 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_requires_1, sourceArity, targetMinLength);
59720                             }
59721                             return 0 /* False */;
59722                         }
59723                         if (!targetRestFlag && targetArity < sourceMinLength) {
59724                             if (reportErrors) {
59725                                 reportError(ts.Diagnostics.Source_has_0_element_s_but_target_allows_only_1, sourceMinLength, targetArity);
59726                             }
59727                             return 0 /* False */;
59728                         }
59729                         if (!targetRestFlag && sourceRestFlag) {
59730                             if (reportErrors) {
59731                                 if (sourceMinLength < targetMinLength) {
59732                                     reportError(ts.Diagnostics.Target_requires_0_element_s_but_source_may_have_fewer, targetMinLength);
59733                                 }
59734                                 else {
59735                                     reportError(ts.Diagnostics.Target_allows_only_0_element_s_but_source_may_have_more, targetArity);
59736                                 }
59737                             }
59738                             return 0 /* False */;
59739                         }
59740                         var maxArity = Math.max(sourceArity, targetArity);
59741                         for (var i = 0; i < maxArity; i++) {
59742                             var targetFlags = i < targetArity ? target.target.elementFlags[i] : targetRestFlag;
59743                             var sourceFlags = isTupleType(source) && i < sourceArity ? source.target.elementFlags[i] : sourceRestFlag;
59744                             var canExcludeDiscriminants = !!excludedProperties;
59745                             if (sourceFlags && targetFlags) {
59746                                 if (targetFlags & 8 /* Variadic */ && !(sourceFlags & 8 /* Variadic */) ||
59747                                     (sourceFlags & 8 /* Variadic */ && !(targetFlags & 12 /* Variable */))) {
59748                                     if (reportErrors) {
59749                                         reportError(ts.Diagnostics.Element_at_index_0_is_variadic_in_one_type_but_not_in_the_other, i);
59750                                     }
59751                                     return 0 /* False */;
59752                                 }
59753                                 if (targetFlags & 1 /* Required */) {
59754                                     if (!(sourceFlags & 1 /* Required */)) {
59755                                         if (reportErrors) {
59756                                             reportError(ts.Diagnostics.Property_0_is_optional_in_type_1_but_required_in_type_2, i, typeToString(source), typeToString(target));
59757                                         }
59758                                         return 0 /* False */;
59759                                     }
59760                                 }
59761                                 // We can only exclude discriminant properties if we have not yet encountered a variable-length element.
59762                                 if (canExcludeDiscriminants) {
59763                                     if (sourceFlags & 12 /* Variable */ || targetFlags & 12 /* Variable */) {
59764                                         canExcludeDiscriminants = false;
59765                                     }
59766                                     if (canExcludeDiscriminants && (excludedProperties === null || excludedProperties === void 0 ? void 0 : excludedProperties.has(("" + i)))) {
59767                                         continue;
59768                                     }
59769                                 }
59770                                 var sourceType = getTypeArguments(source)[Math.min(i, sourceArity - 1)];
59771                                 var targetType = getTypeArguments(target)[Math.min(i, targetArity - 1)];
59772                                 var targetCheckType = sourceFlags & 8 /* Variadic */ && targetFlags & 4 /* Rest */ ? createArrayType(targetType) : targetType;
59773                                 var related = isRelatedTo(sourceType, targetCheckType, reportErrors, /*headMessage*/ undefined, intersectionState);
59774                                 if (!related) {
59775                                     if (reportErrors) {
59776                                         reportIncompatibleError(ts.Diagnostics.Types_of_property_0_are_incompatible, i);
59777                                     }
59778                                     return 0 /* False */;
59779                                 }
59780                                 result &= related;
59781                             }
59782                         }
59783                         return result;
59784                     }
59785                     if (target.target.combinedFlags & 12 /* Variable */) {
59786                         return 0 /* False */;
59787                     }
59788                 }
59789                 var requireOptionalProperties = (relation === subtypeRelation || relation === strictSubtypeRelation) && !isObjectLiteralType(source) && !isEmptyArrayLiteralType(source) && !isTupleType(source);
59790                 var unmatchedProperty = getUnmatchedProperty(source, target, requireOptionalProperties, /*matchDiscriminantProperties*/ false);
59791                 if (unmatchedProperty) {
59792                     if (reportErrors) {
59793                         reportUnmatchedProperty(source, target, unmatchedProperty, requireOptionalProperties);
59794                     }
59795                     return 0 /* False */;
59796                 }
59797                 if (isObjectLiteralType(target)) {
59798                     for (var _i = 0, _a = excludeProperties(getPropertiesOfType(source), excludedProperties); _i < _a.length; _i++) {
59799                         var sourceProp = _a[_i];
59800                         if (!getPropertyOfObjectType(target, sourceProp.escapedName)) {
59801                             var sourceType = getTypeOfSymbol(sourceProp);
59802                             if (!(sourceType === undefinedType || sourceType === undefinedWideningType || sourceType === optionalType)) {
59803                                 if (reportErrors) {
59804                                     reportError(ts.Diagnostics.Property_0_does_not_exist_on_type_1, symbolToString(sourceProp), typeToString(target));
59805                                 }
59806                                 return 0 /* False */;
59807                             }
59808                         }
59809                     }
59810                 }
59811                 // 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_
59812                 // from the target union, across all members
59813                 var properties = getPropertiesOfType(target);
59814                 var numericNamesOnly = isTupleType(source) && isTupleType(target);
59815                 for (var _b = 0, _c = excludeProperties(properties, excludedProperties); _b < _c.length; _b++) {
59816                     var targetProp = _c[_b];
59817                     var name = targetProp.escapedName;
59818                     if (!(targetProp.flags & 4194304 /* Prototype */) && (!numericNamesOnly || isNumericLiteralName(name) || name === "length")) {
59819                         var sourceProp = getPropertyOfType(source, name);
59820                         if (sourceProp && sourceProp !== targetProp) {
59821                             var related = propertyRelatedTo(source, target, sourceProp, targetProp, getTypeOfSymbol, reportErrors, intersectionState, relation === comparableRelation);
59822                             if (!related) {
59823                                 return 0 /* False */;
59824                             }
59825                             result &= related;
59826                         }
59827                     }
59828                 }
59829                 return result;
59830             }
59831             function propertiesIdenticalTo(source, target, excludedProperties) {
59832                 if (!(source.flags & 524288 /* Object */ && target.flags & 524288 /* Object */)) {
59833                     return 0 /* False */;
59834                 }
59835                 var sourceProperties = excludeProperties(getPropertiesOfObjectType(source), excludedProperties);
59836                 var targetProperties = excludeProperties(getPropertiesOfObjectType(target), excludedProperties);
59837                 if (sourceProperties.length !== targetProperties.length) {
59838                     return 0 /* False */;
59839                 }
59840                 var result = -1 /* True */;
59841                 for (var _i = 0, sourceProperties_1 = sourceProperties; _i < sourceProperties_1.length; _i++) {
59842                     var sourceProp = sourceProperties_1[_i];
59843                     var targetProp = getPropertyOfObjectType(target, sourceProp.escapedName);
59844                     if (!targetProp) {
59845                         return 0 /* False */;
59846                     }
59847                     var related = compareProperties(sourceProp, targetProp, isRelatedTo);
59848                     if (!related) {
59849                         return 0 /* False */;
59850                     }
59851                     result &= related;
59852                 }
59853                 return result;
59854             }
59855             function signaturesRelatedTo(source, target, kind, reportErrors) {
59856                 var _a, _b;
59857                 if (relation === identityRelation) {
59858                     return signaturesIdenticalTo(source, target, kind);
59859                 }
59860                 if (target === anyFunctionType || source === anyFunctionType) {
59861                     return -1 /* True */;
59862                 }
59863                 var sourceIsJSConstructor = source.symbol && isJSConstructor(source.symbol.valueDeclaration);
59864                 var targetIsJSConstructor = target.symbol && isJSConstructor(target.symbol.valueDeclaration);
59865                 var sourceSignatures = getSignaturesOfType(source, (sourceIsJSConstructor && kind === 1 /* Construct */) ?
59866                     0 /* Call */ : kind);
59867                 var targetSignatures = getSignaturesOfType(target, (targetIsJSConstructor && kind === 1 /* Construct */) ?
59868                     0 /* Call */ : kind);
59869                 if (kind === 1 /* Construct */ && sourceSignatures.length && targetSignatures.length) {
59870                     if (ts.isAbstractConstructorType(source) && !ts.isAbstractConstructorType(target)) {
59871                         // An abstract constructor type is not assignable to a non-abstract constructor type
59872                         // as it would otherwise be possible to new an abstract class. Note that the assignability
59873                         // check we perform for an extends clause excludes construct signatures from the target,
59874                         // so this check never proceeds.
59875                         if (reportErrors) {
59876                             reportError(ts.Diagnostics.Cannot_assign_an_abstract_constructor_type_to_a_non_abstract_constructor_type);
59877                         }
59878                         return 0 /* False */;
59879                     }
59880                     if (!constructorVisibilitiesAreCompatible(sourceSignatures[0], targetSignatures[0], reportErrors)) {
59881                         return 0 /* False */;
59882                     }
59883                 }
59884                 var result = -1 /* True */;
59885                 var saveErrorInfo = captureErrorCalculationState();
59886                 var incompatibleReporter = kind === 1 /* Construct */ ? reportIncompatibleConstructSignatureReturn : reportIncompatibleCallSignatureReturn;
59887                 var sourceObjectFlags = ts.getObjectFlags(source);
59888                 var targetObjectFlags = ts.getObjectFlags(target);
59889                 if (sourceObjectFlags & 64 /* Instantiated */ && targetObjectFlags & 64 /* Instantiated */ && source.symbol === target.symbol) {
59890                     // We have instantiations of the same anonymous type (which typically will be the type of a
59891                     // method). Simply do a pairwise comparison of the signatures in the two signature lists instead
59892                     // of the much more expensive N * M comparison matrix we explore below. We erase type parameters
59893                     // as they are known to always be the same.
59894                     for (var i = 0; i < targetSignatures.length; i++) {
59895                         var related = signatureRelatedTo(sourceSignatures[i], targetSignatures[i], /*erase*/ true, reportErrors, incompatibleReporter(sourceSignatures[i], targetSignatures[i]));
59896                         if (!related) {
59897                             return 0 /* False */;
59898                         }
59899                         result &= related;
59900                     }
59901                 }
59902                 else if (sourceSignatures.length === 1 && targetSignatures.length === 1) {
59903                     // For simple functions (functions with a single signature) we only erase type parameters for
59904                     // the comparable relation. Otherwise, if the source signature is generic, we instantiate it
59905                     // in the context of the target signature before checking the relationship. Ideally we'd do
59906                     // this regardless of the number of signatures, but the potential costs are prohibitive due
59907                     // to the quadratic nature of the logic below.
59908                     var eraseGenerics = relation === comparableRelation || !!compilerOptions.noStrictGenericChecks;
59909                     var sourceSignature = ts.first(sourceSignatures);
59910                     var targetSignature = ts.first(targetSignatures);
59911                     result = signatureRelatedTo(sourceSignature, targetSignature, eraseGenerics, reportErrors, incompatibleReporter(sourceSignature, targetSignature));
59912                     if (!result && reportErrors && kind === 1 /* Construct */ && (sourceObjectFlags & targetObjectFlags) &&
59913                         (((_a = targetSignature.declaration) === null || _a === void 0 ? void 0 : _a.kind) === 166 /* Constructor */ || ((_b = sourceSignature.declaration) === null || _b === void 0 ? void 0 : _b.kind) === 166 /* Constructor */)) {
59914                         var constructSignatureToString = function (signature) {
59915                             return signatureToString(signature, /*enclosingDeclaration*/ undefined, 262144 /* WriteArrowStyleSignature */, kind);
59916                         };
59917                         reportError(ts.Diagnostics.Type_0_is_not_assignable_to_type_1, constructSignatureToString(sourceSignature), constructSignatureToString(targetSignature));
59918                         reportError(ts.Diagnostics.Types_of_construct_signatures_are_incompatible);
59919                         return result;
59920                     }
59921                 }
59922                 else {
59923                     outer: for (var _i = 0, targetSignatures_1 = targetSignatures; _i < targetSignatures_1.length; _i++) {
59924                         var t = targetSignatures_1[_i];
59925                         // Only elaborate errors from the first failure
59926                         var shouldElaborateErrors = reportErrors;
59927                         for (var _c = 0, sourceSignatures_1 = sourceSignatures; _c < sourceSignatures_1.length; _c++) {
59928                             var s = sourceSignatures_1[_c];
59929                             var related = signatureRelatedTo(s, t, /*erase*/ true, shouldElaborateErrors, incompatibleReporter(s, t));
59930                             if (related) {
59931                                 result &= related;
59932                                 resetErrorInfo(saveErrorInfo);
59933                                 continue outer;
59934                             }
59935                             shouldElaborateErrors = false;
59936                         }
59937                         if (shouldElaborateErrors) {
59938                             reportError(ts.Diagnostics.Type_0_provides_no_match_for_the_signature_1, typeToString(source), signatureToString(t, /*enclosingDeclaration*/ undefined, /*flags*/ undefined, kind));
59939                         }
59940                         return 0 /* False */;
59941                     }
59942                 }
59943                 return result;
59944             }
59945             function reportIncompatibleCallSignatureReturn(siga, sigb) {
59946                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
59947                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
59948                 }
59949                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Call_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
59950             }
59951             function reportIncompatibleConstructSignatureReturn(siga, sigb) {
59952                 if (siga.parameters.length === 0 && sigb.parameters.length === 0) {
59953                     return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signatures_with_no_arguments_have_incompatible_return_types_0_and_1, typeToString(source), typeToString(target)); };
59954                 }
59955                 return function (source, target) { return reportIncompatibleError(ts.Diagnostics.Construct_signature_return_types_0_and_1_are_incompatible, typeToString(source), typeToString(target)); };
59956             }
59957             /**
59958              * See signatureAssignableTo, compareSignaturesIdentical
59959              */
59960             function signatureRelatedTo(source, target, erase, reportErrors, incompatibleReporter) {
59961                 return compareSignaturesRelated(erase ? getErasedSignature(source) : source, erase ? getErasedSignature(target) : target, relation === strictSubtypeRelation ? 8 /* StrictArity */ : 0, reportErrors, reportError, incompatibleReporter, isRelatedTo, makeFunctionTypeMapper(reportUnreliableMarkers));
59962             }
59963             function signaturesIdenticalTo(source, target, kind) {
59964                 var sourceSignatures = getSignaturesOfType(source, kind);
59965                 var targetSignatures = getSignaturesOfType(target, kind);
59966                 if (sourceSignatures.length !== targetSignatures.length) {
59967                     return 0 /* False */;
59968                 }
59969                 var result = -1 /* True */;
59970                 for (var i = 0; i < sourceSignatures.length; i++) {
59971                     var related = compareSignaturesIdentical(sourceSignatures[i], targetSignatures[i], /*partialMatch*/ false, /*ignoreThisTypes*/ false, /*ignoreReturnTypes*/ false, isRelatedTo);
59972                     if (!related) {
59973                         return 0 /* False */;
59974                     }
59975                     result &= related;
59976                 }
59977                 return result;
59978             }
59979             function eachPropertyRelatedTo(source, target, kind, reportErrors) {
59980                 var result = -1 /* True */;
59981                 var props = source.flags & 2097152 /* Intersection */ ? getPropertiesOfUnionOrIntersectionType(source) : getPropertiesOfObjectType(source);
59982                 for (var _i = 0, props_2 = props; _i < props_2.length; _i++) {
59983                     var prop = props_2[_i];
59984                     // Skip over ignored JSX and symbol-named members
59985                     if (isIgnoredJsxProperty(source, prop)) {
59986                         continue;
59987                     }
59988                     var nameType = getSymbolLinks(prop).nameType;
59989                     if (nameType && nameType.flags & 8192 /* UniqueESSymbol */) {
59990                         continue;
59991                     }
59992                     if (kind === 0 /* String */ || isNumericLiteralName(prop.escapedName)) {
59993                         var related = isRelatedTo(getTypeOfSymbol(prop), target, reportErrors);
59994                         if (!related) {
59995                             if (reportErrors) {
59996                                 reportError(ts.Diagnostics.Property_0_is_incompatible_with_index_signature, symbolToString(prop));
59997                             }
59998                             return 0 /* False */;
59999                         }
60000                         result &= related;
60001                     }
60002                 }
60003                 return result;
60004             }
60005             function indexTypeRelatedTo(sourceType, targetType, reportErrors) {
60006                 var related = isRelatedTo(sourceType, targetType, reportErrors);
60007                 if (!related && reportErrors) {
60008                     reportError(ts.Diagnostics.Index_signatures_are_incompatible);
60009                 }
60010                 return related;
60011             }
60012             function indexTypesRelatedTo(source, target, kind, sourceIsPrimitive, reportErrors, intersectionState) {
60013                 if (relation === identityRelation) {
60014                     return indexTypesIdenticalTo(source, target, kind);
60015                 }
60016                 var targetType = getIndexTypeOfType(target, kind);
60017                 if (!targetType || targetType.flags & 1 /* Any */ && !sourceIsPrimitive) {
60018                     // Index signature of type any permits assignment from everything but primitives
60019                     return -1 /* True */;
60020                 }
60021                 if (isGenericMappedType(source)) {
60022                     // A generic mapped type { [P in K]: T } is related to a type with an index signature
60023                     // { [x: string]: U }, and optionally with an index signature { [x: number]: V },
60024                     // if T is related to U and V.
60025                     return getIndexTypeOfType(target, 0 /* String */) ? isRelatedTo(getTemplateTypeFromMappedType(source), targetType, reportErrors) : 0 /* False */;
60026                 }
60027                 var indexType = getIndexTypeOfType(source, kind) || kind === 1 /* Number */ && getIndexTypeOfType(source, 0 /* String */);
60028                 if (indexType) {
60029                     return indexTypeRelatedTo(indexType, targetType, reportErrors);
60030                 }
60031                 if (!(intersectionState & 1 /* Source */) && isObjectTypeWithInferableIndex(source)) {
60032                     // Intersection constituents are never considered to have an inferred index signature
60033                     var related = eachPropertyRelatedTo(source, targetType, kind, reportErrors);
60034                     if (related && kind === 0 /* String */) {
60035                         var numberIndexType = getIndexTypeOfType(source, 1 /* Number */);
60036                         if (numberIndexType) {
60037                             related &= indexTypeRelatedTo(numberIndexType, targetType, reportErrors);
60038                         }
60039                     }
60040                     return related;
60041                 }
60042                 if (reportErrors) {
60043                     reportError(ts.Diagnostics.Index_signature_is_missing_in_type_0, typeToString(source));
60044                 }
60045                 return 0 /* False */;
60046             }
60047             function indexTypesIdenticalTo(source, target, indexKind) {
60048                 var targetInfo = getIndexInfoOfType(target, indexKind);
60049                 var sourceInfo = getIndexInfoOfType(source, indexKind);
60050                 if (!sourceInfo && !targetInfo) {
60051                     return -1 /* True */;
60052                 }
60053                 if (sourceInfo && targetInfo && sourceInfo.isReadonly === targetInfo.isReadonly) {
60054                     return isRelatedTo(sourceInfo.type, targetInfo.type);
60055                 }
60056                 return 0 /* False */;
60057             }
60058             function constructorVisibilitiesAreCompatible(sourceSignature, targetSignature, reportErrors) {
60059                 if (!sourceSignature.declaration || !targetSignature.declaration) {
60060                     return true;
60061                 }
60062                 var sourceAccessibility = ts.getSelectedEffectiveModifierFlags(sourceSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
60063                 var targetAccessibility = ts.getSelectedEffectiveModifierFlags(targetSignature.declaration, 24 /* NonPublicAccessibilityModifier */);
60064                 // A public, protected and private signature is assignable to a private signature.
60065                 if (targetAccessibility === 8 /* Private */) {
60066                     return true;
60067                 }
60068                 // A public and protected signature is assignable to a protected signature.
60069                 if (targetAccessibility === 16 /* Protected */ && sourceAccessibility !== 8 /* Private */) {
60070                     return true;
60071                 }
60072                 // Only a public signature is assignable to public signature.
60073                 if (targetAccessibility !== 16 /* Protected */ && !sourceAccessibility) {
60074                     return true;
60075                 }
60076                 if (reportErrors) {
60077                     reportError(ts.Diagnostics.Cannot_assign_a_0_constructor_type_to_a_1_constructor_type, visibilityToString(sourceAccessibility), visibilityToString(targetAccessibility));
60078                 }
60079                 return false;
60080             }
60081         }
60082         function typeCouldHaveTopLevelSingletonTypes(type) {
60083             // Okay, yes, 'boolean' is a union of 'true | false', but that's not useful
60084             // in error reporting scenarios. If you need to use this function but that detail matters,
60085             // feel free to add a flag.
60086             if (type.flags & 16 /* Boolean */) {
60087                 return false;
60088             }
60089             if (type.flags & 3145728 /* UnionOrIntersection */) {
60090                 return !!ts.forEach(type.types, typeCouldHaveTopLevelSingletonTypes);
60091             }
60092             if (type.flags & 465829888 /* Instantiable */) {
60093                 var constraint = getConstraintOfType(type);
60094                 if (constraint && constraint !== type) {
60095                     return typeCouldHaveTopLevelSingletonTypes(constraint);
60096                 }
60097             }
60098             return isUnitType(type) || !!(type.flags & 134217728 /* TemplateLiteral */);
60099         }
60100         function getBestMatchingType(source, target, isRelatedTo) {
60101             if (isRelatedTo === void 0) { isRelatedTo = compareTypesAssignable; }
60102             return findMatchingDiscriminantType(source, target, isRelatedTo, /*skipPartial*/ true) ||
60103                 findMatchingTypeReferenceOrTypeAliasReference(source, target) ||
60104                 findBestTypeForObjectLiteral(source, target) ||
60105                 findBestTypeForInvokable(source, target) ||
60106                 findMostOverlappyType(source, target);
60107         }
60108         function discriminateTypeByDiscriminableItems(target, discriminators, related, defaultValue, skipPartial) {
60109             // undefined=unknown, true=discriminated, false=not discriminated
60110             // The state of each type progresses from left to right. Discriminated types stop at 'true'.
60111             var discriminable = target.types.map(function (_) { return undefined; });
60112             for (var _i = 0, discriminators_1 = discriminators; _i < discriminators_1.length; _i++) {
60113                 var _a = discriminators_1[_i], getDiscriminatingType = _a[0], propertyName = _a[1];
60114                 var targetProp = getUnionOrIntersectionProperty(target, propertyName);
60115                 if (skipPartial && targetProp && ts.getCheckFlags(targetProp) & 16 /* ReadPartial */) {
60116                     continue;
60117                 }
60118                 var i = 0;
60119                 for (var _b = 0, _c = target.types; _b < _c.length; _b++) {
60120                     var type = _c[_b];
60121                     var targetType = getTypeOfPropertyOfType(type, propertyName);
60122                     if (targetType && related(getDiscriminatingType(), targetType)) {
60123                         discriminable[i] = discriminable[i] === undefined ? true : discriminable[i];
60124                     }
60125                     else {
60126                         discriminable[i] = false;
60127                     }
60128                     i++;
60129                 }
60130             }
60131             var match = discriminable.indexOf(/*searchElement*/ true);
60132             if (match === -1) {
60133                 return defaultValue;
60134             }
60135             // make sure exactly 1 matches before returning it
60136             var nextMatch = discriminable.indexOf(/*searchElement*/ true, match + 1);
60137             while (nextMatch !== -1) {
60138                 if (!isTypeIdenticalTo(target.types[match], target.types[nextMatch])) {
60139                     return defaultValue;
60140                 }
60141                 nextMatch = discriminable.indexOf(/*searchElement*/ true, nextMatch + 1);
60142             }
60143             return target.types[match];
60144         }
60145         /**
60146          * A type is 'weak' if it is an object type with at least one optional property
60147          * and no required properties, call/construct signatures or index signatures
60148          */
60149         function isWeakType(type) {
60150             if (type.flags & 524288 /* Object */) {
60151                 var resolved = resolveStructuredTypeMembers(type);
60152                 return resolved.callSignatures.length === 0 && resolved.constructSignatures.length === 0 &&
60153                     !resolved.stringIndexInfo && !resolved.numberIndexInfo &&
60154                     resolved.properties.length > 0 &&
60155                     ts.every(resolved.properties, function (p) { return !!(p.flags & 16777216 /* Optional */); });
60156             }
60157             if (type.flags & 2097152 /* Intersection */) {
60158                 return ts.every(type.types, isWeakType);
60159             }
60160             return false;
60161         }
60162         function hasCommonProperties(source, target, isComparingJsxAttributes) {
60163             for (var _i = 0, _a = getPropertiesOfType(source); _i < _a.length; _i++) {
60164                 var prop = _a[_i];
60165                 if (isKnownProperty(target, prop.escapedName, isComparingJsxAttributes)) {
60166                     return true;
60167                 }
60168             }
60169             return false;
60170         }
60171         // Return a type reference where the source type parameter is replaced with the target marker
60172         // type, and flag the result as a marker type reference.
60173         function getMarkerTypeReference(type, source, target) {
60174             var result = createTypeReference(type, ts.map(type.typeParameters, function (t) { return t === source ? target : t; }));
60175             result.objectFlags |= 8192 /* MarkerType */;
60176             return result;
60177         }
60178         function getAliasVariances(symbol) {
60179             var links = getSymbolLinks(symbol);
60180             return getVariancesWorker(links.typeParameters, links, function (_links, param, marker) {
60181                 var type = getTypeAliasInstantiation(symbol, instantiateTypes(links.typeParameters, makeUnaryTypeMapper(param, marker)));
60182                 type.aliasTypeArgumentsContainsMarker = true;
60183                 return type;
60184             });
60185         }
60186         // Return an array containing the variance of each type parameter. The variance is effectively
60187         // a digest of the type comparisons that occur for each type argument when instantiations of the
60188         // generic type are structurally compared. We infer the variance information by comparing
60189         // instantiations of the generic type for type arguments with known relations. The function
60190         // returns the emptyArray singleton when invoked recursively for the given generic type.
60191         function getVariancesWorker(typeParameters, cache, createMarkerType) {
60192             var _a, _b, _c;
60193             if (typeParameters === void 0) { typeParameters = ts.emptyArray; }
60194             var variances = cache.variances;
60195             if (!variances) {
60196                 ts.tracing.push("check" /* Check */, "getVariancesWorker", { arity: typeParameters.length, id: (_c = (_a = cache.id) !== null && _a !== void 0 ? _a : (_b = cache.declaredType) === null || _b === void 0 ? void 0 : _b.id) !== null && _c !== void 0 ? _c : -1 });
60197                 // The emptyArray singleton is used to signal a recursive invocation.
60198                 cache.variances = ts.emptyArray;
60199                 variances = [];
60200                 var _loop_19 = function (tp) {
60201                     var unmeasurable = false;
60202                     var unreliable = false;
60203                     var oldHandler = outofbandVarianceMarkerHandler;
60204                     outofbandVarianceMarkerHandler = function (onlyUnreliable) { return onlyUnreliable ? unreliable = true : unmeasurable = true; };
60205                     // We first compare instantiations where the type parameter is replaced with
60206                     // marker types that have a known subtype relationship. From this we can infer
60207                     // invariance, covariance, contravariance or bivariance.
60208                     var typeWithSuper = createMarkerType(cache, tp, markerSuperType);
60209                     var typeWithSub = createMarkerType(cache, tp, markerSubType);
60210                     var variance = (isTypeAssignableTo(typeWithSub, typeWithSuper) ? 1 /* Covariant */ : 0) |
60211                         (isTypeAssignableTo(typeWithSuper, typeWithSub) ? 2 /* Contravariant */ : 0);
60212                     // If the instantiations appear to be related bivariantly it may be because the
60213                     // type parameter is independent (i.e. it isn't witnessed anywhere in the generic
60214                     // type). To determine this we compare instantiations where the type parameter is
60215                     // replaced with marker types that are known to be unrelated.
60216                     if (variance === 3 /* Bivariant */ && isTypeAssignableTo(createMarkerType(cache, tp, markerOtherType), typeWithSuper)) {
60217                         variance = 4 /* Independent */;
60218                     }
60219                     outofbandVarianceMarkerHandler = oldHandler;
60220                     if (unmeasurable || unreliable) {
60221                         if (unmeasurable) {
60222                             variance |= 8 /* Unmeasurable */;
60223                         }
60224                         if (unreliable) {
60225                             variance |= 16 /* Unreliable */;
60226                         }
60227                     }
60228                     variances.push(variance);
60229                 };
60230                 for (var _i = 0, typeParameters_1 = typeParameters; _i < typeParameters_1.length; _i++) {
60231                     var tp = typeParameters_1[_i];
60232                     _loop_19(tp);
60233                 }
60234                 cache.variances = variances;
60235                 ts.tracing.pop();
60236             }
60237             return variances;
60238         }
60239         function getVariances(type) {
60240             // Arrays and tuples are known to be covariant, no need to spend time computing this.
60241             if (type === globalArrayType || type === globalReadonlyArrayType || type.objectFlags & 8 /* Tuple */) {
60242                 return arrayVariances;
60243             }
60244             return getVariancesWorker(type.typeParameters, type, getMarkerTypeReference);
60245         }
60246         // Return true if the given type reference has a 'void' type argument for a covariant type parameter.
60247         // See comment at call in recursiveTypeRelatedTo for when this case matters.
60248         function hasCovariantVoidArgument(typeArguments, variances) {
60249             for (var i = 0; i < variances.length; i++) {
60250                 if ((variances[i] & 7 /* VarianceMask */) === 1 /* Covariant */ && typeArguments[i].flags & 16384 /* Void */) {
60251                     return true;
60252                 }
60253             }
60254             return false;
60255         }
60256         function isUnconstrainedTypeParameter(type) {
60257             return type.flags & 262144 /* TypeParameter */ && !getConstraintOfTypeParameter(type);
60258         }
60259         function isNonDeferredTypeReference(type) {
60260             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && !type.node;
60261         }
60262         function isTypeReferenceWithGenericArguments(type) {
60263             return isNonDeferredTypeReference(type) && ts.some(getTypeArguments(type), function (t) { return isUnconstrainedTypeParameter(t) || isTypeReferenceWithGenericArguments(t); });
60264         }
60265         /**
60266          * getTypeReferenceId(A<T, number, U>) returns "111=0-12=1"
60267          *   where A.id=111 and number.id=12
60268          */
60269         function getTypeReferenceId(type, typeParameters, depth) {
60270             if (depth === void 0) { depth = 0; }
60271             var result = "" + type.target.id;
60272             for (var _i = 0, _a = getTypeArguments(type); _i < _a.length; _i++) {
60273                 var t = _a[_i];
60274                 if (isUnconstrainedTypeParameter(t)) {
60275                     var index = typeParameters.indexOf(t);
60276                     if (index < 0) {
60277                         index = typeParameters.length;
60278                         typeParameters.push(t);
60279                     }
60280                     result += "=" + index;
60281                 }
60282                 else if (depth < 4 && isTypeReferenceWithGenericArguments(t)) {
60283                     result += "<" + getTypeReferenceId(t, typeParameters, depth + 1) + ">";
60284                 }
60285                 else {
60286                     result += "-" + t.id;
60287                 }
60288             }
60289             return result;
60290         }
60291         /**
60292          * To improve caching, the relation key for two generic types uses the target's id plus ids of the type parameters.
60293          * For other cases, the types ids are used.
60294          */
60295         function getRelationKey(source, target, intersectionState, relation) {
60296             if (relation === identityRelation && source.id > target.id) {
60297                 var temp = source;
60298                 source = target;
60299                 target = temp;
60300             }
60301             var postFix = intersectionState ? ":" + intersectionState : "";
60302             if (isTypeReferenceWithGenericArguments(source) && isTypeReferenceWithGenericArguments(target)) {
60303                 var typeParameters = [];
60304                 return getTypeReferenceId(source, typeParameters) + "," + getTypeReferenceId(target, typeParameters) + postFix;
60305             }
60306             return source.id + "," + target.id + postFix;
60307         }
60308         // Invoke the callback for each underlying property symbol of the given symbol and return the first
60309         // value that isn't undefined.
60310         function forEachProperty(prop, callback) {
60311             if (ts.getCheckFlags(prop) & 6 /* Synthetic */) {
60312                 for (var _i = 0, _a = prop.containingType.types; _i < _a.length; _i++) {
60313                     var t = _a[_i];
60314                     var p = getPropertyOfType(t, prop.escapedName);
60315                     var result = p && forEachProperty(p, callback);
60316                     if (result) {
60317                         return result;
60318                     }
60319                 }
60320                 return undefined;
60321             }
60322             return callback(prop);
60323         }
60324         // Return the declaring class type of a property or undefined if property not declared in class
60325         function getDeclaringClass(prop) {
60326             return prop.parent && prop.parent.flags & 32 /* Class */ ? getDeclaredTypeOfSymbol(getParentOfSymbol(prop)) : undefined;
60327         }
60328         // Return the inherited type of the given property or undefined if property doesn't exist in a base class.
60329         function getTypeOfPropertyInBaseClass(property) {
60330             var classType = getDeclaringClass(property);
60331             var baseClassType = classType && getBaseTypes(classType)[0];
60332             return baseClassType && getTypeOfPropertyOfType(baseClassType, property.escapedName);
60333         }
60334         // Return true if some underlying source property is declared in a class that derives
60335         // from the given base class.
60336         function isPropertyInClassDerivedFrom(prop, baseClass) {
60337             return forEachProperty(prop, function (sp) {
60338                 var sourceClass = getDeclaringClass(sp);
60339                 return sourceClass ? hasBaseType(sourceClass, baseClass) : false;
60340             });
60341         }
60342         // Return true if source property is a valid override of protected parts of target property.
60343         function isValidOverrideOf(sourceProp, targetProp) {
60344             return !forEachProperty(targetProp, function (tp) { return ts.getDeclarationModifierFlagsFromSymbol(tp) & 16 /* Protected */ ?
60345                 !isPropertyInClassDerivedFrom(sourceProp, getDeclaringClass(tp)) : false; });
60346         }
60347         // Return true if the given class derives from each of the declaring classes of the protected
60348         // constituents of the given property.
60349         function isClassDerivedFromDeclaringClasses(checkClass, prop) {
60350             return forEachProperty(prop, function (p) { return ts.getDeclarationModifierFlagsFromSymbol(p) & 16 /* Protected */ ?
60351                 !hasBaseType(checkClass, getDeclaringClass(p)) : false; }) ? undefined : checkClass;
60352         }
60353         // Return true if the given type is deeply nested. We consider this to be the case when structural type comparisons
60354         // for 5 or more occurrences or instantiations of the type have been recorded on the given stack. It is possible,
60355         // though highly unlikely, for this test to be true in a situation where a chain of instantiations is not infinitely
60356         // expanding. Effectively, we will generate a false positive when two types are structurally equal to at least 5
60357         // levels, but unequal at some level beyond that.
60358         // In addition, this will also detect when an indexed access has been chained off of 5 or more times (which is essentially
60359         // the dual of the structural comparison), and likewise mark the type as deeply nested, potentially adding false positives
60360         // for finite but deeply expanding indexed accesses (eg, for `Q[P1][P2][P3][P4][P5]`).
60361         // It also detects when a recursive type reference has expanded 5 or more times, eg, if the true branch of
60362         // `type A<T> = null extends T ? [A<NonNullable<T>>] : [T]`
60363         // has expanded into `[A<NonNullable<NonNullable<NonNullable<NonNullable<NonNullable<T>>>>>>]`
60364         // in such cases we need to terminate the expansion, and we do so here.
60365         function isDeeplyNestedType(type, stack, depth) {
60366             if (depth >= 5) {
60367                 var identity_1 = getRecursionIdentity(type);
60368                 if (identity_1) {
60369                     var count = 0;
60370                     for (var i = 0; i < depth; i++) {
60371                         if (getRecursionIdentity(stack[i]) === identity_1) {
60372                             count++;
60373                             if (count >= 5) {
60374                                 return true;
60375                             }
60376                         }
60377                     }
60378                 }
60379             }
60380             return false;
60381         }
60382         // Types with constituents that could circularly reference the type have a recursion identity. The recursion
60383         // identity is some object that is common to instantiations of the type with the same origin.
60384         function getRecursionIdentity(type) {
60385             if (type.flags & 524288 /* Object */ && !isObjectOrArrayLiteralType(type)) {
60386                 if (ts.getObjectFlags(type) && 4 /* Reference */ && type.node) {
60387                     // Deferred type references are tracked through their associated AST node. This gives us finer
60388                     // granularity than using their associated target because each manifest type reference has a
60389                     // unique AST node.
60390                     return type.node;
60391                 }
60392                 if (type.symbol && !(ts.getObjectFlags(type) & 16 /* Anonymous */ && type.symbol.flags & 32 /* Class */)) {
60393                     // We track all object types that have an associated symbol (representing the origin of the type), but
60394                     // exclude the static side of classes from this check since it shares its symbol with the instance side.
60395                     return type.symbol;
60396                 }
60397                 if (isTupleType(type)) {
60398                     // Tuple types are tracked through their target type
60399                     return type.target;
60400                 }
60401             }
60402             if (type.flags & 8388608 /* IndexedAccess */) {
60403                 // Identity is the leftmost object type in a chain of indexed accesses, eg, in A[P][Q] it is A
60404                 do {
60405                     type = type.objectType;
60406                 } while (type.flags & 8388608 /* IndexedAccess */);
60407                 return type;
60408             }
60409             if (type.flags & 16777216 /* Conditional */) {
60410                 // The root object represents the origin of the conditional type
60411                 return type.root;
60412             }
60413             return undefined;
60414         }
60415         function isPropertyIdenticalTo(sourceProp, targetProp) {
60416             return compareProperties(sourceProp, targetProp, compareTypesIdentical) !== 0 /* False */;
60417         }
60418         function compareProperties(sourceProp, targetProp, compareTypes) {
60419             // Two members are considered identical when
60420             // - they are public properties with identical names, optionality, and types,
60421             // - they are private or protected properties originating in the same declaration and having identical types
60422             if (sourceProp === targetProp) {
60423                 return -1 /* True */;
60424             }
60425             var sourcePropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(sourceProp) & 24 /* NonPublicAccessibilityModifier */;
60426             var targetPropAccessibility = ts.getDeclarationModifierFlagsFromSymbol(targetProp) & 24 /* NonPublicAccessibilityModifier */;
60427             if (sourcePropAccessibility !== targetPropAccessibility) {
60428                 return 0 /* False */;
60429             }
60430             if (sourcePropAccessibility) {
60431                 if (getTargetSymbol(sourceProp) !== getTargetSymbol(targetProp)) {
60432                     return 0 /* False */;
60433                 }
60434             }
60435             else {
60436                 if ((sourceProp.flags & 16777216 /* Optional */) !== (targetProp.flags & 16777216 /* Optional */)) {
60437                     return 0 /* False */;
60438                 }
60439             }
60440             if (isReadonlySymbol(sourceProp) !== isReadonlySymbol(targetProp)) {
60441                 return 0 /* False */;
60442             }
60443             return compareTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
60444         }
60445         function isMatchingSignature(source, target, partialMatch) {
60446             var sourceParameterCount = getParameterCount(source);
60447             var targetParameterCount = getParameterCount(target);
60448             var sourceMinArgumentCount = getMinArgumentCount(source);
60449             var targetMinArgumentCount = getMinArgumentCount(target);
60450             var sourceHasRestParameter = hasEffectiveRestParameter(source);
60451             var targetHasRestParameter = hasEffectiveRestParameter(target);
60452             // A source signature matches a target signature if the two signatures have the same number of required,
60453             // optional, and rest parameters.
60454             if (sourceParameterCount === targetParameterCount &&
60455                 sourceMinArgumentCount === targetMinArgumentCount &&
60456                 sourceHasRestParameter === targetHasRestParameter) {
60457                 return true;
60458             }
60459             // A source signature partially matches a target signature if the target signature has no fewer required
60460             // parameters
60461             if (partialMatch && sourceMinArgumentCount <= targetMinArgumentCount) {
60462                 return true;
60463             }
60464             return false;
60465         }
60466         /**
60467          * See signatureRelatedTo, compareSignaturesIdentical
60468          */
60469         function compareSignaturesIdentical(source, target, partialMatch, ignoreThisTypes, ignoreReturnTypes, compareTypes) {
60470             // TODO (drosen): De-duplicate code between related functions.
60471             if (source === target) {
60472                 return -1 /* True */;
60473             }
60474             if (!(isMatchingSignature(source, target, partialMatch))) {
60475                 return 0 /* False */;
60476             }
60477             // Check that the two signatures have the same number of type parameters.
60478             if (ts.length(source.typeParameters) !== ts.length(target.typeParameters)) {
60479                 return 0 /* False */;
60480             }
60481             // Check that type parameter constraints and defaults match. If they do, instantiate the source
60482             // signature with the type parameters of the target signature and continue the comparison.
60483             if (target.typeParameters) {
60484                 var mapper = createTypeMapper(source.typeParameters, target.typeParameters);
60485                 for (var i = 0; i < target.typeParameters.length; i++) {
60486                     var s = source.typeParameters[i];
60487                     var t = target.typeParameters[i];
60488                     if (!(s === t || compareTypes(instantiateType(getConstraintFromTypeParameter(s), mapper) || unknownType, getConstraintFromTypeParameter(t) || unknownType) &&
60489                         compareTypes(instantiateType(getDefaultFromTypeParameter(s), mapper) || unknownType, getDefaultFromTypeParameter(t) || unknownType))) {
60490                         return 0 /* False */;
60491                     }
60492                 }
60493                 source = instantiateSignature(source, mapper, /*eraseTypeParameters*/ true);
60494             }
60495             var result = -1 /* True */;
60496             if (!ignoreThisTypes) {
60497                 var sourceThisType = getThisTypeOfSignature(source);
60498                 if (sourceThisType) {
60499                     var targetThisType = getThisTypeOfSignature(target);
60500                     if (targetThisType) {
60501                         var related = compareTypes(sourceThisType, targetThisType);
60502                         if (!related) {
60503                             return 0 /* False */;
60504                         }
60505                         result &= related;
60506                     }
60507                 }
60508             }
60509             var targetLen = getParameterCount(target);
60510             for (var i = 0; i < targetLen; i++) {
60511                 var s = getTypeAtPosition(source, i);
60512                 var t = getTypeAtPosition(target, i);
60513                 var related = compareTypes(t, s);
60514                 if (!related) {
60515                     return 0 /* False */;
60516                 }
60517                 result &= related;
60518             }
60519             if (!ignoreReturnTypes) {
60520                 var sourceTypePredicate = getTypePredicateOfSignature(source);
60521                 var targetTypePredicate = getTypePredicateOfSignature(target);
60522                 result &= sourceTypePredicate || targetTypePredicate ?
60523                     compareTypePredicatesIdentical(sourceTypePredicate, targetTypePredicate, compareTypes) :
60524                     compareTypes(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
60525             }
60526             return result;
60527         }
60528         function compareTypePredicatesIdentical(source, target, compareTypes) {
60529             return !(source && target && typePredicateKindsMatch(source, target)) ? 0 /* False */ :
60530                 source.type === target.type ? -1 /* True */ :
60531                     source.type && target.type ? compareTypes(source.type, target.type) :
60532                         0 /* False */;
60533         }
60534         function literalTypesWithSameBaseType(types) {
60535             var commonBaseType;
60536             for (var _i = 0, types_13 = types; _i < types_13.length; _i++) {
60537                 var t = types_13[_i];
60538                 var baseType = getBaseTypeOfLiteralType(t);
60539                 if (!commonBaseType) {
60540                     commonBaseType = baseType;
60541                 }
60542                 if (baseType === t || baseType !== commonBaseType) {
60543                     return false;
60544                 }
60545             }
60546             return true;
60547         }
60548         // When the candidate types are all literal types with the same base type, return a union
60549         // of those literal types. Otherwise, return the leftmost type for which no type to the
60550         // right is a supertype.
60551         function getSupertypeOrUnion(types) {
60552             return literalTypesWithSameBaseType(types) ?
60553                 getUnionType(types) :
60554                 ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(s, t) ? t : s; });
60555         }
60556         function getCommonSupertype(types) {
60557             if (!strictNullChecks) {
60558                 return getSupertypeOrUnion(types);
60559             }
60560             var primaryTypes = ts.filter(types, function (t) { return !(t.flags & 98304 /* Nullable */); });
60561             return primaryTypes.length ?
60562                 getNullableType(getSupertypeOrUnion(primaryTypes), getFalsyFlagsOfTypes(types) & 98304 /* Nullable */) :
60563                 getUnionType(types, 2 /* Subtype */);
60564         }
60565         // Return the leftmost type for which no type to the right is a subtype.
60566         function getCommonSubtype(types) {
60567             return ts.reduceLeft(types, function (s, t) { return isTypeSubtypeOf(t, s) ? t : s; });
60568         }
60569         function isArrayType(type) {
60570             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && (type.target === globalArrayType || type.target === globalReadonlyArrayType);
60571         }
60572         function isReadonlyArrayType(type) {
60573             return !!(ts.getObjectFlags(type) & 4 /* Reference */) && type.target === globalReadonlyArrayType;
60574         }
60575         function isMutableArrayOrTuple(type) {
60576             return isArrayType(type) && !isReadonlyArrayType(type) || isTupleType(type) && !type.target.readonly;
60577         }
60578         function getElementTypeOfArrayType(type) {
60579             return isArrayType(type) ? getTypeArguments(type)[0] : undefined;
60580         }
60581         function isArrayLikeType(type) {
60582             // A type is array-like if it is a reference to the global Array or global ReadonlyArray type,
60583             // or if it is not the undefined or null type and if it is assignable to ReadonlyArray<any>
60584             return isArrayType(type) || !(type.flags & 98304 /* Nullable */) && isTypeAssignableTo(type, anyReadonlyArrayType);
60585         }
60586         function isEmptyArrayLiteralType(type) {
60587             var elementType = isArrayType(type) ? getTypeArguments(type)[0] : undefined;
60588             return elementType === undefinedWideningType || elementType === implicitNeverType;
60589         }
60590         function isTupleLikeType(type) {
60591             return isTupleType(type) || !!getPropertyOfType(type, "0");
60592         }
60593         function isArrayOrTupleLikeType(type) {
60594             return isArrayLikeType(type) || isTupleLikeType(type);
60595         }
60596         function getTupleElementType(type, index) {
60597             var propType = getTypeOfPropertyOfType(type, "" + index);
60598             if (propType) {
60599                 return propType;
60600             }
60601             if (everyType(type, isTupleType)) {
60602                 return mapType(type, function (t) { return getRestTypeOfTupleType(t) || undefinedType; });
60603             }
60604             return undefined;
60605         }
60606         function isNeitherUnitTypeNorNever(type) {
60607             return !(type.flags & (109440 /* Unit */ | 131072 /* Never */));
60608         }
60609         function isUnitType(type) {
60610             return !!(type.flags & 109440 /* Unit */);
60611         }
60612         function isLiteralType(type) {
60613             return type.flags & 16 /* Boolean */ ? true :
60614                 type.flags & 1048576 /* Union */ ? type.flags & 1024 /* EnumLiteral */ ? true : ts.every(type.types, isUnitType) :
60615                     isUnitType(type);
60616         }
60617         function getBaseTypeOfLiteralType(type) {
60618             return type.flags & 1024 /* EnumLiteral */ ? getBaseTypeOfEnumLiteralType(type) :
60619                 type.flags & 128 /* StringLiteral */ ? stringType :
60620                     type.flags & 256 /* NumberLiteral */ ? numberType :
60621                         type.flags & 2048 /* BigIntLiteral */ ? bigintType :
60622                             type.flags & 512 /* BooleanLiteral */ ? booleanType :
60623                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getBaseTypeOfLiteralType)) :
60624                                     type;
60625         }
60626         function getWidenedLiteralType(type) {
60627             return type.flags & 1024 /* EnumLiteral */ && isFreshLiteralType(type) ? getBaseTypeOfEnumLiteralType(type) :
60628                 type.flags & 128 /* StringLiteral */ && isFreshLiteralType(type) ? stringType :
60629                     type.flags & 256 /* NumberLiteral */ && isFreshLiteralType(type) ? numberType :
60630                         type.flags & 2048 /* BigIntLiteral */ && isFreshLiteralType(type) ? bigintType :
60631                             type.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(type) ? booleanType :
60632                                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedLiteralType)) :
60633                                     type;
60634         }
60635         function getWidenedUniqueESSymbolType(type) {
60636             return type.flags & 8192 /* UniqueESSymbol */ ? esSymbolType :
60637                 type.flags & 1048576 /* Union */ ? getUnionType(ts.sameMap(type.types, getWidenedUniqueESSymbolType)) :
60638                     type;
60639         }
60640         function getWidenedLiteralLikeTypeForContextualType(type, contextualType) {
60641             if (!isLiteralOfContextualType(type, contextualType)) {
60642                 type = getWidenedUniqueESSymbolType(getWidenedLiteralType(type));
60643             }
60644             return type;
60645         }
60646         function getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(type, contextualSignatureReturnType, isAsync) {
60647             if (type && isUnitType(type)) {
60648                 var contextualType = !contextualSignatureReturnType ? undefined :
60649                     isAsync ? getPromisedTypeOfPromise(contextualSignatureReturnType) :
60650                         contextualSignatureReturnType;
60651                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
60652             }
60653             return type;
60654         }
60655         function getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(type, contextualSignatureReturnType, kind, isAsyncGenerator) {
60656             if (type && isUnitType(type)) {
60657                 var contextualType = !contextualSignatureReturnType ? undefined :
60658                     getIterationTypeOfGeneratorFunctionReturnType(kind, contextualSignatureReturnType, isAsyncGenerator);
60659                 type = getWidenedLiteralLikeTypeForContextualType(type, contextualType);
60660             }
60661             return type;
60662         }
60663         /**
60664          * Check if a Type was written as a tuple type literal.
60665          * Prefer using isTupleLikeType() unless the use of `elementTypes`/`getTypeArguments` is required.
60666          */
60667         function isTupleType(type) {
60668             return !!(ts.getObjectFlags(type) & 4 /* Reference */ && type.target.objectFlags & 8 /* Tuple */);
60669         }
60670         function isGenericTupleType(type) {
60671             return isTupleType(type) && !!(type.target.combinedFlags & 8 /* Variadic */);
60672         }
60673         function isSingleElementGenericTupleType(type) {
60674             return isGenericTupleType(type) && type.target.elementFlags.length === 1;
60675         }
60676         function getRestTypeOfTupleType(type) {
60677             return getElementTypeOfSliceOfTupleType(type, type.target.fixedLength);
60678         }
60679         function getRestArrayTypeOfTupleType(type) {
60680             var restType = getRestTypeOfTupleType(type);
60681             return restType && createArrayType(restType);
60682         }
60683         function getEndLengthOfType(type) {
60684             return isTupleType(type) ? getTypeReferenceArity(type) - ts.findLastIndex(type.target.elementFlags, function (f) { return !(f & (1 /* Required */ | 2 /* Optional */)); }) - 1 : 0;
60685         }
60686         function getElementTypeOfSliceOfTupleType(type, index, endSkipCount, writing) {
60687             if (endSkipCount === void 0) { endSkipCount = 0; }
60688             if (writing === void 0) { writing = false; }
60689             var length = getTypeReferenceArity(type) - endSkipCount;
60690             if (index < length) {
60691                 var typeArguments = getTypeArguments(type);
60692                 var elementTypes = [];
60693                 for (var i = index; i < length; i++) {
60694                     var t = typeArguments[i];
60695                     elementTypes.push(type.target.elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessType(t, numberType) : t);
60696                 }
60697                 return writing ? getIntersectionType(elementTypes) : getUnionType(elementTypes);
60698             }
60699             return undefined;
60700         }
60701         function isTupleTypeStructureMatching(t1, t2) {
60702             return getTypeReferenceArity(t1) === getTypeReferenceArity(t2) &&
60703                 ts.every(t1.target.elementFlags, function (f, i) { return (f & 12 /* Variable */) === (t2.target.elementFlags[i] & 12 /* Variable */); });
60704         }
60705         function isZeroBigInt(_a) {
60706             var value = _a.value;
60707             return value.base10Value === "0";
60708         }
60709         function getFalsyFlagsOfTypes(types) {
60710             var result = 0;
60711             for (var _i = 0, types_14 = types; _i < types_14.length; _i++) {
60712                 var t = types_14[_i];
60713                 result |= getFalsyFlags(t);
60714             }
60715             return result;
60716         }
60717         // Returns the String, Number, Boolean, StringLiteral, NumberLiteral, BooleanLiteral, Void, Undefined, or Null
60718         // flags for the string, number, boolean, "", 0, false, void, undefined, or null types respectively. Returns
60719         // no flags for all other types (including non-falsy literal types).
60720         function getFalsyFlags(type) {
60721             return type.flags & 1048576 /* Union */ ? getFalsyFlagsOfTypes(type.types) :
60722                 type.flags & 128 /* StringLiteral */ ? type.value === "" ? 128 /* StringLiteral */ : 0 :
60723                     type.flags & 256 /* NumberLiteral */ ? type.value === 0 ? 256 /* NumberLiteral */ : 0 :
60724                         type.flags & 2048 /* BigIntLiteral */ ? isZeroBigInt(type) ? 2048 /* BigIntLiteral */ : 0 :
60725                             type.flags & 512 /* BooleanLiteral */ ? (type === falseType || type === regularFalseType) ? 512 /* BooleanLiteral */ : 0 :
60726                                 type.flags & 117724 /* PossiblyFalsy */;
60727         }
60728         function removeDefinitelyFalsyTypes(type) {
60729             return getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ ?
60730                 filterType(type, function (t) { return !(getFalsyFlags(t) & 117632 /* DefinitelyFalsy */); }) :
60731                 type;
60732         }
60733         function extractDefinitelyFalsyTypes(type) {
60734             return mapType(type, getDefinitelyFalsyPartOfType);
60735         }
60736         function getDefinitelyFalsyPartOfType(type) {
60737             return type.flags & 4 /* String */ ? emptyStringType :
60738                 type.flags & 8 /* Number */ ? zeroType :
60739                     type.flags & 64 /* BigInt */ ? zeroBigIntType :
60740                         type === regularFalseType ||
60741                             type === falseType ||
60742                             type.flags & (16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */ | 3 /* AnyOrUnknown */) ||
60743                             type.flags & 128 /* StringLiteral */ && type.value === "" ||
60744                             type.flags & 256 /* NumberLiteral */ && type.value === 0 ||
60745                             type.flags & 2048 /* BigIntLiteral */ && isZeroBigInt(type) ? type :
60746                             neverType;
60747         }
60748         /**
60749          * Add undefined or null or both to a type if they are missing.
60750          * @param type - type to add undefined and/or null to if not present
60751          * @param flags - Either TypeFlags.Undefined or TypeFlags.Null, or both
60752          */
60753         function getNullableType(type, flags) {
60754             var missing = (flags & ~type.flags) & (32768 /* Undefined */ | 65536 /* Null */);
60755             return missing === 0 ? type :
60756                 missing === 32768 /* Undefined */ ? getUnionType([type, undefinedType]) :
60757                     missing === 65536 /* Null */ ? getUnionType([type, nullType]) :
60758                         getUnionType([type, undefinedType, nullType]);
60759         }
60760         function getOptionalType(type) {
60761             ts.Debug.assert(strictNullChecks);
60762             return type.flags & 32768 /* Undefined */ ? type : getUnionType([type, undefinedType]);
60763         }
60764         function getGlobalNonNullableTypeInstantiation(type) {
60765             if (!deferredGlobalNonNullableTypeAlias) {
60766                 deferredGlobalNonNullableTypeAlias = getGlobalSymbol("NonNullable", 524288 /* TypeAlias */, /*diagnostic*/ undefined) || unknownSymbol;
60767             }
60768             // Use NonNullable global type alias if available to improve quick info/declaration emit
60769             if (deferredGlobalNonNullableTypeAlias !== unknownSymbol) {
60770                 return getTypeAliasInstantiation(deferredGlobalNonNullableTypeAlias, [type]);
60771             }
60772             return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */); // Type alias unavailable, fall back to non-higher-order behavior
60773         }
60774         function getNonNullableType(type) {
60775             return strictNullChecks ? getGlobalNonNullableTypeInstantiation(type) : type;
60776         }
60777         function addOptionalTypeMarker(type) {
60778             return strictNullChecks ? getUnionType([type, optionalType]) : type;
60779         }
60780         function isNotOptionalTypeMarker(type) {
60781             return type !== optionalType;
60782         }
60783         function removeOptionalTypeMarker(type) {
60784             return strictNullChecks ? filterType(type, isNotOptionalTypeMarker) : type;
60785         }
60786         function propagateOptionalTypeMarker(type, node, wasOptional) {
60787             return wasOptional ? ts.isOutermostOptionalChain(node) ? getOptionalType(type) : addOptionalTypeMarker(type) : type;
60788         }
60789         function getOptionalExpressionType(exprType, expression) {
60790             return ts.isExpressionOfOptionalChainRoot(expression) ? getNonNullableType(exprType) :
60791                 ts.isOptionalChain(expression) ? removeOptionalTypeMarker(exprType) :
60792                     exprType;
60793         }
60794         /**
60795          * Is source potentially coercible to target type under `==`.
60796          * Assumes that `source` is a constituent of a union, hence
60797          * the boolean literal flag on the LHS, but not on the RHS.
60798          *
60799          * This does not fully replicate the semantics of `==`. The
60800          * intention is to catch cases that are clearly not right.
60801          *
60802          * Comparing (string | number) to number should not remove the
60803          * string element.
60804          *
60805          * Comparing (string | number) to 1 will remove the string
60806          * element, though this is not sound. This is a pragmatic
60807          * choice.
60808          *
60809          * @see narrowTypeByEquality
60810          *
60811          * @param source
60812          * @param target
60813          */
60814         function isCoercibleUnderDoubleEquals(source, target) {
60815             return ((source.flags & (8 /* Number */ | 4 /* String */ | 512 /* BooleanLiteral */)) !== 0)
60816                 && ((target.flags & (8 /* Number */ | 4 /* String */ | 16 /* Boolean */)) !== 0);
60817         }
60818         /**
60819          * Return true if type was inferred from an object literal, written as an object type literal, or is the shape of a module
60820          * with no call or construct signatures.
60821          */
60822         function isObjectTypeWithInferableIndex(type) {
60823             return type.flags & 2097152 /* Intersection */ ? ts.every(type.types, isObjectTypeWithInferableIndex) :
60824                 !!(type.symbol && (type.symbol.flags & (4096 /* ObjectLiteral */ | 2048 /* TypeLiteral */ | 384 /* Enum */ | 512 /* ValueModule */)) !== 0 &&
60825                     !typeHasCallOrConstructSignatures(type)) || !!(ts.getObjectFlags(type) & 2048 /* ReverseMapped */ && isObjectTypeWithInferableIndex(type.source));
60826         }
60827         function createSymbolWithType(source, type) {
60828             var symbol = createSymbol(source.flags, source.escapedName, ts.getCheckFlags(source) & 8 /* Readonly */);
60829             symbol.declarations = source.declarations;
60830             symbol.parent = source.parent;
60831             symbol.type = type;
60832             symbol.target = source;
60833             if (source.valueDeclaration) {
60834                 symbol.valueDeclaration = source.valueDeclaration;
60835             }
60836             var nameType = getSymbolLinks(source).nameType;
60837             if (nameType) {
60838                 symbol.nameType = nameType;
60839             }
60840             return symbol;
60841         }
60842         function transformTypeOfMembers(type, f) {
60843             var members = ts.createSymbolTable();
60844             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
60845                 var property = _a[_i];
60846                 var original = getTypeOfSymbol(property);
60847                 var updated = f(original);
60848                 members.set(property.escapedName, updated === original ? property : createSymbolWithType(property, updated));
60849             }
60850             return members;
60851         }
60852         /**
60853          * If the the provided object literal is subject to the excess properties check,
60854          * create a new that is exempt. Recursively mark object literal members as exempt.
60855          * Leave signatures alone since they are not subject to the check.
60856          */
60857         function getRegularTypeOfObjectLiteral(type) {
60858             if (!(isObjectLiteralType(type) && ts.getObjectFlags(type) & 32768 /* FreshLiteral */)) {
60859                 return type;
60860             }
60861             var regularType = type.regularType;
60862             if (regularType) {
60863                 return regularType;
60864             }
60865             var resolved = type;
60866             var members = transformTypeOfMembers(type, getRegularTypeOfObjectLiteral);
60867             var regularNew = createAnonymousType(resolved.symbol, members, resolved.callSignatures, resolved.constructSignatures, resolved.stringIndexInfo, resolved.numberIndexInfo);
60868             regularNew.flags = resolved.flags;
60869             regularNew.objectFlags |= resolved.objectFlags & ~32768 /* FreshLiteral */;
60870             type.regularType = regularNew;
60871             return regularNew;
60872         }
60873         function createWideningContext(parent, propertyName, siblings) {
60874             return { parent: parent, propertyName: propertyName, siblings: siblings, resolvedProperties: undefined };
60875         }
60876         function getSiblingsOfContext(context) {
60877             if (!context.siblings) {
60878                 var siblings_1 = [];
60879                 for (var _i = 0, _a = getSiblingsOfContext(context.parent); _i < _a.length; _i++) {
60880                     var type = _a[_i];
60881                     if (isObjectLiteralType(type)) {
60882                         var prop = getPropertyOfObjectType(type, context.propertyName);
60883                         if (prop) {
60884                             forEachType(getTypeOfSymbol(prop), function (t) {
60885                                 siblings_1.push(t);
60886                             });
60887                         }
60888                     }
60889                 }
60890                 context.siblings = siblings_1;
60891             }
60892             return context.siblings;
60893         }
60894         function getPropertiesOfContext(context) {
60895             if (!context.resolvedProperties) {
60896                 var names = new ts.Map();
60897                 for (var _i = 0, _a = getSiblingsOfContext(context); _i < _a.length; _i++) {
60898                     var t = _a[_i];
60899                     if (isObjectLiteralType(t) && !(ts.getObjectFlags(t) & 1024 /* ContainsSpread */)) {
60900                         for (var _b = 0, _c = getPropertiesOfType(t); _b < _c.length; _b++) {
60901                             var prop = _c[_b];
60902                             names.set(prop.escapedName, prop);
60903                         }
60904                     }
60905                 }
60906                 context.resolvedProperties = ts.arrayFrom(names.values());
60907             }
60908             return context.resolvedProperties;
60909         }
60910         function getWidenedProperty(prop, context) {
60911             if (!(prop.flags & 4 /* Property */)) {
60912                 // Since get accessors already widen their return value there is no need to
60913                 // widen accessor based properties here.
60914                 return prop;
60915             }
60916             var original = getTypeOfSymbol(prop);
60917             var propContext = context && createWideningContext(context, prop.escapedName, /*siblings*/ undefined);
60918             var widened = getWidenedTypeWithContext(original, propContext);
60919             return widened === original ? prop : createSymbolWithType(prop, widened);
60920         }
60921         function getUndefinedProperty(prop) {
60922             var cached = undefinedProperties.get(prop.escapedName);
60923             if (cached) {
60924                 return cached;
60925             }
60926             var result = createSymbolWithType(prop, undefinedType);
60927             result.flags |= 16777216 /* Optional */;
60928             undefinedProperties.set(prop.escapedName, result);
60929             return result;
60930         }
60931         function getWidenedTypeOfObjectLiteral(type, context) {
60932             var members = ts.createSymbolTable();
60933             for (var _i = 0, _a = getPropertiesOfObjectType(type); _i < _a.length; _i++) {
60934                 var prop = _a[_i];
60935                 members.set(prop.escapedName, getWidenedProperty(prop, context));
60936             }
60937             if (context) {
60938                 for (var _b = 0, _c = getPropertiesOfContext(context); _b < _c.length; _b++) {
60939                     var prop = _c[_b];
60940                     if (!members.has(prop.escapedName)) {
60941                         members.set(prop.escapedName, getUndefinedProperty(prop));
60942                     }
60943                 }
60944             }
60945             var stringIndexInfo = getIndexInfoOfType(type, 0 /* String */);
60946             var numberIndexInfo = getIndexInfoOfType(type, 1 /* Number */);
60947             var result = createAnonymousType(type.symbol, members, ts.emptyArray, ts.emptyArray, stringIndexInfo && createIndexInfo(getWidenedType(stringIndexInfo.type), stringIndexInfo.isReadonly), numberIndexInfo && createIndexInfo(getWidenedType(numberIndexInfo.type), numberIndexInfo.isReadonly));
60948             result.objectFlags |= (ts.getObjectFlags(type) & (16384 /* JSLiteral */ | 2097152 /* NonInferrableType */)); // Retain js literal flag through widening
60949             return result;
60950         }
60951         function getWidenedType(type) {
60952             return getWidenedTypeWithContext(type, /*context*/ undefined);
60953         }
60954         function getWidenedTypeWithContext(type, context) {
60955             if (ts.getObjectFlags(type) & 1572864 /* RequiresWidening */) {
60956                 if (context === undefined && type.widened) {
60957                     return type.widened;
60958                 }
60959                 var result = void 0;
60960                 if (type.flags & (1 /* Any */ | 98304 /* Nullable */)) {
60961                     result = anyType;
60962                 }
60963                 else if (isObjectLiteralType(type)) {
60964                     result = getWidenedTypeOfObjectLiteral(type, context);
60965                 }
60966                 else if (type.flags & 1048576 /* Union */) {
60967                     var unionContext_1 = context || createWideningContext(/*parent*/ undefined, /*propertyName*/ undefined, type.types);
60968                     var widenedTypes = ts.sameMap(type.types, function (t) { return t.flags & 98304 /* Nullable */ ? t : getWidenedTypeWithContext(t, unionContext_1); });
60969                     // Widening an empty object literal transitions from a highly restrictive type to
60970                     // a highly inclusive one. For that reason we perform subtype reduction here if the
60971                     // union includes empty object types (e.g. reducing {} | string to just {}).
60972                     result = getUnionType(widenedTypes, ts.some(widenedTypes, isEmptyObjectType) ? 2 /* Subtype */ : 1 /* Literal */);
60973                 }
60974                 else if (type.flags & 2097152 /* Intersection */) {
60975                     result = getIntersectionType(ts.sameMap(type.types, getWidenedType));
60976                 }
60977                 else if (isArrayType(type) || isTupleType(type)) {
60978                     result = createTypeReference(type.target, ts.sameMap(getTypeArguments(type), getWidenedType));
60979                 }
60980                 if (result && context === undefined) {
60981                     type.widened = result;
60982                 }
60983                 return result || type;
60984             }
60985             return type;
60986         }
60987         /**
60988          * Reports implicit any errors that occur as a result of widening 'null' and 'undefined'
60989          * to 'any'. A call to reportWideningErrorsInType is normally accompanied by a call to
60990          * getWidenedType. But in some cases getWidenedType is called without reporting errors
60991          * (type argument inference is an example).
60992          *
60993          * The return value indicates whether an error was in fact reported. The particular circumstances
60994          * are on a best effort basis. Currently, if the null or undefined that causes widening is inside
60995          * an object literal property (arbitrarily deeply), this function reports an error. If no error is
60996          * reported, reportImplicitAnyError is a suitable fallback to report a general error.
60997          */
60998         function reportWideningErrorsInType(type) {
60999             var errorReported = false;
61000             if (ts.getObjectFlags(type) & 524288 /* ContainsWideningType */) {
61001                 if (type.flags & 1048576 /* Union */) {
61002                     if (ts.some(type.types, isEmptyObjectType)) {
61003                         errorReported = true;
61004                     }
61005                     else {
61006                         for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
61007                             var t = _a[_i];
61008                             if (reportWideningErrorsInType(t)) {
61009                                 errorReported = true;
61010                             }
61011                         }
61012                     }
61013                 }
61014                 if (isArrayType(type) || isTupleType(type)) {
61015                     for (var _b = 0, _c = getTypeArguments(type); _b < _c.length; _b++) {
61016                         var t = _c[_b];
61017                         if (reportWideningErrorsInType(t)) {
61018                             errorReported = true;
61019                         }
61020                     }
61021                 }
61022                 if (isObjectLiteralType(type)) {
61023                     for (var _d = 0, _e = getPropertiesOfObjectType(type); _d < _e.length; _d++) {
61024                         var p = _e[_d];
61025                         var t = getTypeOfSymbol(p);
61026                         if (ts.getObjectFlags(t) & 524288 /* ContainsWideningType */) {
61027                             if (!reportWideningErrorsInType(t)) {
61028                                 error(p.valueDeclaration, ts.Diagnostics.Object_literal_s_property_0_implicitly_has_an_1_type, symbolToString(p), typeToString(getWidenedType(t)));
61029                             }
61030                             errorReported = true;
61031                         }
61032                     }
61033                 }
61034             }
61035             return errorReported;
61036         }
61037         function reportImplicitAny(declaration, type, wideningKind) {
61038             var typeAsString = typeToString(getWidenedType(type));
61039             if (ts.isInJSFile(declaration) && !ts.isCheckJsEnabledForFile(ts.getSourceFileOfNode(declaration), compilerOptions)) {
61040                 // Only report implicit any errors/suggestions in TS and ts-check JS files
61041                 return;
61042             }
61043             var diagnostic;
61044             switch (declaration.kind) {
61045                 case 216 /* BinaryExpression */:
61046                 case 163 /* PropertyDeclaration */:
61047                 case 162 /* PropertySignature */:
61048                     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;
61049                     break;
61050                 case 160 /* Parameter */:
61051                     var param = declaration;
61052                     if (ts.isIdentifier(param.name) &&
61053                         (ts.isCallSignatureDeclaration(param.parent) || ts.isMethodSignature(param.parent) || ts.isFunctionTypeNode(param.parent)) &&
61054                         param.parent.parameters.indexOf(param) > -1 &&
61055                         (resolveName(param, param.name.escapedText, 788968 /* Type */, undefined, param.name.escapedText, /*isUse*/ true) ||
61056                             param.name.originalKeywordKind && ts.isTypeNodeKind(param.name.originalKeywordKind))) {
61057                         var newName = "arg" + param.parent.parameters.indexOf(param);
61058                         errorOrSuggestion(noImplicitAny, declaration, ts.Diagnostics.Parameter_has_a_name_but_no_type_Did_you_mean_0_Colon_1, newName, ts.declarationNameToString(param.name));
61059                         return;
61060                     }
61061                     diagnostic = declaration.dotDotDotToken ?
61062                         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 :
61063                         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;
61064                     break;
61065                 case 198 /* BindingElement */:
61066                     diagnostic = ts.Diagnostics.Binding_element_0_implicitly_has_an_1_type;
61067                     if (!noImplicitAny) {
61068                         // Don't issue a suggestion for binding elements since the codefix doesn't yet support them.
61069                         return;
61070                     }
61071                     break;
61072                 case 308 /* JSDocFunctionType */:
61073                     error(declaration, ts.Diagnostics.Function_type_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
61074                     return;
61075                 case 251 /* FunctionDeclaration */:
61076                 case 165 /* MethodDeclaration */:
61077                 case 164 /* MethodSignature */:
61078                 case 167 /* GetAccessor */:
61079                 case 168 /* SetAccessor */:
61080                 case 208 /* FunctionExpression */:
61081                 case 209 /* ArrowFunction */:
61082                     if (noImplicitAny && !declaration.name) {
61083                         if (wideningKind === 3 /* GeneratorYield */) {
61084                             error(declaration, ts.Diagnostics.Generator_implicitly_has_yield_type_0_because_it_does_not_yield_any_values_Consider_supplying_a_return_type_annotation, typeAsString);
61085                         }
61086                         else {
61087                             error(declaration, ts.Diagnostics.Function_expression_which_lacks_return_type_annotation_implicitly_has_an_0_return_type, typeAsString);
61088                         }
61089                         return;
61090                     }
61091                     diagnostic = !noImplicitAny ? ts.Diagnostics._0_implicitly_has_an_1_return_type_but_a_better_type_may_be_inferred_from_usage :
61092                         wideningKind === 3 /* GeneratorYield */ ? ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_yield_type :
61093                             ts.Diagnostics._0_which_lacks_return_type_annotation_implicitly_has_an_1_return_type;
61094                     break;
61095                 case 190 /* MappedType */:
61096                     if (noImplicitAny) {
61097                         error(declaration, ts.Diagnostics.Mapped_object_type_implicitly_has_an_any_template_type);
61098                     }
61099                     return;
61100                 default:
61101                     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;
61102             }
61103             errorOrSuggestion(noImplicitAny, declaration, diagnostic, ts.declarationNameToString(ts.getNameOfDeclaration(declaration)), typeAsString);
61104         }
61105         function reportErrorsFromWidening(declaration, type, wideningKind) {
61106             if (produceDiagnostics && noImplicitAny && ts.getObjectFlags(type) & 524288 /* ContainsWideningType */ && (!wideningKind || !getContextualSignatureForFunctionLikeDeclaration(declaration))) {
61107                 // Report implicit any error within type if possible, otherwise report error on declaration
61108                 if (!reportWideningErrorsInType(type)) {
61109                     reportImplicitAny(declaration, type, wideningKind);
61110                 }
61111             }
61112         }
61113         function applyToParameterTypes(source, target, callback) {
61114             var sourceCount = getParameterCount(source);
61115             var targetCount = getParameterCount(target);
61116             var sourceRestType = getEffectiveRestType(source);
61117             var targetRestType = getEffectiveRestType(target);
61118             var targetNonRestCount = targetRestType ? targetCount - 1 : targetCount;
61119             var paramCount = sourceRestType ? targetNonRestCount : Math.min(sourceCount, targetNonRestCount);
61120             var sourceThisType = getThisTypeOfSignature(source);
61121             if (sourceThisType) {
61122                 var targetThisType = getThisTypeOfSignature(target);
61123                 if (targetThisType) {
61124                     callback(sourceThisType, targetThisType);
61125                 }
61126             }
61127             for (var i = 0; i < paramCount; i++) {
61128                 callback(getTypeAtPosition(source, i), getTypeAtPosition(target, i));
61129             }
61130             if (targetRestType) {
61131                 callback(getRestTypeAtPosition(source, paramCount), targetRestType);
61132             }
61133         }
61134         function applyToReturnTypes(source, target, callback) {
61135             var sourceTypePredicate = getTypePredicateOfSignature(source);
61136             var targetTypePredicate = getTypePredicateOfSignature(target);
61137             if (sourceTypePredicate && targetTypePredicate && typePredicateKindsMatch(sourceTypePredicate, targetTypePredicate) && sourceTypePredicate.type && targetTypePredicate.type) {
61138                 callback(sourceTypePredicate.type, targetTypePredicate.type);
61139             }
61140             else {
61141                 callback(getReturnTypeOfSignature(source), getReturnTypeOfSignature(target));
61142             }
61143         }
61144         function createInferenceContext(typeParameters, signature, flags, compareTypes) {
61145             return createInferenceContextWorker(typeParameters.map(createInferenceInfo), signature, flags, compareTypes || compareTypesAssignable);
61146         }
61147         function cloneInferenceContext(context, extraFlags) {
61148             if (extraFlags === void 0) { extraFlags = 0; }
61149             return context && createInferenceContextWorker(ts.map(context.inferences, cloneInferenceInfo), context.signature, context.flags | extraFlags, context.compareTypes);
61150         }
61151         function createInferenceContextWorker(inferences, signature, flags, compareTypes) {
61152             var context = {
61153                 inferences: inferences,
61154                 signature: signature,
61155                 flags: flags,
61156                 compareTypes: compareTypes,
61157                 mapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ true); }),
61158                 nonFixingMapper: makeFunctionTypeMapper(function (t) { return mapToInferredType(context, t, /*fix*/ false); }),
61159             };
61160             return context;
61161         }
61162         function mapToInferredType(context, t, fix) {
61163             var inferences = context.inferences;
61164             for (var i = 0; i < inferences.length; i++) {
61165                 var inference = inferences[i];
61166                 if (t === inference.typeParameter) {
61167                     if (fix && !inference.isFixed) {
61168                         clearCachedInferences(inferences);
61169                         inference.isFixed = true;
61170                     }
61171                     return getInferredType(context, i);
61172                 }
61173             }
61174             return t;
61175         }
61176         function clearCachedInferences(inferences) {
61177             for (var _i = 0, inferences_1 = inferences; _i < inferences_1.length; _i++) {
61178                 var inference = inferences_1[_i];
61179                 if (!inference.isFixed) {
61180                     inference.inferredType = undefined;
61181                 }
61182             }
61183         }
61184         function createInferenceInfo(typeParameter) {
61185             return {
61186                 typeParameter: typeParameter,
61187                 candidates: undefined,
61188                 contraCandidates: undefined,
61189                 inferredType: undefined,
61190                 priority: undefined,
61191                 topLevel: true,
61192                 isFixed: false,
61193                 impliedArity: undefined
61194             };
61195         }
61196         function cloneInferenceInfo(inference) {
61197             return {
61198                 typeParameter: inference.typeParameter,
61199                 candidates: inference.candidates && inference.candidates.slice(),
61200                 contraCandidates: inference.contraCandidates && inference.contraCandidates.slice(),
61201                 inferredType: inference.inferredType,
61202                 priority: inference.priority,
61203                 topLevel: inference.topLevel,
61204                 isFixed: inference.isFixed,
61205                 impliedArity: inference.impliedArity
61206             };
61207         }
61208         function cloneInferredPartOfContext(context) {
61209             var inferences = ts.filter(context.inferences, hasInferenceCandidates);
61210             return inferences.length ?
61211                 createInferenceContextWorker(ts.map(inferences, cloneInferenceInfo), context.signature, context.flags, context.compareTypes) :
61212                 undefined;
61213         }
61214         function getMapperFromContext(context) {
61215             return context && context.mapper;
61216         }
61217         // Return true if the given type could possibly reference a type parameter for which
61218         // we perform type inference (i.e. a type parameter of a generic function). We cache
61219         // results for union and intersection types for performance reasons.
61220         function couldContainTypeVariables(type) {
61221             var objectFlags = ts.getObjectFlags(type);
61222             if (objectFlags & 67108864 /* CouldContainTypeVariablesComputed */) {
61223                 return !!(objectFlags & 134217728 /* CouldContainTypeVariables */);
61224             }
61225             var result = !!(type.flags & 465829888 /* Instantiable */ ||
61226                 type.flags & 524288 /* Object */ && !isNonGenericTopLevelType(type) && (objectFlags & 4 /* Reference */ && (type.node || ts.forEach(getTypeArguments(type), couldContainTypeVariables)) ||
61227                     objectFlags & 16 /* Anonymous */ && type.symbol && type.symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 2048 /* TypeLiteral */ | 4096 /* ObjectLiteral */) && type.symbol.declarations ||
61228                     objectFlags & (32 /* Mapped */ | 131072 /* ObjectRestType */)) ||
61229                 type.flags & 3145728 /* UnionOrIntersection */ && !(type.flags & 1024 /* EnumLiteral */) && !isNonGenericTopLevelType(type) && ts.some(type.types, couldContainTypeVariables));
61230             if (type.flags & 3899393 /* ObjectFlagsType */) {
61231                 type.objectFlags |= 67108864 /* CouldContainTypeVariablesComputed */ | (result ? 134217728 /* CouldContainTypeVariables */ : 0);
61232             }
61233             return result;
61234         }
61235         function isNonGenericTopLevelType(type) {
61236             if (type.aliasSymbol && !type.aliasTypeArguments) {
61237                 var declaration = ts.getDeclarationOfKind(type.aliasSymbol, 254 /* TypeAliasDeclaration */);
61238                 return !!(declaration && ts.findAncestor(declaration.parent, function (n) { return n.kind === 297 /* SourceFile */ ? true : n.kind === 256 /* ModuleDeclaration */ ? false : "quit"; }));
61239             }
61240             return false;
61241         }
61242         function isTypeParameterAtTopLevel(type, typeParameter) {
61243             return !!(type === typeParameter ||
61244                 type.flags & 3145728 /* UnionOrIntersection */ && ts.some(type.types, function (t) { return isTypeParameterAtTopLevel(t, typeParameter); }) ||
61245                 type.flags & 16777216 /* Conditional */ && (getTrueTypeFromConditionalType(type) === typeParameter || getFalseTypeFromConditionalType(type) === typeParameter));
61246         }
61247         /** Create an object with properties named in the string literal type. Every property has type `any` */
61248         function createEmptyObjectTypeFromStringLiteral(type) {
61249             var members = ts.createSymbolTable();
61250             forEachType(type, function (t) {
61251                 if (!(t.flags & 128 /* StringLiteral */)) {
61252                     return;
61253                 }
61254                 var name = ts.escapeLeadingUnderscores(t.value);
61255                 var literalProp = createSymbol(4 /* Property */, name);
61256                 literalProp.type = anyType;
61257                 if (t.symbol) {
61258                     literalProp.declarations = t.symbol.declarations;
61259                     literalProp.valueDeclaration = t.symbol.valueDeclaration;
61260                 }
61261                 members.set(name, literalProp);
61262             });
61263             var indexInfo = type.flags & 4 /* String */ ? createIndexInfo(emptyObjectType, /*isReadonly*/ false) : undefined;
61264             return createAnonymousType(undefined, members, ts.emptyArray, ts.emptyArray, indexInfo, undefined);
61265         }
61266         /**
61267          * Infer a suitable input type for a homomorphic mapped type { [P in keyof T]: X }. We construct
61268          * an object type with the same set of properties as the source type, where the type of each
61269          * property is computed by inferring from the source property type to X for the type
61270          * variable T[P] (i.e. we treat the type T[P] as the type variable we're inferring for).
61271          */
61272         function inferTypeForHomomorphicMappedType(source, target, constraint) {
61273             if (inInferTypeForHomomorphicMappedType) {
61274                 return undefined;
61275             }
61276             var key = source.id + "," + target.id + "," + constraint.id;
61277             if (reverseMappedCache.has(key)) {
61278                 return reverseMappedCache.get(key);
61279             }
61280             inInferTypeForHomomorphicMappedType = true;
61281             var type = createReverseMappedType(source, target, constraint);
61282             inInferTypeForHomomorphicMappedType = false;
61283             reverseMappedCache.set(key, type);
61284             return type;
61285         }
61286         // We consider a type to be partially inferable if it isn't marked non-inferable or if it is
61287         // an object literal type with at least one property of an inferable type. For example, an object
61288         // literal { a: 123, b: x => true } is marked non-inferable because it contains a context sensitive
61289         // arrow function, but is considered partially inferable because property 'a' has an inferable type.
61290         function isPartiallyInferableType(type) {
61291             return !(ts.getObjectFlags(type) & 2097152 /* NonInferrableType */) ||
61292                 isObjectLiteralType(type) && ts.some(getPropertiesOfType(type), function (prop) { return isPartiallyInferableType(getTypeOfSymbol(prop)); }) ||
61293                 isTupleType(type) && ts.some(getTypeArguments(type), isPartiallyInferableType);
61294         }
61295         function createReverseMappedType(source, target, constraint) {
61296             // We consider a source type reverse mappable if it has a string index signature or if
61297             // it has one or more properties and is of a partially inferable type.
61298             if (!(getIndexInfoOfType(source, 0 /* String */) || getPropertiesOfType(source).length !== 0 && isPartiallyInferableType(source))) {
61299                 return undefined;
61300             }
61301             // For arrays and tuples we infer new arrays and tuples where the reverse mapping has been
61302             // applied to the element type(s).
61303             if (isArrayType(source)) {
61304                 return createArrayType(inferReverseMappedType(getTypeArguments(source)[0], target, constraint), isReadonlyArrayType(source));
61305             }
61306             if (isTupleType(source)) {
61307                 var elementTypes = ts.map(getTypeArguments(source), function (t) { return inferReverseMappedType(t, target, constraint); });
61308                 var elementFlags = getMappedTypeModifiers(target) & 4 /* IncludeOptional */ ?
61309                     ts.sameMap(source.target.elementFlags, function (f) { return f & 2 /* Optional */ ? 1 /* Required */ : f; }) :
61310                     source.target.elementFlags;
61311                 return createTupleType(elementTypes, elementFlags, source.target.readonly, source.target.labeledElementDeclarations);
61312             }
61313             // For all other object types we infer a new object type where the reverse mapping has been
61314             // applied to the type of each property.
61315             var reversed = createObjectType(2048 /* ReverseMapped */ | 16 /* Anonymous */, /*symbol*/ undefined);
61316             reversed.source = source;
61317             reversed.mappedType = target;
61318             reversed.constraintType = constraint;
61319             return reversed;
61320         }
61321         function getTypeOfReverseMappedSymbol(symbol) {
61322             return inferReverseMappedType(symbol.propertyType, symbol.mappedType, symbol.constraintType);
61323         }
61324         function inferReverseMappedType(sourceType, target, constraint) {
61325             var typeParameter = getIndexedAccessType(constraint.type, getTypeParameterFromMappedType(target));
61326             var templateType = getTemplateTypeFromMappedType(target);
61327             var inference = createInferenceInfo(typeParameter);
61328             inferTypes([inference], sourceType, templateType);
61329             return getTypeFromInference(inference) || unknownType;
61330         }
61331         function getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties) {
61332             var properties, _i, properties_2, targetProp, sourceProp, targetType, sourceType;
61333             return __generator(this, function (_a) {
61334                 switch (_a.label) {
61335                     case 0:
61336                         properties = getPropertiesOfType(target);
61337                         _i = 0, properties_2 = properties;
61338                         _a.label = 1;
61339                     case 1:
61340                         if (!(_i < properties_2.length)) return [3 /*break*/, 6];
61341                         targetProp = properties_2[_i];
61342                         // TODO: remove this when we support static private identifier fields and find other solutions to get privateNamesAndStaticFields test to pass
61343                         if (isStaticPrivateIdentifierProperty(targetProp)) {
61344                             return [3 /*break*/, 5];
61345                         }
61346                         if (!(requireOptionalProperties || !(targetProp.flags & 16777216 /* Optional */ || ts.getCheckFlags(targetProp) & 48 /* Partial */))) return [3 /*break*/, 5];
61347                         sourceProp = getPropertyOfType(source, targetProp.escapedName);
61348                         if (!!sourceProp) return [3 /*break*/, 3];
61349                         return [4 /*yield*/, targetProp];
61350                     case 2:
61351                         _a.sent();
61352                         return [3 /*break*/, 5];
61353                     case 3:
61354                         if (!matchDiscriminantProperties) return [3 /*break*/, 5];
61355                         targetType = getTypeOfSymbol(targetProp);
61356                         if (!(targetType.flags & 109440 /* Unit */)) return [3 /*break*/, 5];
61357                         sourceType = getTypeOfSymbol(sourceProp);
61358                         if (!!(sourceType.flags & 1 /* Any */ || getRegularTypeOfLiteralType(sourceType) === getRegularTypeOfLiteralType(targetType))) return [3 /*break*/, 5];
61359                         return [4 /*yield*/, targetProp];
61360                     case 4:
61361                         _a.sent();
61362                         _a.label = 5;
61363                     case 5:
61364                         _i++;
61365                         return [3 /*break*/, 1];
61366                     case 6: return [2 /*return*/];
61367                 }
61368             });
61369         }
61370         function getUnmatchedProperty(source, target, requireOptionalProperties, matchDiscriminantProperties) {
61371             var result = getUnmatchedProperties(source, target, requireOptionalProperties, matchDiscriminantProperties).next();
61372             if (!result.done)
61373                 return result.value;
61374         }
61375         function tupleTypesDefinitelyUnrelated(source, target) {
61376             return !(target.target.combinedFlags & 8 /* Variadic */) && target.target.minLength > source.target.minLength ||
61377                 !target.target.hasRestElement && (source.target.hasRestElement || target.target.fixedLength < source.target.fixedLength);
61378         }
61379         function typesDefinitelyUnrelated(source, target) {
61380             // Two tuple types with incompatible arities are definitely unrelated.
61381             // Two object types that each have a property that is unmatched in the other are definitely unrelated.
61382             return isTupleType(source) && isTupleType(target) ? tupleTypesDefinitelyUnrelated(source, target) :
61383                 !!getUnmatchedProperty(source, target, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true) &&
61384                     !!getUnmatchedProperty(target, source, /*requireOptionalProperties*/ false, /*matchDiscriminantProperties*/ true);
61385         }
61386         function getTypeFromInference(inference) {
61387             return inference.candidates ? getUnionType(inference.candidates, 2 /* Subtype */) :
61388                 inference.contraCandidates ? getIntersectionType(inference.contraCandidates) :
61389                     undefined;
61390         }
61391         function hasSkipDirectInferenceFlag(node) {
61392             return !!getNodeLinks(node).skipDirectInference;
61393         }
61394         function isFromInferenceBlockedSource(type) {
61395             return !!(type.symbol && ts.some(type.symbol.declarations, hasSkipDirectInferenceFlag));
61396         }
61397         function isValidBigIntString(s) {
61398             var scanner = ts.createScanner(99 /* ESNext */, /*skipTrivia*/ false);
61399             var success = true;
61400             scanner.setOnError(function () { return success = false; });
61401             scanner.setText(s + "n");
61402             var result = scanner.scan();
61403             if (result === 40 /* MinusToken */) {
61404                 result = scanner.scan();
61405             }
61406             var flags = scanner.getTokenFlags();
61407             // validate that
61408             // * scanning proceeded without error
61409             // * a bigint can be scanned, and that when it is scanned, it is
61410             // * the full length of the input string (so the scanner is one character beyond the augmented input length)
61411             // * it does not contain a numeric seperator (the `BigInt` constructor does not accept a numeric seperator in its input)
61412             return success && result === 9 /* BigIntLiteral */ && scanner.getTextPos() === (s.length + 1) && !(flags & 512 /* ContainsSeparator */);
61413         }
61414         function isStringLiteralTypeValueParsableAsType(s, target) {
61415             if (target.flags & 1048576 /* Union */) {
61416                 return !!forEachType(target, function (t) { return isStringLiteralTypeValueParsableAsType(s, t); });
61417             }
61418             switch (target) {
61419                 case stringType: return true;
61420                 case numberType: return s.value !== "" && isFinite(+(s.value));
61421                 case bigintType: return s.value !== "" && isValidBigIntString(s.value);
61422                 // the next 4 should be handled in `getTemplateLiteralType`, as they are all exactly one value, but are here for completeness, just in case
61423                 // this function is ever used on types which don't come from template literal holes
61424                 case trueType: return s.value === "true";
61425                 case falseType: return s.value === "false";
61426                 case undefinedType: return s.value === "undefined";
61427                 case nullType: return s.value === "null";
61428                 default: return !!(target.flags & 1 /* Any */);
61429             }
61430         }
61431         function inferLiteralsFromTemplateLiteralType(source, target) {
61432             var value = source.value;
61433             var texts = target.texts;
61434             var lastIndex = texts.length - 1;
61435             var startText = texts[0];
61436             var endText = texts[lastIndex];
61437             if (!(value.startsWith(startText) && value.slice(startText.length).endsWith(endText)))
61438                 return undefined;
61439             var matches = [];
61440             var str = value.slice(startText.length, value.length - endText.length);
61441             var pos = 0;
61442             for (var i = 1; i < lastIndex; i++) {
61443                 var delim = texts[i];
61444                 var delimPos = delim.length > 0 ? str.indexOf(delim, pos) : pos < str.length ? pos + 1 : -1;
61445                 if (delimPos < 0)
61446                     return undefined;
61447                 matches.push(getLiteralType(str.slice(pos, delimPos)));
61448                 pos = delimPos + delim.length;
61449             }
61450             matches.push(getLiteralType(str.slice(pos)));
61451             return matches;
61452         }
61453         function inferTypes(inferences, originalSource, originalTarget, priority, contravariant) {
61454             if (priority === void 0) { priority = 0; }
61455             if (contravariant === void 0) { contravariant = false; }
61456             var bivariant = false;
61457             var propagationType;
61458             var inferencePriority = 1024 /* MaxValue */;
61459             var allowComplexConstraintInference = true;
61460             var visited;
61461             var sourceStack;
61462             var targetStack;
61463             var expandingFlags = 0 /* None */;
61464             inferFromTypes(originalSource, originalTarget);
61465             function inferFromTypes(source, target) {
61466                 if (!couldContainTypeVariables(target)) {
61467                     return;
61468                 }
61469                 if (source === wildcardType) {
61470                     // We are inferring from an 'any' type. We want to infer this type for every type parameter
61471                     // referenced in the target type, so we record it as the propagation type and infer from the
61472                     // target to itself. Then, as we find candidates we substitute the propagation type.
61473                     var savePropagationType = propagationType;
61474                     propagationType = source;
61475                     inferFromTypes(target, target);
61476                     propagationType = savePropagationType;
61477                     return;
61478                 }
61479                 if (source.aliasSymbol && source.aliasTypeArguments && source.aliasSymbol === target.aliasSymbol) {
61480                     // Source and target are types originating in the same generic type alias declaration.
61481                     // Simply infer from source type arguments to target type arguments.
61482                     inferFromTypeArguments(source.aliasTypeArguments, target.aliasTypeArguments, getAliasVariances(source.aliasSymbol));
61483                     return;
61484                 }
61485                 if (source === target && source.flags & 3145728 /* UnionOrIntersection */) {
61486                     // When source and target are the same union or intersection type, just relate each constituent
61487                     // type to itself.
61488                     for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
61489                         var t = _a[_i];
61490                         inferFromTypes(t, t);
61491                     }
61492                     return;
61493                 }
61494                 if (target.flags & 1048576 /* Union */) {
61495                     // First, infer between identically matching source and target constituents and remove the
61496                     // matching types.
61497                     var _b = inferFromMatchingTypes(source.flags & 1048576 /* Union */ ? source.types : [source], target.types, isTypeOrBaseIdenticalTo), tempSources = _b[0], tempTargets = _b[1];
61498                     // Next, infer between closely matching source and target constituents and remove
61499                     // the matching types. Types closely match when they are instantiations of the same
61500                     // object type or instantiations of the same type alias.
61501                     var _c = inferFromMatchingTypes(tempSources, tempTargets, isTypeCloselyMatchedBy), sources = _c[0], targets = _c[1];
61502                     if (targets.length === 0) {
61503                         return;
61504                     }
61505                     target = getUnionType(targets);
61506                     if (sources.length === 0) {
61507                         // All source constituents have been matched and there is nothing further to infer from.
61508                         // However, simply making no inferences is undesirable because it could ultimately mean
61509                         // inferring a type parameter constraint. Instead, make a lower priority inference from
61510                         // the full source to whatever remains in the target. For example, when inferring from
61511                         // string to 'string | T', make a lower priority inference of string for T.
61512                         inferWithPriority(source, target, 1 /* NakedTypeVariable */);
61513                         return;
61514                     }
61515                     source = getUnionType(sources);
61516                 }
61517                 else if (target.flags & 2097152 /* Intersection */ && ts.some(target.types, function (t) { return !!getInferenceInfoForType(t) || (isGenericMappedType(t) && !!getInferenceInfoForType(getHomomorphicTypeVariable(t) || neverType)); })) {
61518                     // We reduce intersection types only when they contain naked type parameters. For example, when
61519                     // inferring from 'string[] & { extra: any }' to 'string[] & T' we want to remove string[] and
61520                     // infer { extra: any } for T. But when inferring to 'string[] & Iterable<T>' we want to keep the
61521                     // string[] on the source side and infer string for T.
61522                     // Likewise, we consider a homomorphic mapped type constrainted to the target type parameter as similar to a "naked type variable"
61523                     // in such scenarios.
61524                     if (!(source.flags & 1048576 /* Union */)) {
61525                         // Infer between identically matching source and target constituents and remove the matching types.
61526                         var _d = inferFromMatchingTypes(source.flags & 2097152 /* Intersection */ ? source.types : [source], target.types, isTypeIdenticalTo), sources = _d[0], targets = _d[1];
61527                         if (sources.length === 0 || targets.length === 0) {
61528                             return;
61529                         }
61530                         source = getIntersectionType(sources);
61531                         target = getIntersectionType(targets);
61532                     }
61533                 }
61534                 else if (target.flags & (8388608 /* IndexedAccess */ | 33554432 /* Substitution */)) {
61535                     target = getActualTypeVariable(target);
61536                 }
61537                 if (target.flags & 8650752 /* TypeVariable */) {
61538                     // If target is a type parameter, make an inference, unless the source type contains
61539                     // the anyFunctionType (the wildcard type that's used to avoid contextually typing functions).
61540                     // Because the anyFunctionType is internal, it should not be exposed to the user by adding
61541                     // it as an inference candidate. Hopefully, a better candidate will come along that does
61542                     // not contain anyFunctionType when we come back to this argument for its second round
61543                     // of inference. Also, we exclude inferences for silentNeverType (which is used as a wildcard
61544                     // when constructing types from type parameters that had no inference candidates).
61545                     if (ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ || source === nonInferrableAnyType || source === silentNeverType ||
61546                         (priority & 64 /* ReturnType */ && (source === autoType || source === autoArrayType)) || isFromInferenceBlockedSource(source)) {
61547                         return;
61548                     }
61549                     var inference = getInferenceInfoForType(target);
61550                     if (inference) {
61551                         if (!inference.isFixed) {
61552                             if (inference.priority === undefined || priority < inference.priority) {
61553                                 inference.candidates = undefined;
61554                                 inference.contraCandidates = undefined;
61555                                 inference.topLevel = true;
61556                                 inference.priority = priority;
61557                             }
61558                             if (priority === inference.priority) {
61559                                 var candidate = propagationType || source;
61560                                 // We make contravariant inferences only if we are in a pure contravariant position,
61561                                 // i.e. only if we have not descended into a bivariant position.
61562                                 if (contravariant && !bivariant) {
61563                                     if (!ts.contains(inference.contraCandidates, candidate)) {
61564                                         inference.contraCandidates = ts.append(inference.contraCandidates, candidate);
61565                                         clearCachedInferences(inferences);
61566                                     }
61567                                 }
61568                                 else if (!ts.contains(inference.candidates, candidate)) {
61569                                     inference.candidates = ts.append(inference.candidates, candidate);
61570                                     clearCachedInferences(inferences);
61571                                 }
61572                             }
61573                             if (!(priority & 64 /* ReturnType */) && target.flags & 262144 /* TypeParameter */ && inference.topLevel && !isTypeParameterAtTopLevel(originalTarget, target)) {
61574                                 inference.topLevel = false;
61575                                 clearCachedInferences(inferences);
61576                             }
61577                         }
61578                         inferencePriority = Math.min(inferencePriority, priority);
61579                         return;
61580                     }
61581                     else {
61582                         // Infer to the simplified version of an indexed access, if possible, to (hopefully) expose more bare type parameters to the inference engine
61583                         var simplified = getSimplifiedType(target, /*writing*/ false);
61584                         if (simplified !== target) {
61585                             invokeOnce(source, simplified, inferFromTypes);
61586                         }
61587                         else if (target.flags & 8388608 /* IndexedAccess */) {
61588                             var indexType = getSimplifiedType(target.indexType, /*writing*/ false);
61589                             // Generally simplifications of instantiable indexes are avoided to keep relationship checking correct, however if our target is an access, we can consider
61590                             // that key of that access to be "instantiated", since we're looking to find the infernce goal in any way we can.
61591                             if (indexType.flags & 465829888 /* Instantiable */) {
61592                                 var simplified_1 = distributeIndexOverObjectType(getSimplifiedType(target.objectType, /*writing*/ false), indexType, /*writing*/ false);
61593                                 if (simplified_1 && simplified_1 !== target) {
61594                                     invokeOnce(source, simplified_1, inferFromTypes);
61595                                 }
61596                             }
61597                         }
61598                     }
61599                 }
61600                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target)) &&
61601                     !(source.node && target.node)) {
61602                     // If source and target are references to the same generic type, infer from type arguments
61603                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
61604                 }
61605                 else if (source.flags & 4194304 /* Index */ && target.flags & 4194304 /* Index */) {
61606                     contravariant = !contravariant;
61607                     inferFromTypes(source.type, target.type);
61608                     contravariant = !contravariant;
61609                 }
61610                 else if ((isLiteralType(source) || source.flags & 4 /* String */) && target.flags & 4194304 /* Index */) {
61611                     var empty = createEmptyObjectTypeFromStringLiteral(source);
61612                     contravariant = !contravariant;
61613                     inferWithPriority(empty, target.type, 128 /* LiteralKeyof */);
61614                     contravariant = !contravariant;
61615                 }
61616                 else if (source.flags & 8388608 /* IndexedAccess */ && target.flags & 8388608 /* IndexedAccess */) {
61617                     inferFromTypes(source.objectType, target.objectType);
61618                     inferFromTypes(source.indexType, target.indexType);
61619                 }
61620                 else if (source.flags & 268435456 /* StringMapping */ && target.flags & 268435456 /* StringMapping */) {
61621                     if (source.symbol === target.symbol) {
61622                         inferFromTypes(source.type, target.type);
61623                     }
61624                 }
61625                 else if (target.flags & 16777216 /* Conditional */) {
61626                     invokeOnce(source, target, inferToConditionalType);
61627                 }
61628                 else if (target.flags & 3145728 /* UnionOrIntersection */) {
61629                     inferToMultipleTypes(source, target.types, target.flags);
61630                 }
61631                 else if (source.flags & 1048576 /* Union */) {
61632                     // Source is a union or intersection type, infer from each constituent type
61633                     var sourceTypes = source.types;
61634                     for (var _e = 0, sourceTypes_2 = sourceTypes; _e < sourceTypes_2.length; _e++) {
61635                         var sourceType = sourceTypes_2[_e];
61636                         inferFromTypes(sourceType, target);
61637                     }
61638                 }
61639                 else if (target.flags & 134217728 /* TemplateLiteral */) {
61640                     inferToTemplateLiteralType(source, target);
61641                 }
61642                 else {
61643                     source = getReducedType(source);
61644                     if (!(priority & 256 /* NoConstraints */ && source.flags & (2097152 /* Intersection */ | 465829888 /* Instantiable */))) {
61645                         var apparentSource = getApparentType(source);
61646                         // getApparentType can return _any_ type, since an indexed access or conditional may simplify to any other type.
61647                         // If that occurs and it doesn't simplify to an object or intersection, we'll need to restart `inferFromTypes`
61648                         // with the simplified source.
61649                         if (apparentSource !== source && allowComplexConstraintInference && !(apparentSource.flags & (524288 /* Object */ | 2097152 /* Intersection */))) {
61650                             // TODO: The `allowComplexConstraintInference` flag is a hack! This forbids inference from complex constraints within constraints!
61651                             // This isn't required algorithmically, but rather is used to lower the memory burden caused by performing inference
61652                             // that is _too good_ in projects with complicated constraints (eg, fp-ts). In such cases, if we did not limit ourselves
61653                             // here, we might produce more valid inferences for types, causing us to do more checks and perform more instantiations
61654                             // (in addition to the extra stack depth here) which, in turn, can push the already close process over its limit.
61655                             // TL;DR: If we ever become generally more memory efficient (or our resource budget ever increases), we should just
61656                             // remove this `allowComplexConstraintInference` flag.
61657                             allowComplexConstraintInference = false;
61658                             return inferFromTypes(apparentSource, target);
61659                         }
61660                         source = apparentSource;
61661                     }
61662                     if (source.flags & (524288 /* Object */ | 2097152 /* Intersection */)) {
61663                         invokeOnce(source, target, inferFromObjectTypes);
61664                     }
61665                 }
61666                 if (source.flags & 25165824 /* Simplifiable */) {
61667                     var simplified = getSimplifiedType(source, contravariant);
61668                     if (simplified !== source) {
61669                         inferFromTypes(simplified, target);
61670                     }
61671                 }
61672             }
61673             function inferWithPriority(source, target, newPriority) {
61674                 var savePriority = priority;
61675                 priority |= newPriority;
61676                 inferFromTypes(source, target);
61677                 priority = savePriority;
61678             }
61679             function invokeOnce(source, target, action) {
61680                 var key = source.id + "," + target.id;
61681                 var status = visited && visited.get(key);
61682                 if (status !== undefined) {
61683                     inferencePriority = Math.min(inferencePriority, status);
61684                     return;
61685                 }
61686                 (visited || (visited = new ts.Map())).set(key, -1 /* Circularity */);
61687                 var saveInferencePriority = inferencePriority;
61688                 inferencePriority = 1024 /* MaxValue */;
61689                 // We stop inferring and report a circularity if we encounter duplicate recursion identities on both
61690                 // the source side and the target side.
61691                 var saveExpandingFlags = expandingFlags;
61692                 var sourceIdentity = getRecursionIdentity(source) || source;
61693                 var targetIdentity = getRecursionIdentity(target) || target;
61694                 if (sourceIdentity && ts.contains(sourceStack, sourceIdentity))
61695                     expandingFlags |= 1 /* Source */;
61696                 if (targetIdentity && ts.contains(targetStack, targetIdentity))
61697                     expandingFlags |= 2 /* Target */;
61698                 if (expandingFlags !== 3 /* Both */) {
61699                     if (sourceIdentity)
61700                         (sourceStack || (sourceStack = [])).push(sourceIdentity);
61701                     if (targetIdentity)
61702                         (targetStack || (targetStack = [])).push(targetIdentity);
61703                     action(source, target);
61704                     if (targetIdentity)
61705                         targetStack.pop();
61706                     if (sourceIdentity)
61707                         sourceStack.pop();
61708                 }
61709                 else {
61710                     inferencePriority = -1 /* Circularity */;
61711                 }
61712                 expandingFlags = saveExpandingFlags;
61713                 visited.set(key, inferencePriority);
61714                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
61715             }
61716             function inferFromMatchingTypes(sources, targets, matches) {
61717                 var matchedSources;
61718                 var matchedTargets;
61719                 for (var _i = 0, targets_1 = targets; _i < targets_1.length; _i++) {
61720                     var t = targets_1[_i];
61721                     for (var _a = 0, sources_1 = sources; _a < sources_1.length; _a++) {
61722                         var s = sources_1[_a];
61723                         if (matches(s, t)) {
61724                             inferFromTypes(s, t);
61725                             matchedSources = ts.appendIfUnique(matchedSources, s);
61726                             matchedTargets = ts.appendIfUnique(matchedTargets, t);
61727                         }
61728                     }
61729                 }
61730                 return [
61731                     matchedSources ? ts.filter(sources, function (t) { return !ts.contains(matchedSources, t); }) : sources,
61732                     matchedTargets ? ts.filter(targets, function (t) { return !ts.contains(matchedTargets, t); }) : targets,
61733                 ];
61734             }
61735             function inferFromTypeArguments(sourceTypes, targetTypes, variances) {
61736                 var count = sourceTypes.length < targetTypes.length ? sourceTypes.length : targetTypes.length;
61737                 for (var i = 0; i < count; i++) {
61738                     if (i < variances.length && (variances[i] & 7 /* VarianceMask */) === 2 /* Contravariant */) {
61739                         inferFromContravariantTypes(sourceTypes[i], targetTypes[i]);
61740                     }
61741                     else {
61742                         inferFromTypes(sourceTypes[i], targetTypes[i]);
61743                     }
61744                 }
61745             }
61746             function inferFromContravariantTypes(source, target) {
61747                 if (strictFunctionTypes || priority & 512 /* AlwaysStrict */) {
61748                     contravariant = !contravariant;
61749                     inferFromTypes(source, target);
61750                     contravariant = !contravariant;
61751                 }
61752                 else {
61753                     inferFromTypes(source, target);
61754                 }
61755             }
61756             function getInferenceInfoForType(type) {
61757                 if (type.flags & 8650752 /* TypeVariable */) {
61758                     for (var _i = 0, inferences_2 = inferences; _i < inferences_2.length; _i++) {
61759                         var inference = inferences_2[_i];
61760                         if (type === inference.typeParameter) {
61761                             return inference;
61762                         }
61763                     }
61764                 }
61765                 return undefined;
61766             }
61767             function getSingleTypeVariableFromIntersectionTypes(types) {
61768                 var typeVariable;
61769                 for (var _i = 0, types_15 = types; _i < types_15.length; _i++) {
61770                     var type = types_15[_i];
61771                     var t = type.flags & 2097152 /* Intersection */ && ts.find(type.types, function (t) { return !!getInferenceInfoForType(t); });
61772                     if (!t || typeVariable && t !== typeVariable) {
61773                         return undefined;
61774                     }
61775                     typeVariable = t;
61776                 }
61777                 return typeVariable;
61778             }
61779             function inferToMultipleTypes(source, targets, targetFlags) {
61780                 var typeVariableCount = 0;
61781                 if (targetFlags & 1048576 /* Union */) {
61782                     var nakedTypeVariable = void 0;
61783                     var sources = source.flags & 1048576 /* Union */ ? source.types : [source];
61784                     var matched_1 = new Array(sources.length);
61785                     var inferenceCircularity = false;
61786                     // First infer to types that are not naked type variables. For each source type we
61787                     // track whether inferences were made from that particular type to some target with
61788                     // equal priority (i.e. of equal quality) to what we would infer for a naked type
61789                     // parameter.
61790                     for (var _i = 0, targets_2 = targets; _i < targets_2.length; _i++) {
61791                         var t = targets_2[_i];
61792                         if (getInferenceInfoForType(t)) {
61793                             nakedTypeVariable = t;
61794                             typeVariableCount++;
61795                         }
61796                         else {
61797                             for (var i = 0; i < sources.length; i++) {
61798                                 var saveInferencePriority = inferencePriority;
61799                                 inferencePriority = 1024 /* MaxValue */;
61800                                 inferFromTypes(sources[i], t);
61801                                 if (inferencePriority === priority)
61802                                     matched_1[i] = true;
61803                                 inferenceCircularity = inferenceCircularity || inferencePriority === -1 /* Circularity */;
61804                                 inferencePriority = Math.min(inferencePriority, saveInferencePriority);
61805                             }
61806                         }
61807                     }
61808                     if (typeVariableCount === 0) {
61809                         // If every target is an intersection of types containing a single naked type variable,
61810                         // make a lower priority inference to that type variable. This handles inferring from
61811                         // 'A | B' to 'T & (X | Y)' where we want to infer 'A | B' for T.
61812                         var intersectionTypeVariable = getSingleTypeVariableFromIntersectionTypes(targets);
61813                         if (intersectionTypeVariable) {
61814                             inferWithPriority(source, intersectionTypeVariable, 1 /* NakedTypeVariable */);
61815                         }
61816                         return;
61817                     }
61818                     // If the target has a single naked type variable and no inference circularities were
61819                     // encountered above (meaning we explored the types fully), create a union of the source
61820                     // types from which no inferences have been made so far and infer from that union to the
61821                     // naked type variable.
61822                     if (typeVariableCount === 1 && !inferenceCircularity) {
61823                         var unmatched = ts.flatMap(sources, function (s, i) { return matched_1[i] ? undefined : s; });
61824                         if (unmatched.length) {
61825                             inferFromTypes(getUnionType(unmatched), nakedTypeVariable);
61826                             return;
61827                         }
61828                     }
61829                 }
61830                 else {
61831                     // We infer from types that are not naked type variables first so that inferences we
61832                     // make from nested naked type variables and given slightly higher priority by virtue
61833                     // of being first in the candidates array.
61834                     for (var _a = 0, targets_3 = targets; _a < targets_3.length; _a++) {
61835                         var t = targets_3[_a];
61836                         if (getInferenceInfoForType(t)) {
61837                             typeVariableCount++;
61838                         }
61839                         else {
61840                             inferFromTypes(source, t);
61841                         }
61842                     }
61843                 }
61844                 // Inferences directly to naked type variables are given lower priority as they are
61845                 // less specific. For example, when inferring from Promise<string> to T | Promise<T>,
61846                 // we want to infer string for T, not Promise<string> | string. For intersection types
61847                 // we only infer to single naked type variables.
61848                 if (targetFlags & 2097152 /* Intersection */ ? typeVariableCount === 1 : typeVariableCount > 0) {
61849                     for (var _b = 0, targets_4 = targets; _b < targets_4.length; _b++) {
61850                         var t = targets_4[_b];
61851                         if (getInferenceInfoForType(t)) {
61852                             inferWithPriority(source, t, 1 /* NakedTypeVariable */);
61853                         }
61854                     }
61855                 }
61856             }
61857             function inferToMappedType(source, target, constraintType) {
61858                 if (constraintType.flags & 1048576 /* Union */) {
61859                     var result = false;
61860                     for (var _i = 0, _a = constraintType.types; _i < _a.length; _i++) {
61861                         var type = _a[_i];
61862                         result = inferToMappedType(source, target, type) || result;
61863                     }
61864                     return result;
61865                 }
61866                 if (constraintType.flags & 4194304 /* Index */) {
61867                     // We're inferring from some source type S to a homomorphic mapped type { [P in keyof T]: X },
61868                     // where T is a type variable. Use inferTypeForHomomorphicMappedType to infer a suitable source
61869                     // type and then make a secondary inference from that type to T. We make a secondary inference
61870                     // such that direct inferences to T get priority over inferences to Partial<T>, for example.
61871                     var inference = getInferenceInfoForType(constraintType.type);
61872                     if (inference && !inference.isFixed && !isFromInferenceBlockedSource(source)) {
61873                         var inferredType = inferTypeForHomomorphicMappedType(source, target, constraintType);
61874                         if (inferredType) {
61875                             // We assign a lower priority to inferences made from types containing non-inferrable
61876                             // types because we may only have a partial result (i.e. we may have failed to make
61877                             // reverse inferences for some properties).
61878                             inferWithPriority(inferredType, inference.typeParameter, ts.getObjectFlags(source) & 2097152 /* NonInferrableType */ ?
61879                                 8 /* PartialHomomorphicMappedType */ :
61880                                 4 /* HomomorphicMappedType */);
61881                         }
61882                     }
61883                     return true;
61884                 }
61885                 if (constraintType.flags & 262144 /* TypeParameter */) {
61886                     // We're inferring from some source type S to a mapped type { [P in K]: X }, where K is a type
61887                     // parameter. First infer from 'keyof S' to K.
61888                     inferWithPriority(getIndexType(source), constraintType, 16 /* MappedTypeConstraint */);
61889                     // If K is constrained to a type C, also infer to C. Thus, for a mapped type { [P in K]: X },
61890                     // where K extends keyof T, we make the same inferences as for a homomorphic mapped type
61891                     // { [P in keyof T]: X }. This enables us to make meaningful inferences when the target is a
61892                     // Pick<T, K>.
61893                     var extendedConstraint = getConstraintOfType(constraintType);
61894                     if (extendedConstraint && inferToMappedType(source, target, extendedConstraint)) {
61895                         return true;
61896                     }
61897                     // If no inferences can be made to K's constraint, infer from a union of the property types
61898                     // in the source to the template type X.
61899                     var propTypes = ts.map(getPropertiesOfType(source), getTypeOfSymbol);
61900                     var stringIndexType = getIndexTypeOfType(source, 0 /* String */);
61901                     var numberIndexInfo = getNonEnumNumberIndexInfo(source);
61902                     var numberIndexType = numberIndexInfo && numberIndexInfo.type;
61903                     inferFromTypes(getUnionType(ts.append(ts.append(propTypes, stringIndexType), numberIndexType)), getTemplateTypeFromMappedType(target));
61904                     return true;
61905                 }
61906                 return false;
61907             }
61908             function inferToConditionalType(source, target) {
61909                 if (source.flags & 16777216 /* Conditional */) {
61910                     inferFromTypes(source.checkType, target.checkType);
61911                     inferFromTypes(source.extendsType, target.extendsType);
61912                     inferFromTypes(getTrueTypeFromConditionalType(source), getTrueTypeFromConditionalType(target));
61913                     inferFromTypes(getFalseTypeFromConditionalType(source), getFalseTypeFromConditionalType(target));
61914                 }
61915                 else {
61916                     var savePriority = priority;
61917                     priority |= contravariant ? 32 /* ContravariantConditional */ : 0;
61918                     var targetTypes = [getTrueTypeFromConditionalType(target), getFalseTypeFromConditionalType(target)];
61919                     inferToMultipleTypes(source, targetTypes, target.flags);
61920                     priority = savePriority;
61921                 }
61922             }
61923             function inferToTemplateLiteralType(source, target) {
61924                 var matches = source.flags & 128 /* StringLiteral */ ? inferLiteralsFromTemplateLiteralType(source, target) :
61925                     source.flags & 134217728 /* TemplateLiteral */ && ts.arraysEqual(source.texts, target.texts) ? source.types :
61926                         undefined;
61927                 var types = target.types;
61928                 for (var i = 0; i < types.length; i++) {
61929                     inferFromTypes(matches ? matches[i] : neverType, types[i]);
61930                 }
61931             }
61932             function inferFromObjectTypes(source, target) {
61933                 if (ts.getObjectFlags(source) & 4 /* Reference */ && ts.getObjectFlags(target) & 4 /* Reference */ && (source.target === target.target || isArrayType(source) && isArrayType(target))) {
61934                     // If source and target are references to the same generic type, infer from type arguments
61935                     inferFromTypeArguments(getTypeArguments(source), getTypeArguments(target), getVariances(source.target));
61936                     return;
61937                 }
61938                 if (isGenericMappedType(source) && isGenericMappedType(target)) {
61939                     // The source and target types are generic types { [P in S]: X } and { [P in T]: Y }, so we infer
61940                     // from S to T and from X to Y.
61941                     inferFromTypes(getConstraintTypeFromMappedType(source), getConstraintTypeFromMappedType(target));
61942                     inferFromTypes(getTemplateTypeFromMappedType(source), getTemplateTypeFromMappedType(target));
61943                     var sourceNameType = getNameTypeFromMappedType(source);
61944                     var targetNameType = getNameTypeFromMappedType(target);
61945                     if (sourceNameType && targetNameType)
61946                         inferFromTypes(sourceNameType, targetNameType);
61947                 }
61948                 if (ts.getObjectFlags(target) & 32 /* Mapped */ && !target.declaration.nameType) {
61949                     var constraintType = getConstraintTypeFromMappedType(target);
61950                     if (inferToMappedType(source, target, constraintType)) {
61951                         return;
61952                     }
61953                 }
61954                 // Infer from the members of source and target only if the two types are possibly related
61955                 if (!typesDefinitelyUnrelated(source, target)) {
61956                     if (isArrayType(source) || isTupleType(source)) {
61957                         if (isTupleType(target)) {
61958                             var sourceArity = getTypeReferenceArity(source);
61959                             var targetArity = getTypeReferenceArity(target);
61960                             var elementTypes = getTypeArguments(target);
61961                             var elementFlags = target.target.elementFlags;
61962                             // When source and target are tuple types with the same structure (fixed, variadic, and rest are matched
61963                             // to the same kind in each position), simply infer between the element types.
61964                             if (isTupleType(source) && isTupleTypeStructureMatching(source, target)) {
61965                                 for (var i = 0; i < targetArity; i++) {
61966                                     inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
61967                                 }
61968                                 return;
61969                             }
61970                             var startLength = isTupleType(source) ? Math.min(source.target.fixedLength, target.target.fixedLength) : 0;
61971                             var sourceRestType = !isTupleType(source) || sourceArity > 0 && source.target.elementFlags[sourceArity - 1] & 4 /* Rest */ ?
61972                                 getTypeArguments(source)[sourceArity - 1] : undefined;
61973                             var endLength = !(target.target.combinedFlags & 12 /* Variable */) ? 0 :
61974                                 sourceRestType ? getEndLengthOfType(target) :
61975                                     Math.min(getEndLengthOfType(source), getEndLengthOfType(target));
61976                             var sourceEndLength = sourceRestType ? 0 : endLength;
61977                             // Infer between starting fixed elements.
61978                             for (var i = 0; i < startLength; i++) {
61979                                 inferFromTypes(getTypeArguments(source)[i], elementTypes[i]);
61980                             }
61981                             if (sourceRestType && sourceArity - startLength === 1) {
61982                                 // Single rest element remains in source, infer from that to every element in target
61983                                 for (var i = startLength; i < targetArity - endLength; i++) {
61984                                     inferFromTypes(elementFlags[i] & 8 /* Variadic */ ? createArrayType(sourceRestType) : sourceRestType, elementTypes[i]);
61985                                 }
61986                             }
61987                             else {
61988                                 var middleLength = targetArity - startLength - endLength;
61989                                 if (middleLength === 2 && elementFlags[startLength] & elementFlags[startLength + 1] & 8 /* Variadic */ && isTupleType(source)) {
61990                                     // Middle of target is [...T, ...U] and source is tuple type
61991                                     var targetInfo = getInferenceInfoForType(elementTypes[startLength]);
61992                                     if (targetInfo && targetInfo.impliedArity !== undefined) {
61993                                         // Infer slices from source based on implied arity of T.
61994                                         inferFromTypes(sliceTupleType(source, startLength, sourceEndLength + sourceArity - targetInfo.impliedArity), elementTypes[startLength]);
61995                                         inferFromTypes(sliceTupleType(source, startLength + targetInfo.impliedArity, sourceEndLength), elementTypes[startLength + 1]);
61996                                     }
61997                                 }
61998                                 else if (middleLength === 1 && elementFlags[startLength] & 8 /* Variadic */) {
61999                                     // Middle of target is exactly one variadic element. Infer the slice between the fixed parts in the source.
62000                                     // If target ends in optional element(s), make a lower priority a speculative inference.
62001                                     var endsInOptional = target.target.elementFlags[targetArity - 1] & 2 /* Optional */;
62002                                     var sourceSlice = isTupleType(source) ? sliceTupleType(source, startLength, sourceEndLength) : createArrayType(sourceRestType);
62003                                     inferWithPriority(sourceSlice, elementTypes[startLength], endsInOptional ? 2 /* SpeculativeTuple */ : 0);
62004                                 }
62005                                 else if (middleLength === 1 && elementFlags[startLength] & 4 /* Rest */) {
62006                                     // Middle of target is exactly one rest element. If middle of source is not empty, infer union of middle element types.
62007                                     var restType = isTupleType(source) ? getElementTypeOfSliceOfTupleType(source, startLength, sourceEndLength) : sourceRestType;
62008                                     if (restType) {
62009                                         inferFromTypes(restType, elementTypes[startLength]);
62010                                     }
62011                                 }
62012                             }
62013                             // Infer between ending fixed elements
62014                             for (var i = 0; i < endLength; i++) {
62015                                 inferFromTypes(sourceRestType || getTypeArguments(source)[sourceArity - i - 1], elementTypes[targetArity - i - 1]);
62016                             }
62017                             return;
62018                         }
62019                         if (isArrayType(target)) {
62020                             inferFromIndexTypes(source, target);
62021                             return;
62022                         }
62023                     }
62024                     inferFromProperties(source, target);
62025                     inferFromSignatures(source, target, 0 /* Call */);
62026                     inferFromSignatures(source, target, 1 /* Construct */);
62027                     inferFromIndexTypes(source, target);
62028                 }
62029             }
62030             function inferFromProperties(source, target) {
62031                 var properties = getPropertiesOfObjectType(target);
62032                 for (var _i = 0, properties_3 = properties; _i < properties_3.length; _i++) {
62033                     var targetProp = properties_3[_i];
62034                     var sourceProp = getPropertyOfType(source, targetProp.escapedName);
62035                     if (sourceProp) {
62036                         inferFromTypes(getTypeOfSymbol(sourceProp), getTypeOfSymbol(targetProp));
62037                     }
62038                 }
62039             }
62040             function inferFromSignatures(source, target, kind) {
62041                 var sourceSignatures = getSignaturesOfType(source, kind);
62042                 var targetSignatures = getSignaturesOfType(target, kind);
62043                 var sourceLen = sourceSignatures.length;
62044                 var targetLen = targetSignatures.length;
62045                 var len = sourceLen < targetLen ? sourceLen : targetLen;
62046                 var skipParameters = !!(ts.getObjectFlags(source) & 2097152 /* NonInferrableType */);
62047                 for (var i = 0; i < len; i++) {
62048                     inferFromSignature(getBaseSignature(sourceSignatures[sourceLen - len + i]), getErasedSignature(targetSignatures[targetLen - len + i]), skipParameters);
62049                 }
62050             }
62051             function inferFromSignature(source, target, skipParameters) {
62052                 if (!skipParameters) {
62053                     var saveBivariant = bivariant;
62054                     var kind = target.declaration ? target.declaration.kind : 0 /* Unknown */;
62055                     // Once we descend into a bivariant signature we remain bivariant for all nested inferences
62056                     bivariant = bivariant || kind === 165 /* MethodDeclaration */ || kind === 164 /* MethodSignature */ || kind === 166 /* Constructor */;
62057                     applyToParameterTypes(source, target, inferFromContravariantTypes);
62058                     bivariant = saveBivariant;
62059                 }
62060                 applyToReturnTypes(source, target, inferFromTypes);
62061             }
62062             function inferFromIndexTypes(source, target) {
62063                 var targetStringIndexType = getIndexTypeOfType(target, 0 /* String */);
62064                 if (targetStringIndexType) {
62065                     var sourceIndexType = getIndexTypeOfType(source, 0 /* String */) ||
62066                         getImplicitIndexTypeOfType(source, 0 /* String */);
62067                     if (sourceIndexType) {
62068                         inferFromTypes(sourceIndexType, targetStringIndexType);
62069                     }
62070                 }
62071                 var targetNumberIndexType = getIndexTypeOfType(target, 1 /* Number */);
62072                 if (targetNumberIndexType) {
62073                     var sourceIndexType = getIndexTypeOfType(source, 1 /* Number */) ||
62074                         getIndexTypeOfType(source, 0 /* String */) ||
62075                         getImplicitIndexTypeOfType(source, 1 /* Number */);
62076                     if (sourceIndexType) {
62077                         inferFromTypes(sourceIndexType, targetNumberIndexType);
62078                     }
62079                 }
62080             }
62081         }
62082         function isTypeOrBaseIdenticalTo(s, t) {
62083             return isTypeIdenticalTo(s, t) || !!(t.flags & 4 /* String */ && s.flags & 128 /* StringLiteral */ || t.flags & 8 /* Number */ && s.flags & 256 /* NumberLiteral */);
62084         }
62085         function isTypeCloselyMatchedBy(s, t) {
62086             return !!(s.flags & 524288 /* Object */ && t.flags & 524288 /* Object */ && s.symbol && s.symbol === t.symbol ||
62087                 s.aliasSymbol && s.aliasTypeArguments && s.aliasSymbol === t.aliasSymbol);
62088         }
62089         function hasPrimitiveConstraint(type) {
62090             var constraint = getConstraintOfTypeParameter(type);
62091             return !!constraint && maybeTypeOfKind(constraint.flags & 16777216 /* Conditional */ ? getDefaultConstraintOfConditionalType(constraint) : constraint, 131068 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
62092         }
62093         function isObjectLiteralType(type) {
62094             return !!(ts.getObjectFlags(type) & 128 /* ObjectLiteral */);
62095         }
62096         function isObjectOrArrayLiteralType(type) {
62097             return !!(ts.getObjectFlags(type) & (128 /* ObjectLiteral */ | 65536 /* ArrayLiteral */));
62098         }
62099         function unionObjectAndArrayLiteralCandidates(candidates) {
62100             if (candidates.length > 1) {
62101                 var objectLiterals = ts.filter(candidates, isObjectOrArrayLiteralType);
62102                 if (objectLiterals.length) {
62103                     var literalsType = getUnionType(objectLiterals, 2 /* Subtype */);
62104                     return ts.concatenate(ts.filter(candidates, function (t) { return !isObjectOrArrayLiteralType(t); }), [literalsType]);
62105                 }
62106             }
62107             return candidates;
62108         }
62109         function getContravariantInference(inference) {
62110             return inference.priority & 208 /* PriorityImpliesCombination */ ? getIntersectionType(inference.contraCandidates) : getCommonSubtype(inference.contraCandidates);
62111         }
62112         function getCovariantInference(inference, signature) {
62113             // Extract all object and array literal types and replace them with a single widened and normalized type.
62114             var candidates = unionObjectAndArrayLiteralCandidates(inference.candidates);
62115             // We widen inferred literal types if
62116             // all inferences were made to top-level occurrences of the type parameter, and
62117             // the type parameter has no constraint or its constraint includes no primitive or literal types, and
62118             // the type parameter was fixed during inference or does not occur at top-level in the return type.
62119             var primitiveConstraint = hasPrimitiveConstraint(inference.typeParameter);
62120             var widenLiteralTypes = !primitiveConstraint && inference.topLevel &&
62121                 (inference.isFixed || !isTypeParameterAtTopLevel(getReturnTypeOfSignature(signature), inference.typeParameter));
62122             var baseCandidates = primitiveConstraint ? ts.sameMap(candidates, getRegularTypeOfLiteralType) :
62123                 widenLiteralTypes ? ts.sameMap(candidates, getWidenedLiteralType) :
62124                     candidates;
62125             // If all inferences were made from a position that implies a combined result, infer a union type.
62126             // Otherwise, infer a common supertype.
62127             var unwidenedType = inference.priority & 208 /* PriorityImpliesCombination */ ?
62128                 getUnionType(baseCandidates, 2 /* Subtype */) :
62129                 getCommonSupertype(baseCandidates);
62130             return getWidenedType(unwidenedType);
62131         }
62132         function getInferredType(context, index) {
62133             var inference = context.inferences[index];
62134             if (!inference.inferredType) {
62135                 var inferredType = void 0;
62136                 var signature = context.signature;
62137                 if (signature) {
62138                     var inferredCovariantType = inference.candidates ? getCovariantInference(inference, signature) : undefined;
62139                     if (inference.contraCandidates) {
62140                         var inferredContravariantType = getContravariantInference(inference);
62141                         // If we have both co- and contra-variant inferences, we prefer the contra-variant inference
62142                         // unless the co-variant inference is a subtype and not 'never'.
62143                         inferredType = inferredCovariantType && !(inferredCovariantType.flags & 131072 /* Never */) &&
62144                             isTypeSubtypeOf(inferredCovariantType, inferredContravariantType) ?
62145                             inferredCovariantType : inferredContravariantType;
62146                     }
62147                     else if (inferredCovariantType) {
62148                         inferredType = inferredCovariantType;
62149                     }
62150                     else if (context.flags & 1 /* NoDefault */) {
62151                         // We use silentNeverType as the wildcard that signals no inferences.
62152                         inferredType = silentNeverType;
62153                     }
62154                     else {
62155                         // Infer either the default or the empty object type when no inferences were
62156                         // made. It is important to remember that in this case, inference still
62157                         // succeeds, meaning there is no error for not having inference candidates. An
62158                         // inference error only occurs when there are *conflicting* candidates, i.e.
62159                         // candidates with no common supertype.
62160                         var defaultType = getDefaultFromTypeParameter(inference.typeParameter);
62161                         if (defaultType) {
62162                             // Instantiate the default type. Any forward reference to a type
62163                             // parameter should be instantiated to the empty object type.
62164                             inferredType = instantiateType(defaultType, mergeTypeMappers(createBackreferenceMapper(context, index), context.nonFixingMapper));
62165                         }
62166                     }
62167                 }
62168                 else {
62169                     inferredType = getTypeFromInference(inference);
62170                 }
62171                 inference.inferredType = inferredType || getDefaultTypeArgumentType(!!(context.flags & 2 /* AnyDefault */));
62172                 var constraint = getConstraintOfTypeParameter(inference.typeParameter);
62173                 if (constraint) {
62174                     var instantiatedConstraint = instantiateType(constraint, context.nonFixingMapper);
62175                     if (!inferredType || !context.compareTypes(inferredType, getTypeWithThisArgument(instantiatedConstraint, inferredType))) {
62176                         inference.inferredType = inferredType = instantiatedConstraint;
62177                     }
62178                 }
62179             }
62180             return inference.inferredType;
62181         }
62182         function getDefaultTypeArgumentType(isInJavaScriptFile) {
62183             return isInJavaScriptFile ? anyType : unknownType;
62184         }
62185         function getInferredTypes(context) {
62186             var result = [];
62187             for (var i = 0; i < context.inferences.length; i++) {
62188                 result.push(getInferredType(context, i));
62189             }
62190             return result;
62191         }
62192         // EXPRESSION TYPE CHECKING
62193         function getCannotFindNameDiagnosticForName(node) {
62194             switch (node.escapedText) {
62195                 case "document":
62196                 case "console":
62197                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_include_dom;
62198                 case "$":
62199                     return compilerOptions.types
62200                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery_and_then_add_jquery_to_the_types_field_in_your_tsconfig
62201                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_jQuery_Try_npm_i_save_dev_types_Slashjquery;
62202                 case "describe":
62203                 case "suite":
62204                 case "it":
62205                 case "test":
62206                     return compilerOptions.types
62207                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha_and_then_add_jest_or_mocha_to_the_types_field_in_your_tsconfig
62208                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_a_test_runner_Try_npm_i_save_dev_types_Slashjest_or_npm_i_save_dev_types_Slashmocha;
62209                 case "process":
62210                 case "require":
62211                 case "Buffer":
62212                 case "module":
62213                     return compilerOptions.types
62214                         ? ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode_and_then_add_node_to_the_types_field_in_your_tsconfig
62215                         : ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_install_type_definitions_for_node_Try_npm_i_save_dev_types_Slashnode;
62216                 case "Map":
62217                 case "Set":
62218                 case "Promise":
62219                 case "Symbol":
62220                 case "WeakMap":
62221                 case "WeakSet":
62222                 case "Iterator":
62223                 case "AsyncIterator":
62224                 case "SharedArrayBuffer":
62225                 case "Atomics":
62226                 case "AsyncIterable":
62227                 case "AsyncIterableIterator":
62228                 case "AsyncGenerator":
62229                 case "AsyncGeneratorFunction":
62230                 case "BigInt":
62231                 case "Reflect":
62232                 case "BigInt64Array":
62233                 case "BigUint64Array":
62234                     return ts.Diagnostics.Cannot_find_name_0_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_1_or_later;
62235                 default:
62236                     if (node.parent.kind === 289 /* ShorthandPropertyAssignment */) {
62237                         return ts.Diagnostics.No_value_exists_in_scope_for_the_shorthand_property_0_Either_declare_one_or_provide_an_initializer;
62238                     }
62239                     else {
62240                         return ts.Diagnostics.Cannot_find_name_0;
62241                     }
62242             }
62243         }
62244         function getResolvedSymbol(node) {
62245             var links = getNodeLinks(node);
62246             if (!links.resolvedSymbol) {
62247                 links.resolvedSymbol = !ts.nodeIsMissing(node) &&
62248                     resolveName(node, node.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */, getCannotFindNameDiagnosticForName(node), node, !ts.isWriteOnlyAccess(node), 
62249                     /*excludeGlobals*/ false, ts.Diagnostics.Cannot_find_name_0_Did_you_mean_1) || unknownSymbol;
62250             }
62251             return links.resolvedSymbol;
62252         }
62253         function isInTypeQuery(node) {
62254             // TypeScript 1.0 spec (April 2014): 3.6.3
62255             // A type query consists of the keyword typeof followed by an expression.
62256             // The expression is restricted to a single identifier or a sequence of identifiers separated by periods
62257             return !!ts.findAncestor(node, function (n) { return n.kind === 176 /* TypeQuery */ ? true : n.kind === 78 /* Identifier */ || n.kind === 157 /* QualifiedName */ ? false : "quit"; });
62258         }
62259         // Return the flow cache key for a "dotted name" (i.e. a sequence of identifiers
62260         // separated by dots). The key consists of the id of the symbol referenced by the
62261         // leftmost identifier followed by zero or more property names separated by dots.
62262         // The result is undefined if the reference isn't a dotted name. We prefix nodes
62263         // occurring in an apparent type position with '@' because the control flow type
62264         // of such nodes may be based on the apparent type instead of the declared type.
62265         function getFlowCacheKey(node, declaredType, initialType, flowContainer) {
62266             switch (node.kind) {
62267                 case 78 /* Identifier */:
62268                     var symbol = getResolvedSymbol(node);
62269                     return symbol !== unknownSymbol ? (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType) + "|" + (isConstraintPosition(node) ? "@" : "") + getSymbolId(symbol) : undefined;
62270                 case 107 /* ThisKeyword */:
62271                     return "0|" + (flowContainer ? getNodeId(flowContainer) : "-1") + "|" + getTypeId(declaredType) + "|" + getTypeId(initialType);
62272                 case 225 /* NonNullExpression */:
62273                 case 207 /* ParenthesizedExpression */:
62274                     return getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
62275                 case 201 /* PropertyAccessExpression */:
62276                 case 202 /* ElementAccessExpression */:
62277                     var propName = getAccessedPropertyName(node);
62278                     if (propName !== undefined) {
62279                         var key = getFlowCacheKey(node.expression, declaredType, initialType, flowContainer);
62280                         return key && key + "." + propName;
62281                     }
62282             }
62283             return undefined;
62284         }
62285         function isMatchingReference(source, target) {
62286             switch (target.kind) {
62287                 case 207 /* ParenthesizedExpression */:
62288                 case 225 /* NonNullExpression */:
62289                     return isMatchingReference(source, target.expression);
62290                 case 216 /* BinaryExpression */:
62291                     return (ts.isAssignmentExpression(target) && isMatchingReference(source, target.left)) ||
62292                         (ts.isBinaryExpression(target) && target.operatorToken.kind === 27 /* CommaToken */ && isMatchingReference(source, target.right));
62293             }
62294             switch (source.kind) {
62295                 case 78 /* Identifier */:
62296                 case 79 /* PrivateIdentifier */:
62297                     return target.kind === 78 /* Identifier */ && getResolvedSymbol(source) === getResolvedSymbol(target) ||
62298                         (target.kind === 249 /* VariableDeclaration */ || target.kind === 198 /* BindingElement */) &&
62299                             getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(source)) === getSymbolOfNode(target);
62300                 case 107 /* ThisKeyword */:
62301                     return target.kind === 107 /* ThisKeyword */;
62302                 case 105 /* SuperKeyword */:
62303                     return target.kind === 105 /* SuperKeyword */;
62304                 case 225 /* NonNullExpression */:
62305                 case 207 /* ParenthesizedExpression */:
62306                     return isMatchingReference(source.expression, target);
62307                 case 201 /* PropertyAccessExpression */:
62308                 case 202 /* ElementAccessExpression */:
62309                     return ts.isAccessExpression(target) &&
62310                         getAccessedPropertyName(source) === getAccessedPropertyName(target) &&
62311                         isMatchingReference(source.expression, target.expression);
62312             }
62313             return false;
62314         }
62315         // Given a source x, check if target matches x or is an && operation with an operand that matches x.
62316         function containsTruthyCheck(source, target) {
62317             return isMatchingReference(source, target) ||
62318                 (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 55 /* AmpersandAmpersandToken */ &&
62319                     (containsTruthyCheck(source, target.left) || containsTruthyCheck(source, target.right)));
62320         }
62321         function getAccessedPropertyName(access) {
62322             return access.kind === 201 /* PropertyAccessExpression */ ? access.name.escapedText :
62323                 ts.isStringOrNumericLiteralLike(access.argumentExpression) ? ts.escapeLeadingUnderscores(access.argumentExpression.text) :
62324                     undefined;
62325         }
62326         function containsMatchingReference(source, target) {
62327             while (ts.isAccessExpression(source)) {
62328                 source = source.expression;
62329                 if (isMatchingReference(source, target)) {
62330                     return true;
62331                 }
62332             }
62333             return false;
62334         }
62335         function optionalChainContainsReference(source, target) {
62336             while (ts.isOptionalChain(source)) {
62337                 source = source.expression;
62338                 if (isMatchingReference(source, target)) {
62339                     return true;
62340                 }
62341             }
62342             return false;
62343         }
62344         function isDiscriminantProperty(type, name) {
62345             if (type && type.flags & 1048576 /* Union */) {
62346                 var prop = getUnionOrIntersectionProperty(type, name);
62347                 if (prop && ts.getCheckFlags(prop) & 2 /* SyntheticProperty */) {
62348                     if (prop.isDiscriminantProperty === undefined) {
62349                         prop.isDiscriminantProperty =
62350                             (prop.checkFlags & 192 /* Discriminant */) === 192 /* Discriminant */ &&
62351                                 !maybeTypeOfKind(getTypeOfSymbol(prop), 465829888 /* Instantiable */);
62352                     }
62353                     return !!prop.isDiscriminantProperty;
62354                 }
62355             }
62356             return false;
62357         }
62358         function findDiscriminantProperties(sourceProperties, target) {
62359             var result;
62360             for (var _i = 0, sourceProperties_2 = sourceProperties; _i < sourceProperties_2.length; _i++) {
62361                 var sourceProperty = sourceProperties_2[_i];
62362                 if (isDiscriminantProperty(target, sourceProperty.escapedName)) {
62363                     if (result) {
62364                         result.push(sourceProperty);
62365                         continue;
62366                     }
62367                     result = [sourceProperty];
62368                 }
62369             }
62370             return result;
62371         }
62372         function isOrContainsMatchingReference(source, target) {
62373             return isMatchingReference(source, target) || containsMatchingReference(source, target);
62374         }
62375         function hasMatchingArgument(callExpression, reference) {
62376             if (callExpression.arguments) {
62377                 for (var _i = 0, _a = callExpression.arguments; _i < _a.length; _i++) {
62378                     var argument = _a[_i];
62379                     if (isOrContainsMatchingReference(reference, argument)) {
62380                         return true;
62381                     }
62382                 }
62383             }
62384             if (callExpression.expression.kind === 201 /* PropertyAccessExpression */ &&
62385                 isOrContainsMatchingReference(reference, callExpression.expression.expression)) {
62386                 return true;
62387             }
62388             return false;
62389         }
62390         function getFlowNodeId(flow) {
62391             if (!flow.id || flow.id < 0) {
62392                 flow.id = nextFlowId;
62393                 nextFlowId++;
62394             }
62395             return flow.id;
62396         }
62397         function typeMaybeAssignableTo(source, target) {
62398             if (!(source.flags & 1048576 /* Union */)) {
62399                 return isTypeAssignableTo(source, target);
62400             }
62401             for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
62402                 var t = _a[_i];
62403                 if (isTypeAssignableTo(t, target)) {
62404                     return true;
62405                 }
62406             }
62407             return false;
62408         }
62409         // Remove those constituent types of declaredType to which no constituent type of assignedType is assignable.
62410         // For example, when a variable of type number | string | boolean is assigned a value of type number | boolean,
62411         // we remove type string.
62412         function getAssignmentReducedType(declaredType, assignedType) {
62413             if (declaredType !== assignedType) {
62414                 if (assignedType.flags & 131072 /* Never */) {
62415                     return assignedType;
62416                 }
62417                 var reducedType = filterType(declaredType, function (t) { return typeMaybeAssignableTo(assignedType, t); });
62418                 if (assignedType.flags & 512 /* BooleanLiteral */ && isFreshLiteralType(assignedType)) {
62419                     reducedType = mapType(reducedType, getFreshTypeOfLiteralType); // Ensure that if the assignment is a fresh type, that we narrow to fresh types
62420                 }
62421                 // Our crude heuristic produces an invalid result in some cases: see GH#26130.
62422                 // For now, when that happens, we give up and don't narrow at all.  (This also
62423                 // means we'll never narrow for erroneous assignments where the assigned type
62424                 // is not assignable to the declared type.)
62425                 if (isTypeAssignableTo(assignedType, reducedType)) {
62426                     return reducedType;
62427                 }
62428             }
62429             return declaredType;
62430         }
62431         function getTypeFactsOfTypes(types) {
62432             var result = 0 /* None */;
62433             for (var _i = 0, types_16 = types; _i < types_16.length; _i++) {
62434                 var t = types_16[_i];
62435                 result |= getTypeFacts(t);
62436             }
62437             return result;
62438         }
62439         function isFunctionObjectType(type) {
62440             // We do a quick check for a "bind" property before performing the more expensive subtype
62441             // check. This gives us a quicker out in the common case where an object type is not a function.
62442             var resolved = resolveStructuredTypeMembers(type);
62443             return !!(resolved.callSignatures.length || resolved.constructSignatures.length ||
62444                 resolved.members.get("bind") && isTypeSubtypeOf(type, globalFunctionType));
62445         }
62446         function getTypeFacts(type) {
62447             var flags = type.flags;
62448             if (flags & 4 /* String */) {
62449                 return strictNullChecks ? 16317953 /* StringStrictFacts */ : 16776705 /* StringFacts */;
62450             }
62451             if (flags & 128 /* StringLiteral */) {
62452                 var isEmpty = type.value === "";
62453                 return strictNullChecks ?
62454                     isEmpty ? 12123649 /* EmptyStringStrictFacts */ : 7929345 /* NonEmptyStringStrictFacts */ :
62455                     isEmpty ? 12582401 /* EmptyStringFacts */ : 16776705 /* NonEmptyStringFacts */;
62456             }
62457             if (flags & (8 /* Number */ | 32 /* Enum */)) {
62458                 return strictNullChecks ? 16317698 /* NumberStrictFacts */ : 16776450 /* NumberFacts */;
62459             }
62460             if (flags & 256 /* NumberLiteral */) {
62461                 var isZero = type.value === 0;
62462                 return strictNullChecks ?
62463                     isZero ? 12123394 /* ZeroNumberStrictFacts */ : 7929090 /* NonZeroNumberStrictFacts */ :
62464                     isZero ? 12582146 /* ZeroNumberFacts */ : 16776450 /* NonZeroNumberFacts */;
62465             }
62466             if (flags & 64 /* BigInt */) {
62467                 return strictNullChecks ? 16317188 /* BigIntStrictFacts */ : 16775940 /* BigIntFacts */;
62468             }
62469             if (flags & 2048 /* BigIntLiteral */) {
62470                 var isZero = isZeroBigInt(type);
62471                 return strictNullChecks ?
62472                     isZero ? 12122884 /* ZeroBigIntStrictFacts */ : 7928580 /* NonZeroBigIntStrictFacts */ :
62473                     isZero ? 12581636 /* ZeroBigIntFacts */ : 16775940 /* NonZeroBigIntFacts */;
62474             }
62475             if (flags & 16 /* Boolean */) {
62476                 return strictNullChecks ? 16316168 /* BooleanStrictFacts */ : 16774920 /* BooleanFacts */;
62477             }
62478             if (flags & 528 /* BooleanLike */) {
62479                 return strictNullChecks ?
62480                     (type === falseType || type === regularFalseType) ? 12121864 /* FalseStrictFacts */ : 7927560 /* TrueStrictFacts */ :
62481                     (type === falseType || type === regularFalseType) ? 12580616 /* FalseFacts */ : 16774920 /* TrueFacts */;
62482             }
62483             if (flags & 524288 /* Object */) {
62484                 return ts.getObjectFlags(type) & 16 /* Anonymous */ && isEmptyObjectType(type) ?
62485                     strictNullChecks ? 16318463 /* EmptyObjectStrictFacts */ : 16777215 /* EmptyObjectFacts */ :
62486                     isFunctionObjectType(type) ?
62487                         strictNullChecks ? 7880640 /* FunctionStrictFacts */ : 16728000 /* FunctionFacts */ :
62488                         strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
62489             }
62490             if (flags & (16384 /* Void */ | 32768 /* Undefined */)) {
62491                 return 9830144 /* UndefinedFacts */;
62492             }
62493             if (flags & 65536 /* Null */) {
62494                 return 9363232 /* NullFacts */;
62495             }
62496             if (flags & 12288 /* ESSymbolLike */) {
62497                 return strictNullChecks ? 7925520 /* SymbolStrictFacts */ : 16772880 /* SymbolFacts */;
62498             }
62499             if (flags & 67108864 /* NonPrimitive */) {
62500                 return strictNullChecks ? 7888800 /* ObjectStrictFacts */ : 16736160 /* ObjectFacts */;
62501             }
62502             if (flags & 131072 /* Never */) {
62503                 return 0 /* None */;
62504             }
62505             if (flags & 465829888 /* Instantiable */) {
62506                 return getTypeFacts(getBaseConstraintOfType(type) || unknownType);
62507             }
62508             if (flags & 3145728 /* UnionOrIntersection */) {
62509                 return getTypeFactsOfTypes(type.types);
62510             }
62511             return 16777215 /* All */;
62512         }
62513         function getTypeWithFacts(type, include) {
62514             return filterType(type, function (t) { return (getTypeFacts(t) & include) !== 0; });
62515         }
62516         function getTypeWithDefault(type, defaultExpression) {
62517             if (defaultExpression) {
62518                 var defaultType = getTypeOfExpression(defaultExpression);
62519                 return getUnionType([getTypeWithFacts(type, 524288 /* NEUndefined */), defaultType]);
62520             }
62521             return type;
62522         }
62523         function getTypeOfDestructuredProperty(type, name) {
62524             var nameType = getLiteralTypeFromPropertyName(name);
62525             if (!isTypeUsableAsPropertyName(nameType))
62526                 return errorType;
62527             var text = getPropertyNameFromType(nameType);
62528             return getConstraintForLocation(getTypeOfPropertyOfType(type, text), name) ||
62529                 isNumericLiteralName(text) && includeUndefinedInIndexSignature(getIndexTypeOfType(type, 1 /* Number */)) ||
62530                 includeUndefinedInIndexSignature(getIndexTypeOfType(type, 0 /* String */)) ||
62531                 errorType;
62532         }
62533         function getTypeOfDestructuredArrayElement(type, index) {
62534             return everyType(type, isTupleLikeType) && getTupleElementType(type, index) ||
62535                 includeUndefinedInIndexSignature(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined)) ||
62536                 errorType;
62537         }
62538         function includeUndefinedInIndexSignature(type) {
62539             if (!type)
62540                 return type;
62541             return compilerOptions.noUncheckedIndexedAccess ?
62542                 getUnionType([type, undefinedType]) :
62543                 type;
62544         }
62545         function getTypeOfDestructuredSpreadExpression(type) {
62546             return createArrayType(checkIteratedTypeOrElementType(65 /* Destructuring */, type, undefinedType, /*errorNode*/ undefined) || errorType);
62547         }
62548         function getAssignedTypeOfBinaryExpression(node) {
62549             var isDestructuringDefaultAssignment = node.parent.kind === 199 /* ArrayLiteralExpression */ && isDestructuringAssignmentTarget(node.parent) ||
62550                 node.parent.kind === 288 /* PropertyAssignment */ && isDestructuringAssignmentTarget(node.parent.parent);
62551             return isDestructuringDefaultAssignment ?
62552                 getTypeWithDefault(getAssignedType(node), node.right) :
62553                 getTypeOfExpression(node.right);
62554         }
62555         function isDestructuringAssignmentTarget(parent) {
62556             return parent.parent.kind === 216 /* BinaryExpression */ && parent.parent.left === parent ||
62557                 parent.parent.kind === 239 /* ForOfStatement */ && parent.parent.initializer === parent;
62558         }
62559         function getAssignedTypeOfArrayLiteralElement(node, element) {
62560             return getTypeOfDestructuredArrayElement(getAssignedType(node), node.elements.indexOf(element));
62561         }
62562         function getAssignedTypeOfSpreadExpression(node) {
62563             return getTypeOfDestructuredSpreadExpression(getAssignedType(node.parent));
62564         }
62565         function getAssignedTypeOfPropertyAssignment(node) {
62566             return getTypeOfDestructuredProperty(getAssignedType(node.parent), node.name);
62567         }
62568         function getAssignedTypeOfShorthandPropertyAssignment(node) {
62569             return getTypeWithDefault(getAssignedTypeOfPropertyAssignment(node), node.objectAssignmentInitializer);
62570         }
62571         function getAssignedType(node) {
62572             var parent = node.parent;
62573             switch (parent.kind) {
62574                 case 238 /* ForInStatement */:
62575                     return stringType;
62576                 case 239 /* ForOfStatement */:
62577                     return checkRightHandSideOfForOf(parent) || errorType;
62578                 case 216 /* BinaryExpression */:
62579                     return getAssignedTypeOfBinaryExpression(parent);
62580                 case 210 /* DeleteExpression */:
62581                     return undefinedType;
62582                 case 199 /* ArrayLiteralExpression */:
62583                     return getAssignedTypeOfArrayLiteralElement(parent, node);
62584                 case 220 /* SpreadElement */:
62585                     return getAssignedTypeOfSpreadExpression(parent);
62586                 case 288 /* PropertyAssignment */:
62587                     return getAssignedTypeOfPropertyAssignment(parent);
62588                 case 289 /* ShorthandPropertyAssignment */:
62589                     return getAssignedTypeOfShorthandPropertyAssignment(parent);
62590             }
62591             return errorType;
62592         }
62593         function getInitialTypeOfBindingElement(node) {
62594             var pattern = node.parent;
62595             var parentType = getInitialType(pattern.parent);
62596             var type = pattern.kind === 196 /* ObjectBindingPattern */ ?
62597                 getTypeOfDestructuredProperty(parentType, node.propertyName || node.name) :
62598                 !node.dotDotDotToken ?
62599                     getTypeOfDestructuredArrayElement(parentType, pattern.elements.indexOf(node)) :
62600                     getTypeOfDestructuredSpreadExpression(parentType);
62601             return getTypeWithDefault(type, node.initializer);
62602         }
62603         function getTypeOfInitializer(node) {
62604             // Return the cached type if one is available. If the type of the variable was inferred
62605             // from its initializer, we'll already have cached the type. Otherwise we compute it now
62606             // without caching such that transient types are reflected.
62607             var links = getNodeLinks(node);
62608             return links.resolvedType || getTypeOfExpression(node);
62609         }
62610         function getInitialTypeOfVariableDeclaration(node) {
62611             if (node.initializer) {
62612                 return getTypeOfInitializer(node.initializer);
62613             }
62614             if (node.parent.parent.kind === 238 /* ForInStatement */) {
62615                 return stringType;
62616             }
62617             if (node.parent.parent.kind === 239 /* ForOfStatement */) {
62618                 return checkRightHandSideOfForOf(node.parent.parent) || errorType;
62619             }
62620             return errorType;
62621         }
62622         function getInitialType(node) {
62623             return node.kind === 249 /* VariableDeclaration */ ?
62624                 getInitialTypeOfVariableDeclaration(node) :
62625                 getInitialTypeOfBindingElement(node);
62626         }
62627         function isEmptyArrayAssignment(node) {
62628             return node.kind === 249 /* VariableDeclaration */ && node.initializer &&
62629                 isEmptyArrayLiteral(node.initializer) ||
62630                 node.kind !== 198 /* BindingElement */ && node.parent.kind === 216 /* BinaryExpression */ &&
62631                     isEmptyArrayLiteral(node.parent.right);
62632         }
62633         function getReferenceCandidate(node) {
62634             switch (node.kind) {
62635                 case 207 /* ParenthesizedExpression */:
62636                     return getReferenceCandidate(node.expression);
62637                 case 216 /* BinaryExpression */:
62638                     switch (node.operatorToken.kind) {
62639                         case 62 /* EqualsToken */:
62640                         case 74 /* BarBarEqualsToken */:
62641                         case 75 /* AmpersandAmpersandEqualsToken */:
62642                         case 76 /* QuestionQuestionEqualsToken */:
62643                             return getReferenceCandidate(node.left);
62644                         case 27 /* CommaToken */:
62645                             return getReferenceCandidate(node.right);
62646                     }
62647             }
62648             return node;
62649         }
62650         function getReferenceRoot(node) {
62651             var parent = node.parent;
62652             return parent.kind === 207 /* ParenthesizedExpression */ ||
62653                 parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */ && parent.left === node ||
62654                 parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 27 /* CommaToken */ && parent.right === node ?
62655                 getReferenceRoot(parent) : node;
62656         }
62657         function getTypeOfSwitchClause(clause) {
62658             if (clause.kind === 284 /* CaseClause */) {
62659                 return getRegularTypeOfLiteralType(getTypeOfExpression(clause.expression));
62660             }
62661             return neverType;
62662         }
62663         function getSwitchClauseTypes(switchStatement) {
62664             var links = getNodeLinks(switchStatement);
62665             if (!links.switchTypes) {
62666                 links.switchTypes = [];
62667                 for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
62668                     var clause = _a[_i];
62669                     links.switchTypes.push(getTypeOfSwitchClause(clause));
62670                 }
62671             }
62672             return links.switchTypes;
62673         }
62674         function getSwitchClauseTypeOfWitnesses(switchStatement, retainDefault) {
62675             var witnesses = [];
62676             for (var _i = 0, _a = switchStatement.caseBlock.clauses; _i < _a.length; _i++) {
62677                 var clause = _a[_i];
62678                 if (clause.kind === 284 /* CaseClause */) {
62679                     if (ts.isStringLiteralLike(clause.expression)) {
62680                         witnesses.push(clause.expression.text);
62681                         continue;
62682                     }
62683                     return ts.emptyArray;
62684                 }
62685                 if (retainDefault)
62686                     witnesses.push(/*explicitDefaultStatement*/ undefined);
62687             }
62688             return witnesses;
62689         }
62690         function eachTypeContainedIn(source, types) {
62691             return source.flags & 1048576 /* Union */ ? !ts.forEach(source.types, function (t) { return !ts.contains(types, t); }) : ts.contains(types, source);
62692         }
62693         function isTypeSubsetOf(source, target) {
62694             return source === target || target.flags & 1048576 /* Union */ && isTypeSubsetOfUnion(source, target);
62695         }
62696         function isTypeSubsetOfUnion(source, target) {
62697             if (source.flags & 1048576 /* Union */) {
62698                 for (var _i = 0, _a = source.types; _i < _a.length; _i++) {
62699                     var t = _a[_i];
62700                     if (!containsType(target.types, t)) {
62701                         return false;
62702                     }
62703                 }
62704                 return true;
62705             }
62706             if (source.flags & 1024 /* EnumLiteral */ && getBaseTypeOfEnumLiteralType(source) === target) {
62707                 return true;
62708             }
62709             return containsType(target.types, source);
62710         }
62711         function forEachType(type, f) {
62712             return type.flags & 1048576 /* Union */ ? ts.forEach(type.types, f) : f(type);
62713         }
62714         function everyType(type, f) {
62715             return type.flags & 1048576 /* Union */ ? ts.every(type.types, f) : f(type);
62716         }
62717         function filterType(type, f) {
62718             if (type.flags & 1048576 /* Union */) {
62719                 var types = type.types;
62720                 var filtered = ts.filter(types, f);
62721                 return filtered === types ? type : getUnionTypeFromSortedList(filtered, type.objectFlags);
62722             }
62723             return type.flags & 131072 /* Never */ || f(type) ? type : neverType;
62724         }
62725         function countTypes(type) {
62726             return type.flags & 1048576 /* Union */ ? type.types.length : 1;
62727         }
62728         function mapType(type, mapper, noReductions) {
62729             if (type.flags & 131072 /* Never */) {
62730                 return type;
62731             }
62732             if (!(type.flags & 1048576 /* Union */)) {
62733                 return mapper(type);
62734             }
62735             var mappedTypes;
62736             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
62737                 var t = _a[_i];
62738                 var mapped = mapper(t);
62739                 if (mapped) {
62740                     if (!mappedTypes) {
62741                         mappedTypes = [mapped];
62742                     }
62743                     else {
62744                         mappedTypes.push(mapped);
62745                     }
62746                 }
62747             }
62748             return mappedTypes && getUnionType(mappedTypes, noReductions ? 0 /* None */ : 1 /* Literal */);
62749         }
62750         function extractTypesOfKind(type, kind) {
62751             return filterType(type, function (t) { return (t.flags & kind) !== 0; });
62752         }
62753         // Return a new type in which occurrences of the string and number primitive types in
62754         // typeWithPrimitives have been replaced with occurrences of string literals and numeric
62755         // literals in typeWithLiterals, respectively.
62756         function replacePrimitivesWithLiterals(typeWithPrimitives, typeWithLiterals) {
62757             if (isTypeSubsetOf(stringType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 128 /* StringLiteral */) ||
62758                 isTypeSubsetOf(numberType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 256 /* NumberLiteral */) ||
62759                 isTypeSubsetOf(bigintType, typeWithPrimitives) && maybeTypeOfKind(typeWithLiterals, 2048 /* BigIntLiteral */)) {
62760                 return mapType(typeWithPrimitives, function (t) {
62761                     return t.flags & 4 /* String */ ? extractTypesOfKind(typeWithLiterals, 4 /* String */ | 128 /* StringLiteral */) :
62762                         t.flags & 8 /* Number */ ? extractTypesOfKind(typeWithLiterals, 8 /* Number */ | 256 /* NumberLiteral */) :
62763                             t.flags & 64 /* BigInt */ ? extractTypesOfKind(typeWithLiterals, 64 /* BigInt */ | 2048 /* BigIntLiteral */) : t;
62764                 });
62765             }
62766             return typeWithPrimitives;
62767         }
62768         function isIncomplete(flowType) {
62769             return flowType.flags === 0;
62770         }
62771         function getTypeFromFlowType(flowType) {
62772             return flowType.flags === 0 ? flowType.type : flowType;
62773         }
62774         function createFlowType(type, incomplete) {
62775             return incomplete ? { flags: 0, type: type.flags & 131072 /* Never */ ? silentNeverType : type } : type;
62776         }
62777         // An evolving array type tracks the element types that have so far been seen in an
62778         // 'x.push(value)' or 'x[n] = value' operation along the control flow graph. Evolving
62779         // array types are ultimately converted into manifest array types (using getFinalArrayType)
62780         // and never escape the getFlowTypeOfReference function.
62781         function createEvolvingArrayType(elementType) {
62782             var result = createObjectType(256 /* EvolvingArray */);
62783             result.elementType = elementType;
62784             return result;
62785         }
62786         function getEvolvingArrayType(elementType) {
62787             return evolvingArrayTypes[elementType.id] || (evolvingArrayTypes[elementType.id] = createEvolvingArrayType(elementType));
62788         }
62789         // When adding evolving array element types we do not perform subtype reduction. Instead,
62790         // we defer subtype reduction until the evolving array type is finalized into a manifest
62791         // array type.
62792         function addEvolvingArrayElementType(evolvingArrayType, node) {
62793             var elementType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(getContextFreeTypeOfExpression(node)));
62794             return isTypeSubsetOf(elementType, evolvingArrayType.elementType) ? evolvingArrayType : getEvolvingArrayType(getUnionType([evolvingArrayType.elementType, elementType]));
62795         }
62796         function createFinalArrayType(elementType) {
62797             return elementType.flags & 131072 /* Never */ ?
62798                 autoArrayType :
62799                 createArrayType(elementType.flags & 1048576 /* Union */ ?
62800                     getUnionType(elementType.types, 2 /* Subtype */) :
62801                     elementType);
62802         }
62803         // We perform subtype reduction upon obtaining the final array type from an evolving array type.
62804         function getFinalArrayType(evolvingArrayType) {
62805             return evolvingArrayType.finalArrayType || (evolvingArrayType.finalArrayType = createFinalArrayType(evolvingArrayType.elementType));
62806         }
62807         function finalizeEvolvingArrayType(type) {
62808             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? getFinalArrayType(type) : type;
62809         }
62810         function getElementTypeOfEvolvingArrayType(type) {
62811             return ts.getObjectFlags(type) & 256 /* EvolvingArray */ ? type.elementType : neverType;
62812         }
62813         function isEvolvingArrayTypeList(types) {
62814             var hasEvolvingArrayType = false;
62815             for (var _i = 0, types_17 = types; _i < types_17.length; _i++) {
62816                 var t = types_17[_i];
62817                 if (!(t.flags & 131072 /* Never */)) {
62818                     if (!(ts.getObjectFlags(t) & 256 /* EvolvingArray */)) {
62819                         return false;
62820                     }
62821                     hasEvolvingArrayType = true;
62822                 }
62823             }
62824             return hasEvolvingArrayType;
62825         }
62826         // At flow control branch or loop junctions, if the type along every antecedent code path
62827         // is an evolving array type, we construct a combined evolving array type. Otherwise we
62828         // finalize all evolving array types.
62829         function getUnionOrEvolvingArrayType(types, subtypeReduction) {
62830             return isEvolvingArrayTypeList(types) ?
62831                 getEvolvingArrayType(getUnionType(ts.map(types, getElementTypeOfEvolvingArrayType))) :
62832                 getUnionType(ts.sameMap(types, finalizeEvolvingArrayType), subtypeReduction);
62833         }
62834         // Return true if the given node is 'x' in an 'x.length', x.push(value)', 'x.unshift(value)' or
62835         // 'x[n] = value' operation, where 'n' is an expression of type any, undefined, or a number-like type.
62836         function isEvolvingArrayOperationTarget(node) {
62837             var root = getReferenceRoot(node);
62838             var parent = root.parent;
62839             var isLengthPushOrUnshift = ts.isPropertyAccessExpression(parent) && (parent.name.escapedText === "length" ||
62840                 parent.parent.kind === 203 /* CallExpression */
62841                     && ts.isIdentifier(parent.name)
62842                     && ts.isPushOrUnshiftIdentifier(parent.name));
62843             var isElementAssignment = parent.kind === 202 /* ElementAccessExpression */ &&
62844                 parent.expression === root &&
62845                 parent.parent.kind === 216 /* BinaryExpression */ &&
62846                 parent.parent.operatorToken.kind === 62 /* EqualsToken */ &&
62847                 parent.parent.left === parent &&
62848                 !ts.isAssignmentTarget(parent.parent) &&
62849                 isTypeAssignableToKind(getTypeOfExpression(parent.argumentExpression), 296 /* NumberLike */);
62850             return isLengthPushOrUnshift || isElementAssignment;
62851         }
62852         function isDeclarationWithExplicitTypeAnnotation(declaration) {
62853             return (declaration.kind === 249 /* VariableDeclaration */ || declaration.kind === 160 /* Parameter */ ||
62854                 declaration.kind === 163 /* PropertyDeclaration */ || declaration.kind === 162 /* PropertySignature */) &&
62855                 !!ts.getEffectiveTypeAnnotationNode(declaration);
62856         }
62857         function getExplicitTypeOfSymbol(symbol, diagnostic) {
62858             if (symbol.flags & (16 /* Function */ | 8192 /* Method */ | 32 /* Class */ | 512 /* ValueModule */)) {
62859                 return getTypeOfSymbol(symbol);
62860             }
62861             if (symbol.flags & (3 /* Variable */ | 4 /* Property */)) {
62862                 if (ts.getCheckFlags(symbol) & 262144 /* Mapped */) {
62863                     var origin = symbol.syntheticOrigin;
62864                     if (origin && getExplicitTypeOfSymbol(origin)) {
62865                         return getTypeOfSymbol(symbol);
62866                     }
62867                 }
62868                 var declaration = symbol.valueDeclaration;
62869                 if (declaration) {
62870                     if (isDeclarationWithExplicitTypeAnnotation(declaration)) {
62871                         return getTypeOfSymbol(symbol);
62872                     }
62873                     if (ts.isVariableDeclaration(declaration) && declaration.parent.parent.kind === 239 /* ForOfStatement */) {
62874                         var statement = declaration.parent.parent;
62875                         var expressionType = getTypeOfDottedName(statement.expression, /*diagnostic*/ undefined);
62876                         if (expressionType) {
62877                             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
62878                             return checkIteratedTypeOrElementType(use, expressionType, undefinedType, /*errorNode*/ undefined);
62879                         }
62880                     }
62881                     if (diagnostic) {
62882                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(declaration, ts.Diagnostics._0_needs_an_explicit_type_annotation, symbolToString(symbol)));
62883                     }
62884                 }
62885             }
62886         }
62887         // We require the dotted function name in an assertion expression to be comprised of identifiers
62888         // that reference function, method, class or value module symbols; or variable, property or
62889         // parameter symbols with declarations that have explicit type annotations. Such references are
62890         // resolvable with no possibility of triggering circularities in control flow analysis.
62891         function getTypeOfDottedName(node, diagnostic) {
62892             if (!(node.flags & 16777216 /* InWithStatement */)) {
62893                 switch (node.kind) {
62894                     case 78 /* Identifier */:
62895                         var symbol = getExportSymbolOfValueSymbolIfExported(getResolvedSymbol(node));
62896                         return getExplicitTypeOfSymbol(symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol, diagnostic);
62897                     case 107 /* ThisKeyword */:
62898                         return getExplicitThisType(node);
62899                     case 105 /* SuperKeyword */:
62900                         return checkSuperExpression(node);
62901                     case 201 /* PropertyAccessExpression */:
62902                         var type = getTypeOfDottedName(node.expression, diagnostic);
62903                         var prop = type && getPropertyOfType(type, node.name.escapedText);
62904                         return prop && getExplicitTypeOfSymbol(prop, diagnostic);
62905                     case 207 /* ParenthesizedExpression */:
62906                         return getTypeOfDottedName(node.expression, diagnostic);
62907                 }
62908             }
62909         }
62910         function getEffectsSignature(node) {
62911             var links = getNodeLinks(node);
62912             var signature = links.effectsSignature;
62913             if (signature === undefined) {
62914                 // A call expression parented by an expression statement is a potential assertion. Other call
62915                 // expressions are potential type predicate function calls. In order to avoid triggering
62916                 // circularities in control flow analysis, we use getTypeOfDottedName when resolving the call
62917                 // target expression of an assertion.
62918                 var funcType = void 0;
62919                 if (node.parent.kind === 233 /* ExpressionStatement */) {
62920                     funcType = getTypeOfDottedName(node.expression, /*diagnostic*/ undefined);
62921                 }
62922                 else if (node.expression.kind !== 105 /* SuperKeyword */) {
62923                     if (ts.isOptionalChain(node)) {
62924                         funcType = checkNonNullType(getOptionalExpressionType(checkExpression(node.expression), node.expression), node.expression);
62925                     }
62926                     else {
62927                         funcType = checkNonNullExpression(node.expression);
62928                     }
62929                 }
62930                 var signatures = getSignaturesOfType(funcType && getApparentType(funcType) || unknownType, 0 /* Call */);
62931                 var candidate = signatures.length === 1 && !signatures[0].typeParameters ? signatures[0] :
62932                     ts.some(signatures, hasTypePredicateOrNeverReturnType) ? getResolvedSignature(node) :
62933                         undefined;
62934                 signature = links.effectsSignature = candidate && hasTypePredicateOrNeverReturnType(candidate) ? candidate : unknownSignature;
62935             }
62936             return signature === unknownSignature ? undefined : signature;
62937         }
62938         function hasTypePredicateOrNeverReturnType(signature) {
62939             return !!(getTypePredicateOfSignature(signature) ||
62940                 signature.declaration && (getReturnTypeFromAnnotation(signature.declaration) || unknownType).flags & 131072 /* Never */);
62941         }
62942         function getTypePredicateArgument(predicate, callExpression) {
62943             if (predicate.kind === 1 /* Identifier */ || predicate.kind === 3 /* AssertsIdentifier */) {
62944                 return callExpression.arguments[predicate.parameterIndex];
62945             }
62946             var invokedExpression = ts.skipParentheses(callExpression.expression);
62947             return ts.isAccessExpression(invokedExpression) ? ts.skipParentheses(invokedExpression.expression) : undefined;
62948         }
62949         function reportFlowControlError(node) {
62950             var block = ts.findAncestor(node, ts.isFunctionOrModuleBlock);
62951             var sourceFile = ts.getSourceFileOfNode(node);
62952             var span = ts.getSpanOfTokenAtPosition(sourceFile, block.statements.pos);
62953             diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, ts.Diagnostics.The_containing_function_or_module_body_is_too_large_for_control_flow_analysis));
62954         }
62955         function isReachableFlowNode(flow) {
62956             var result = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ false);
62957             lastFlowNode = flow;
62958             lastFlowNodeReachable = result;
62959             return result;
62960         }
62961         function isFalseExpression(expr) {
62962             var node = ts.skipParentheses(expr);
62963             return node.kind === 94 /* FalseKeyword */ || node.kind === 216 /* BinaryExpression */ && (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && (isFalseExpression(node.left) || isFalseExpression(node.right)) ||
62964                 node.operatorToken.kind === 56 /* BarBarToken */ && isFalseExpression(node.left) && isFalseExpression(node.right));
62965         }
62966         function isReachableFlowNodeWorker(flow, noCacheCheck) {
62967             while (true) {
62968                 if (flow === lastFlowNode) {
62969                     return lastFlowNodeReachable;
62970                 }
62971                 var flags = flow.flags;
62972                 if (flags & 4096 /* Shared */) {
62973                     if (!noCacheCheck) {
62974                         var id = getFlowNodeId(flow);
62975                         var reachable = flowNodeReachable[id];
62976                         return reachable !== undefined ? reachable : (flowNodeReachable[id] = isReachableFlowNodeWorker(flow, /*noCacheCheck*/ true));
62977                     }
62978                     noCacheCheck = false;
62979                 }
62980                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */)) {
62981                     flow = flow.antecedent;
62982                 }
62983                 else if (flags & 512 /* Call */) {
62984                     var signature = getEffectsSignature(flow.node);
62985                     if (signature) {
62986                         var predicate = getTypePredicateOfSignature(signature);
62987                         if (predicate && predicate.kind === 3 /* AssertsIdentifier */ && !predicate.type) {
62988                             var predicateArgument = flow.node.arguments[predicate.parameterIndex];
62989                             if (predicateArgument && isFalseExpression(predicateArgument)) {
62990                                 return false;
62991                             }
62992                         }
62993                         if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
62994                             return false;
62995                         }
62996                     }
62997                     flow = flow.antecedent;
62998                 }
62999                 else if (flags & 4 /* BranchLabel */) {
63000                     // A branching point is reachable if any branch is reachable.
63001                     return ts.some(flow.antecedents, function (f) { return isReachableFlowNodeWorker(f, /*noCacheCheck*/ false); });
63002                 }
63003                 else if (flags & 8 /* LoopLabel */) {
63004                     // A loop is reachable if the control flow path that leads to the top is reachable.
63005                     flow = flow.antecedents[0];
63006                 }
63007                 else if (flags & 128 /* SwitchClause */) {
63008                     // The control flow path representing an unmatched value in a switch statement with
63009                     // no default clause is unreachable if the switch statement is exhaustive.
63010                     if (flow.clauseStart === flow.clauseEnd && isExhaustiveSwitchStatement(flow.switchStatement)) {
63011                         return false;
63012                     }
63013                     flow = flow.antecedent;
63014                 }
63015                 else if (flags & 1024 /* ReduceLabel */) {
63016                     // Cache is unreliable once we start adjusting labels
63017                     lastFlowNode = undefined;
63018                     var target = flow.target;
63019                     var saveAntecedents = target.antecedents;
63020                     target.antecedents = flow.antecedents;
63021                     var result = isReachableFlowNodeWorker(flow.antecedent, /*noCacheCheck*/ false);
63022                     target.antecedents = saveAntecedents;
63023                     return result;
63024                 }
63025                 else {
63026                     return !(flags & 1 /* Unreachable */);
63027                 }
63028             }
63029         }
63030         // Return true if the given flow node is preceded by a 'super(...)' call in every possible code path
63031         // leading to the node.
63032         function isPostSuperFlowNode(flow, noCacheCheck) {
63033             while (true) {
63034                 var flags = flow.flags;
63035                 if (flags & 4096 /* Shared */) {
63036                     if (!noCacheCheck) {
63037                         var id = getFlowNodeId(flow);
63038                         var postSuper = flowNodePostSuper[id];
63039                         return postSuper !== undefined ? postSuper : (flowNodePostSuper[id] = isPostSuperFlowNode(flow, /*noCacheCheck*/ true));
63040                     }
63041                     noCacheCheck = false;
63042                 }
63043                 if (flags & (16 /* Assignment */ | 96 /* Condition */ | 256 /* ArrayMutation */ | 128 /* SwitchClause */)) {
63044                     flow = flow.antecedent;
63045                 }
63046                 else if (flags & 512 /* Call */) {
63047                     if (flow.node.expression.kind === 105 /* SuperKeyword */) {
63048                         return true;
63049                     }
63050                     flow = flow.antecedent;
63051                 }
63052                 else if (flags & 4 /* BranchLabel */) {
63053                     // A branching point is post-super if every branch is post-super.
63054                     return ts.every(flow.antecedents, function (f) { return isPostSuperFlowNode(f, /*noCacheCheck*/ false); });
63055                 }
63056                 else if (flags & 8 /* LoopLabel */) {
63057                     // A loop is post-super if the control flow path that leads to the top is post-super.
63058                     flow = flow.antecedents[0];
63059                 }
63060                 else if (flags & 1024 /* ReduceLabel */) {
63061                     var target = flow.target;
63062                     var saveAntecedents = target.antecedents;
63063                     target.antecedents = flow.antecedents;
63064                     var result = isPostSuperFlowNode(flow.antecedent, /*noCacheCheck*/ false);
63065                     target.antecedents = saveAntecedents;
63066                     return result;
63067                 }
63068                 else {
63069                     // Unreachable nodes are considered post-super to silence errors
63070                     return !!(flags & 1 /* Unreachable */);
63071                 }
63072             }
63073         }
63074         function getFlowTypeOfReference(reference, declaredType, initialType, flowContainer, couldBeUninitialized) {
63075             if (initialType === void 0) { initialType = declaredType; }
63076             var key;
63077             var isKeySet = false;
63078             var flowDepth = 0;
63079             if (flowAnalysisDisabled) {
63080                 return errorType;
63081             }
63082             if (!reference.flowNode || !couldBeUninitialized && !(declaredType.flags & 536624127 /* Narrowable */)) {
63083                 return declaredType;
63084             }
63085             flowInvocationCount++;
63086             var sharedFlowStart = sharedFlowCount;
63087             var evolvedType = getTypeFromFlowType(getTypeAtFlowNode(reference.flowNode));
63088             sharedFlowCount = sharedFlowStart;
63089             // When the reference is 'x' in an 'x.length', 'x.push(value)', 'x.unshift(value)' or x[n] = value' operation,
63090             // we give type 'any[]' to 'x' instead of using the type determined by control flow analysis such that operations
63091             // on empty arrays are possible without implicit any errors and new element types can be inferred without
63092             // type mismatch errors.
63093             var resultType = ts.getObjectFlags(evolvedType) & 256 /* EvolvingArray */ && isEvolvingArrayOperationTarget(reference) ? autoArrayType : finalizeEvolvingArrayType(evolvedType);
63094             if (resultType === unreachableNeverType || reference.parent && reference.parent.kind === 225 /* NonNullExpression */ && getTypeWithFacts(resultType, 2097152 /* NEUndefinedOrNull */).flags & 131072 /* Never */) {
63095                 return declaredType;
63096             }
63097             return resultType;
63098             function getOrSetCacheKey() {
63099                 if (isKeySet) {
63100                     return key;
63101                 }
63102                 isKeySet = true;
63103                 return key = getFlowCacheKey(reference, declaredType, initialType, flowContainer);
63104             }
63105             function getTypeAtFlowNode(flow) {
63106                 if (flowDepth === 2000) {
63107                     // We have made 2000 recursive invocations. To avoid overflowing the call stack we report an error
63108                     // and disable further control flow analysis in the containing function or module body.
63109                     ts.tracing.instant("check" /* Check */, "getTypeAtFlowNode_DepthLimit", { flowId: flow.id });
63110                     flowAnalysisDisabled = true;
63111                     reportFlowControlError(reference);
63112                     return errorType;
63113                 }
63114                 flowDepth++;
63115                 while (true) {
63116                     var flags = flow.flags;
63117                     if (flags & 4096 /* Shared */) {
63118                         // We cache results of flow type resolution for shared nodes that were previously visited in
63119                         // the same getFlowTypeOfReference invocation. A node is considered shared when it is the
63120                         // antecedent of more than one node.
63121                         for (var i = sharedFlowStart; i < sharedFlowCount; i++) {
63122                             if (sharedFlowNodes[i] === flow) {
63123                                 flowDepth--;
63124                                 return sharedFlowTypes[i];
63125                             }
63126                         }
63127                     }
63128                     var type = void 0;
63129                     if (flags & 16 /* Assignment */) {
63130                         type = getTypeAtFlowAssignment(flow);
63131                         if (!type) {
63132                             flow = flow.antecedent;
63133                             continue;
63134                         }
63135                     }
63136                     else if (flags & 512 /* Call */) {
63137                         type = getTypeAtFlowCall(flow);
63138                         if (!type) {
63139                             flow = flow.antecedent;
63140                             continue;
63141                         }
63142                     }
63143                     else if (flags & 96 /* Condition */) {
63144                         type = getTypeAtFlowCondition(flow);
63145                     }
63146                     else if (flags & 128 /* SwitchClause */) {
63147                         type = getTypeAtSwitchClause(flow);
63148                     }
63149                     else if (flags & 12 /* Label */) {
63150                         if (flow.antecedents.length === 1) {
63151                             flow = flow.antecedents[0];
63152                             continue;
63153                         }
63154                         type = flags & 4 /* BranchLabel */ ?
63155                             getTypeAtFlowBranchLabel(flow) :
63156                             getTypeAtFlowLoopLabel(flow);
63157                     }
63158                     else if (flags & 256 /* ArrayMutation */) {
63159                         type = getTypeAtFlowArrayMutation(flow);
63160                         if (!type) {
63161                             flow = flow.antecedent;
63162                             continue;
63163                         }
63164                     }
63165                     else if (flags & 1024 /* ReduceLabel */) {
63166                         var target = flow.target;
63167                         var saveAntecedents = target.antecedents;
63168                         target.antecedents = flow.antecedents;
63169                         type = getTypeAtFlowNode(flow.antecedent);
63170                         target.antecedents = saveAntecedents;
63171                     }
63172                     else if (flags & 2 /* Start */) {
63173                         // Check if we should continue with the control flow of the containing function.
63174                         var container = flow.node;
63175                         if (container && container !== flowContainer &&
63176                             reference.kind !== 201 /* PropertyAccessExpression */ &&
63177                             reference.kind !== 202 /* ElementAccessExpression */ &&
63178                             reference.kind !== 107 /* ThisKeyword */) {
63179                             flow = container.flowNode;
63180                             continue;
63181                         }
63182                         // At the top of the flow we have the initial type.
63183                         type = initialType;
63184                     }
63185                     else {
63186                         // Unreachable code errors are reported in the binding phase. Here we
63187                         // simply return the non-auto declared type to reduce follow-on errors.
63188                         type = convertAutoToAny(declaredType);
63189                     }
63190                     if (flags & 4096 /* Shared */) {
63191                         // Record visited node and the associated type in the cache.
63192                         sharedFlowNodes[sharedFlowCount] = flow;
63193                         sharedFlowTypes[sharedFlowCount] = type;
63194                         sharedFlowCount++;
63195                     }
63196                     flowDepth--;
63197                     return type;
63198                 }
63199             }
63200             function getInitialOrAssignedType(flow) {
63201                 var node = flow.node;
63202                 return getConstraintForLocation(node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */ ?
63203                     getInitialType(node) :
63204                     getAssignedType(node), reference);
63205             }
63206             function getTypeAtFlowAssignment(flow) {
63207                 var node = flow.node;
63208                 // Assignments only narrow the computed type if the declared type is a union type. Thus, we
63209                 // only need to evaluate the assigned type if the declared type is a union type.
63210                 if (isMatchingReference(reference, node)) {
63211                     if (!isReachableFlowNode(flow)) {
63212                         return unreachableNeverType;
63213                     }
63214                     if (ts.getAssignmentTargetKind(node) === 2 /* Compound */) {
63215                         var flowType = getTypeAtFlowNode(flow.antecedent);
63216                         return createFlowType(getBaseTypeOfLiteralType(getTypeFromFlowType(flowType)), isIncomplete(flowType));
63217                     }
63218                     if (declaredType === autoType || declaredType === autoArrayType) {
63219                         if (isEmptyArrayAssignment(node)) {
63220                             return getEvolvingArrayType(neverType);
63221                         }
63222                         var assignedType = getWidenedLiteralType(getInitialOrAssignedType(flow));
63223                         return isTypeAssignableTo(assignedType, declaredType) ? assignedType : anyArrayType;
63224                     }
63225                     if (declaredType.flags & 1048576 /* Union */) {
63226                         return getAssignmentReducedType(declaredType, getInitialOrAssignedType(flow));
63227                     }
63228                     return declaredType;
63229                 }
63230                 // We didn't have a direct match. However, if the reference is a dotted name, this
63231                 // may be an assignment to a left hand part of the reference. For example, for a
63232                 // reference 'x.y.z', we may be at an assignment to 'x.y' or 'x'. In that case,
63233                 // return the declared type.
63234                 if (containsMatchingReference(reference, node)) {
63235                     if (!isReachableFlowNode(flow)) {
63236                         return unreachableNeverType;
63237                     }
63238                     // A matching dotted name might also be an expando property on a function *expression*,
63239                     // in which case we continue control flow analysis back to the function's declaration
63240                     if (ts.isVariableDeclaration(node) && (ts.isInJSFile(node) || ts.isVarConst(node))) {
63241                         var init = ts.getDeclaredExpandoInitializer(node);
63242                         if (init && (init.kind === 208 /* FunctionExpression */ || init.kind === 209 /* ArrowFunction */)) {
63243                             return getTypeAtFlowNode(flow.antecedent);
63244                         }
63245                     }
63246                     return declaredType;
63247                 }
63248                 // for (const _ in ref) acts as a nonnull on ref
63249                 if (ts.isVariableDeclaration(node) && node.parent.parent.kind === 238 /* ForInStatement */ && isMatchingReference(reference, node.parent.parent.expression)) {
63250                     return getNonNullableTypeIfNeeded(getTypeFromFlowType(getTypeAtFlowNode(flow.antecedent)));
63251                 }
63252                 // Assignment doesn't affect reference
63253                 return undefined;
63254             }
63255             function narrowTypeByAssertion(type, expr) {
63256                 var node = ts.skipParentheses(expr);
63257                 if (node.kind === 94 /* FalseKeyword */) {
63258                     return unreachableNeverType;
63259                 }
63260                 if (node.kind === 216 /* BinaryExpression */) {
63261                     if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
63262                         return narrowTypeByAssertion(narrowTypeByAssertion(type, node.left), node.right);
63263                     }
63264                     if (node.operatorToken.kind === 56 /* BarBarToken */) {
63265                         return getUnionType([narrowTypeByAssertion(type, node.left), narrowTypeByAssertion(type, node.right)]);
63266                     }
63267                 }
63268                 return narrowType(type, node, /*assumeTrue*/ true);
63269             }
63270             function getTypeAtFlowCall(flow) {
63271                 var signature = getEffectsSignature(flow.node);
63272                 if (signature) {
63273                     var predicate = getTypePredicateOfSignature(signature);
63274                     if (predicate && (predicate.kind === 2 /* AssertsThis */ || predicate.kind === 3 /* AssertsIdentifier */)) {
63275                         var flowType = getTypeAtFlowNode(flow.antecedent);
63276                         var type = finalizeEvolvingArrayType(getTypeFromFlowType(flowType));
63277                         var narrowedType = predicate.type ? narrowTypeByTypePredicate(type, predicate, flow.node, /*assumeTrue*/ true) :
63278                             predicate.kind === 3 /* AssertsIdentifier */ && predicate.parameterIndex >= 0 && predicate.parameterIndex < flow.node.arguments.length ? narrowTypeByAssertion(type, flow.node.arguments[predicate.parameterIndex]) :
63279                                 type;
63280                         return narrowedType === type ? flowType : createFlowType(narrowedType, isIncomplete(flowType));
63281                     }
63282                     if (getReturnTypeOfSignature(signature).flags & 131072 /* Never */) {
63283                         return unreachableNeverType;
63284                     }
63285                 }
63286                 return undefined;
63287             }
63288             function getTypeAtFlowArrayMutation(flow) {
63289                 if (declaredType === autoType || declaredType === autoArrayType) {
63290                     var node = flow.node;
63291                     var expr = node.kind === 203 /* CallExpression */ ?
63292                         node.expression.expression :
63293                         node.left.expression;
63294                     if (isMatchingReference(reference, getReferenceCandidate(expr))) {
63295                         var flowType = getTypeAtFlowNode(flow.antecedent);
63296                         var type = getTypeFromFlowType(flowType);
63297                         if (ts.getObjectFlags(type) & 256 /* EvolvingArray */) {
63298                             var evolvedType_1 = type;
63299                             if (node.kind === 203 /* CallExpression */) {
63300                                 for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
63301                                     var arg = _a[_i];
63302                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, arg);
63303                                 }
63304                             }
63305                             else {
63306                                 // 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)
63307                                 var indexType = getContextFreeTypeOfExpression(node.left.argumentExpression);
63308                                 if (isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
63309                                     evolvedType_1 = addEvolvingArrayElementType(evolvedType_1, node.right);
63310                                 }
63311                             }
63312                             return evolvedType_1 === type ? flowType : createFlowType(evolvedType_1, isIncomplete(flowType));
63313                         }
63314                         return flowType;
63315                     }
63316                 }
63317                 return undefined;
63318             }
63319             function getTypeAtFlowCondition(flow) {
63320                 var flowType = getTypeAtFlowNode(flow.antecedent);
63321                 var type = getTypeFromFlowType(flowType);
63322                 if (type.flags & 131072 /* Never */) {
63323                     return flowType;
63324                 }
63325                 // If we have an antecedent type (meaning we're reachable in some way), we first
63326                 // attempt to narrow the antecedent type. If that produces the never type, and if
63327                 // the antecedent type is incomplete (i.e. a transient type in a loop), then we
63328                 // take the type guard as an indication that control *could* reach here once we
63329                 // have the complete type. We proceed by switching to the silent never type which
63330                 // doesn't report errors when operators are applied to it. Note that this is the
63331                 // *only* place a silent never type is ever generated.
63332                 var assumeTrue = (flow.flags & 32 /* TrueCondition */) !== 0;
63333                 var nonEvolvingType = finalizeEvolvingArrayType(type);
63334                 var narrowedType = narrowType(nonEvolvingType, flow.node, assumeTrue);
63335                 if (narrowedType === nonEvolvingType) {
63336                     return flowType;
63337                 }
63338                 return createFlowType(narrowedType, isIncomplete(flowType));
63339             }
63340             function getTypeAtSwitchClause(flow) {
63341                 var expr = flow.switchStatement.expression;
63342                 var flowType = getTypeAtFlowNode(flow.antecedent);
63343                 var type = getTypeFromFlowType(flowType);
63344                 if (isMatchingReference(reference, expr)) {
63345                     type = narrowTypeBySwitchOnDiscriminant(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
63346                 }
63347                 else if (expr.kind === 211 /* TypeOfExpression */ && isMatchingReference(reference, expr.expression)) {
63348                     type = narrowBySwitchOnTypeOf(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd);
63349                 }
63350                 else {
63351                     if (strictNullChecks) {
63352                         if (optionalChainContainsReference(expr, reference)) {
63353                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & (32768 /* Undefined */ | 131072 /* Never */)); });
63354                         }
63355                         else if (expr.kind === 211 /* TypeOfExpression */ && optionalChainContainsReference(expr.expression, reference)) {
63356                             type = narrowTypeBySwitchOptionalChainContainment(type, flow.switchStatement, flow.clauseStart, flow.clauseEnd, function (t) { return !(t.flags & 131072 /* Never */ || t.flags & 128 /* StringLiteral */ && t.value === "undefined"); });
63357                         }
63358                     }
63359                     if (isMatchingReferenceDiscriminant(expr, type)) {
63360                         type = narrowTypeByDiscriminant(type, expr, function (t) { return narrowTypeBySwitchOnDiscriminant(t, flow.switchStatement, flow.clauseStart, flow.clauseEnd); });
63361                     }
63362                 }
63363                 return createFlowType(type, isIncomplete(flowType));
63364             }
63365             function getTypeAtFlowBranchLabel(flow) {
63366                 var antecedentTypes = [];
63367                 var subtypeReduction = false;
63368                 var seenIncomplete = false;
63369                 var bypassFlow;
63370                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
63371                     var antecedent = _a[_i];
63372                     if (!bypassFlow && antecedent.flags & 128 /* SwitchClause */ && antecedent.clauseStart === antecedent.clauseEnd) {
63373                         // The antecedent is the bypass branch of a potentially exhaustive switch statement.
63374                         bypassFlow = antecedent;
63375                         continue;
63376                     }
63377                     var flowType = getTypeAtFlowNode(antecedent);
63378                     var type = getTypeFromFlowType(flowType);
63379                     // If the type at a particular antecedent path is the declared type and the
63380                     // reference is known to always be assigned (i.e. when declared and initial types
63381                     // are the same), there is no reason to process more antecedents since the only
63382                     // possible outcome is subtypes that will be removed in the final union type anyway.
63383                     if (type === declaredType && declaredType === initialType) {
63384                         return type;
63385                     }
63386                     ts.pushIfUnique(antecedentTypes, type);
63387                     // If an antecedent type is not a subset of the declared type, we need to perform
63388                     // subtype reduction. This happens when a "foreign" type is injected into the control
63389                     // flow using the instanceof operator or a user defined type predicate.
63390                     if (!isTypeSubsetOf(type, declaredType)) {
63391                         subtypeReduction = true;
63392                     }
63393                     if (isIncomplete(flowType)) {
63394                         seenIncomplete = true;
63395                     }
63396                 }
63397                 if (bypassFlow) {
63398                     var flowType = getTypeAtFlowNode(bypassFlow);
63399                     var type = getTypeFromFlowType(flowType);
63400                     // If the bypass flow contributes a type we haven't seen yet and the switch statement
63401                     // isn't exhaustive, process the bypass flow type. Since exhaustiveness checks increase
63402                     // the risk of circularities, we only want to perform them when they make a difference.
63403                     if (!ts.contains(antecedentTypes, type) && !isExhaustiveSwitchStatement(bypassFlow.switchStatement)) {
63404                         if (type === declaredType && declaredType === initialType) {
63405                             return type;
63406                         }
63407                         antecedentTypes.push(type);
63408                         if (!isTypeSubsetOf(type, declaredType)) {
63409                             subtypeReduction = true;
63410                         }
63411                         if (isIncomplete(flowType)) {
63412                             seenIncomplete = true;
63413                         }
63414                     }
63415                 }
63416                 return createFlowType(getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */), seenIncomplete);
63417             }
63418             function getTypeAtFlowLoopLabel(flow) {
63419                 // If we have previously computed the control flow type for the reference at
63420                 // this flow loop junction, return the cached type.
63421                 var id = getFlowNodeId(flow);
63422                 var cache = flowLoopCaches[id] || (flowLoopCaches[id] = new ts.Map());
63423                 var key = getOrSetCacheKey();
63424                 if (!key) {
63425                     // No cache key is generated when binding patterns are in unnarrowable situations
63426                     return declaredType;
63427                 }
63428                 var cached = cache.get(key);
63429                 if (cached) {
63430                     return cached;
63431                 }
63432                 // If this flow loop junction and reference are already being processed, return
63433                 // the union of the types computed for each branch so far, marked as incomplete.
63434                 // It is possible to see an empty array in cases where loops are nested and the
63435                 // back edge of the outer loop reaches an inner loop that is already being analyzed.
63436                 // In such cases we restart the analysis of the inner loop, which will then see
63437                 // a non-empty in-process array for the outer loop and eventually terminate because
63438                 // the first antecedent of a loop junction is always the non-looping control flow
63439                 // path that leads to the top.
63440                 for (var i = flowLoopStart; i < flowLoopCount; i++) {
63441                     if (flowLoopNodes[i] === flow && flowLoopKeys[i] === key && flowLoopTypes[i].length) {
63442                         return createFlowType(getUnionOrEvolvingArrayType(flowLoopTypes[i], 1 /* Literal */), /*incomplete*/ true);
63443                     }
63444                 }
63445                 // Add the flow loop junction and reference to the in-process stack and analyze
63446                 // each antecedent code path.
63447                 var antecedentTypes = [];
63448                 var subtypeReduction = false;
63449                 var firstAntecedentType;
63450                 for (var _i = 0, _a = flow.antecedents; _i < _a.length; _i++) {
63451                     var antecedent = _a[_i];
63452                     var flowType = void 0;
63453                     if (!firstAntecedentType) {
63454                         // The first antecedent of a loop junction is always the non-looping control
63455                         // flow path that leads to the top.
63456                         flowType = firstAntecedentType = getTypeAtFlowNode(antecedent);
63457                     }
63458                     else {
63459                         // All but the first antecedent are the looping control flow paths that lead
63460                         // back to the loop junction. We track these on the flow loop stack.
63461                         flowLoopNodes[flowLoopCount] = flow;
63462                         flowLoopKeys[flowLoopCount] = key;
63463                         flowLoopTypes[flowLoopCount] = antecedentTypes;
63464                         flowLoopCount++;
63465                         var saveFlowTypeCache = flowTypeCache;
63466                         flowTypeCache = undefined;
63467                         flowType = getTypeAtFlowNode(antecedent);
63468                         flowTypeCache = saveFlowTypeCache;
63469                         flowLoopCount--;
63470                         // If we see a value appear in the cache it is a sign that control flow analysis
63471                         // was restarted and completed by checkExpressionCached. We can simply pick up
63472                         // the resulting type and bail out.
63473                         var cached_1 = cache.get(key);
63474                         if (cached_1) {
63475                             return cached_1;
63476                         }
63477                     }
63478                     var type = getTypeFromFlowType(flowType);
63479                     ts.pushIfUnique(antecedentTypes, type);
63480                     // If an antecedent type is not a subset of the declared type, we need to perform
63481                     // subtype reduction. This happens when a "foreign" type is injected into the control
63482                     // flow using the instanceof operator or a user defined type predicate.
63483                     if (!isTypeSubsetOf(type, declaredType)) {
63484                         subtypeReduction = true;
63485                     }
63486                     // If the type at a particular antecedent path is the declared type there is no
63487                     // reason to process more antecedents since the only possible outcome is subtypes
63488                     // that will be removed in the final union type anyway.
63489                     if (type === declaredType) {
63490                         break;
63491                     }
63492                 }
63493                 // The result is incomplete if the first antecedent (the non-looping control flow path)
63494                 // is incomplete.
63495                 var result = getUnionOrEvolvingArrayType(antecedentTypes, subtypeReduction ? 2 /* Subtype */ : 1 /* Literal */);
63496                 if (isIncomplete(firstAntecedentType)) {
63497                     return createFlowType(result, /*incomplete*/ true);
63498                 }
63499                 cache.set(key, result);
63500                 return result;
63501             }
63502             function isMatchingReferenceDiscriminant(expr, computedType) {
63503                 var type = declaredType.flags & 1048576 /* Union */ ? declaredType : computedType;
63504                 if (!(type.flags & 1048576 /* Union */) || !ts.isAccessExpression(expr)) {
63505                     return false;
63506                 }
63507                 var name = getAccessedPropertyName(expr);
63508                 if (name === undefined) {
63509                     return false;
63510                 }
63511                 return isMatchingReference(reference, expr.expression) && isDiscriminantProperty(type, name);
63512             }
63513             function narrowTypeByDiscriminant(type, access, narrowType) {
63514                 var propName = getAccessedPropertyName(access);
63515                 if (propName === undefined) {
63516                     return type;
63517                 }
63518                 var propType = getTypeOfPropertyOfType(type, propName);
63519                 if (!propType) {
63520                     return type;
63521                 }
63522                 var narrowedPropType = narrowType(propType);
63523                 return filterType(type, function (t) {
63524                     var discriminantType = getTypeOfPropertyOrIndexSignature(t, propName);
63525                     return !(discriminantType.flags & 131072 /* Never */) && isTypeComparableTo(discriminantType, narrowedPropType);
63526                 });
63527             }
63528             function narrowTypeByTruthiness(type, expr, assumeTrue) {
63529                 if (isMatchingReference(reference, expr)) {
63530                     return getTypeWithFacts(type, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */);
63531                 }
63532                 if (strictNullChecks && assumeTrue && optionalChainContainsReference(expr, reference)) {
63533                     type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
63534                 }
63535                 if (isMatchingReferenceDiscriminant(expr, type)) {
63536                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumeTrue ? 4194304 /* Truthy */ : 8388608 /* Falsy */); });
63537                 }
63538                 return type;
63539             }
63540             function isTypePresencePossible(type, propName, assumeTrue) {
63541                 if (getIndexInfoOfType(type, 0 /* String */)) {
63542                     return true;
63543                 }
63544                 var prop = getPropertyOfType(type, propName);
63545                 if (prop) {
63546                     return prop.flags & 16777216 /* Optional */ ? true : assumeTrue;
63547                 }
63548                 return !assumeTrue;
63549             }
63550             function narrowByInKeyword(type, literal, assumeTrue) {
63551                 if (type.flags & (1048576 /* Union */ | 524288 /* Object */)
63552                     || isThisTypeParameter(type)
63553                     || type.flags & 2097152 /* Intersection */ && ts.every(type.types, function (t) { return t.symbol !== globalThisSymbol; })) {
63554                     var propName_1 = ts.escapeLeadingUnderscores(literal.text);
63555                     return filterType(type, function (t) { return isTypePresencePossible(t, propName_1, assumeTrue); });
63556                 }
63557                 return type;
63558             }
63559             function narrowTypeByBinaryExpression(type, expr, assumeTrue) {
63560                 switch (expr.operatorToken.kind) {
63561                     case 62 /* EqualsToken */:
63562                     case 74 /* BarBarEqualsToken */:
63563                     case 75 /* AmpersandAmpersandEqualsToken */:
63564                     case 76 /* QuestionQuestionEqualsToken */:
63565                         return narrowTypeByTruthiness(narrowType(type, expr.right, assumeTrue), expr.left, assumeTrue);
63566                     case 34 /* EqualsEqualsToken */:
63567                     case 35 /* ExclamationEqualsToken */:
63568                     case 36 /* EqualsEqualsEqualsToken */:
63569                     case 37 /* ExclamationEqualsEqualsToken */:
63570                         var operator_1 = expr.operatorToken.kind;
63571                         var left_1 = getReferenceCandidate(expr.left);
63572                         var right_1 = getReferenceCandidate(expr.right);
63573                         if (left_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(right_1)) {
63574                             return narrowTypeByTypeof(type, left_1, operator_1, right_1, assumeTrue);
63575                         }
63576                         if (right_1.kind === 211 /* TypeOfExpression */ && ts.isStringLiteralLike(left_1)) {
63577                             return narrowTypeByTypeof(type, right_1, operator_1, left_1, assumeTrue);
63578                         }
63579                         if (isMatchingReference(reference, left_1)) {
63580                             return narrowTypeByEquality(type, operator_1, right_1, assumeTrue);
63581                         }
63582                         if (isMatchingReference(reference, right_1)) {
63583                             return narrowTypeByEquality(type, operator_1, left_1, assumeTrue);
63584                         }
63585                         if (strictNullChecks) {
63586                             if (optionalChainContainsReference(left_1, reference)) {
63587                                 type = narrowTypeByOptionalChainContainment(type, operator_1, right_1, assumeTrue);
63588                             }
63589                             else if (optionalChainContainsReference(right_1, reference)) {
63590                                 type = narrowTypeByOptionalChainContainment(type, operator_1, left_1, assumeTrue);
63591                             }
63592                         }
63593                         if (isMatchingReferenceDiscriminant(left_1, type)) {
63594                             return narrowTypeByDiscriminant(type, left_1, function (t) { return narrowTypeByEquality(t, operator_1, right_1, assumeTrue); });
63595                         }
63596                         if (isMatchingReferenceDiscriminant(right_1, type)) {
63597                             return narrowTypeByDiscriminant(type, right_1, function (t) { return narrowTypeByEquality(t, operator_1, left_1, assumeTrue); });
63598                         }
63599                         if (isMatchingConstructorReference(left_1)) {
63600                             return narrowTypeByConstructor(type, operator_1, right_1, assumeTrue);
63601                         }
63602                         if (isMatchingConstructorReference(right_1)) {
63603                             return narrowTypeByConstructor(type, operator_1, left_1, assumeTrue);
63604                         }
63605                         break;
63606                     case 101 /* InstanceOfKeyword */:
63607                         return narrowTypeByInstanceof(type, expr, assumeTrue);
63608                     case 100 /* InKeyword */:
63609                         var target = getReferenceCandidate(expr.right);
63610                         if (ts.isStringLiteralLike(expr.left) && isMatchingReference(reference, target)) {
63611                             return narrowByInKeyword(type, expr.left, assumeTrue);
63612                         }
63613                         break;
63614                     case 27 /* CommaToken */:
63615                         return narrowType(type, expr.right, assumeTrue);
63616                 }
63617                 return type;
63618             }
63619             function narrowTypeByOptionalChainContainment(type, operator, value, assumeTrue) {
63620                 // We are in a branch of obj?.foo === value (or any one of the other equality operators). We narrow obj as follows:
63621                 // When operator is === and type of value excludes undefined, null and undefined is removed from type of obj in true branch.
63622                 // When operator is !== and type of value excludes undefined, null and undefined is removed from type of obj in false branch.
63623                 // When operator is == and type of value excludes null and undefined, null and undefined is removed from type of obj in true branch.
63624                 // When operator is != and type of value excludes null and undefined, null and undefined is removed from type of obj in false branch.
63625                 // When operator is === and type of value is undefined, null and undefined is removed from type of obj in false branch.
63626                 // When operator is !== and type of value is undefined, null and undefined is removed from type of obj in true branch.
63627                 // When operator is == and type of value is null or undefined, null and undefined is removed from type of obj in false branch.
63628                 // When operator is != and type of value is null or undefined, null and undefined is removed from type of obj in true branch.
63629                 var equalsOperator = operator === 34 /* EqualsEqualsToken */ || operator === 36 /* EqualsEqualsEqualsToken */;
63630                 var nullableFlags = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */ ? 98304 /* Nullable */ : 32768 /* Undefined */;
63631                 var valueType = getTypeOfExpression(value);
63632                 // Note that we include any and unknown in the exclusion test because their domain includes null and undefined.
63633                 var removeNullable = equalsOperator !== assumeTrue && everyType(valueType, function (t) { return !!(t.flags & nullableFlags); }) ||
63634                     equalsOperator === assumeTrue && everyType(valueType, function (t) { return !(t.flags & (3 /* AnyOrUnknown */ | nullableFlags)); });
63635                 return removeNullable ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
63636             }
63637             function narrowTypeByEquality(type, operator, value, assumeTrue) {
63638                 if (type.flags & 1 /* Any */) {
63639                     return type;
63640                 }
63641                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
63642                     assumeTrue = !assumeTrue;
63643                 }
63644                 var valueType = getTypeOfExpression(value);
63645                 if ((type.flags & 2 /* Unknown */) && assumeTrue && (operator === 36 /* EqualsEqualsEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */)) {
63646                     if (valueType.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
63647                         return valueType;
63648                     }
63649                     if (valueType.flags & 524288 /* Object */) {
63650                         return nonPrimitiveType;
63651                     }
63652                     return type;
63653                 }
63654                 if (valueType.flags & 98304 /* Nullable */) {
63655                     if (!strictNullChecks) {
63656                         return type;
63657                     }
63658                     var doubleEquals = operator === 34 /* EqualsEqualsToken */ || operator === 35 /* ExclamationEqualsToken */;
63659                     var facts = doubleEquals ?
63660                         assumeTrue ? 262144 /* EQUndefinedOrNull */ : 2097152 /* NEUndefinedOrNull */ :
63661                         valueType.flags & 65536 /* Null */ ?
63662                             assumeTrue ? 131072 /* EQNull */ : 1048576 /* NENull */ :
63663                             assumeTrue ? 65536 /* EQUndefined */ : 524288 /* NEUndefined */;
63664                     return getTypeWithFacts(type, facts);
63665                 }
63666                 if (assumeTrue) {
63667                     var filterFn = operator === 34 /* EqualsEqualsToken */ ?
63668                         (function (t) { return areTypesComparable(t, valueType) || isCoercibleUnderDoubleEquals(t, valueType); }) :
63669                         function (t) { return areTypesComparable(t, valueType); };
63670                     return replacePrimitivesWithLiterals(filterType(type, filterFn), valueType);
63671                 }
63672                 if (isUnitType(valueType)) {
63673                     var regularType_1 = getRegularTypeOfLiteralType(valueType);
63674                     return filterType(type, function (t) { return isUnitType(t) ? !areTypesComparable(t, valueType) : getRegularTypeOfLiteralType(t) !== regularType_1; });
63675                 }
63676                 return type;
63677             }
63678             function narrowTypeByTypeof(type, typeOfExpr, operator, literal, assumeTrue) {
63679                 // We have '==', '!=', '===', or !==' operator with 'typeof xxx' and string literal operands
63680                 if (operator === 35 /* ExclamationEqualsToken */ || operator === 37 /* ExclamationEqualsEqualsToken */) {
63681                     assumeTrue = !assumeTrue;
63682                 }
63683                 var target = getReferenceCandidate(typeOfExpr.expression);
63684                 if (!isMatchingReference(reference, target)) {
63685                     if (strictNullChecks && optionalChainContainsReference(target, reference) && assumeTrue === (literal.text !== "undefined")) {
63686                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
63687                     }
63688                     return type;
63689                 }
63690                 if (type.flags & 1 /* Any */ && literal.text === "function") {
63691                     return type;
63692                 }
63693                 if (assumeTrue && type.flags & 2 /* Unknown */ && literal.text === "object") {
63694                     // The pattern x && typeof x === 'object', where x is of type unknown, narrows x to type object. We don't
63695                     // need to check for the reverse typeof x === 'object' && x since that already narrows correctly.
63696                     if (typeOfExpr.parent.parent.kind === 216 /* BinaryExpression */) {
63697                         var expr = typeOfExpr.parent.parent;
63698                         if (expr.operatorToken.kind === 55 /* AmpersandAmpersandToken */ && expr.right === typeOfExpr.parent && containsTruthyCheck(reference, expr.left)) {
63699                             return nonPrimitiveType;
63700                         }
63701                     }
63702                     return getUnionType([nonPrimitiveType, nullType]);
63703                 }
63704                 var facts = assumeTrue ?
63705                     typeofEQFacts.get(literal.text) || 128 /* TypeofEQHostObject */ :
63706                     typeofNEFacts.get(literal.text) || 32768 /* TypeofNEHostObject */;
63707                 var impliedType = getImpliedTypeFromTypeofGuard(type, literal.text);
63708                 return getTypeWithFacts(assumeTrue && impliedType ? mapType(type, narrowUnionMemberByTypeof(impliedType)) : type, facts);
63709             }
63710             function narrowTypeBySwitchOptionalChainContainment(type, switchStatement, clauseStart, clauseEnd, clauseCheck) {
63711                 var everyClauseChecks = clauseStart !== clauseEnd && ts.every(getSwitchClauseTypes(switchStatement).slice(clauseStart, clauseEnd), clauseCheck);
63712                 return everyClauseChecks ? getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */) : type;
63713             }
63714             function narrowTypeBySwitchOnDiscriminant(type, switchStatement, clauseStart, clauseEnd) {
63715                 // We only narrow if all case expressions specify
63716                 // values with unit types, except for the case where
63717                 // `type` is unknown. In this instance we map object
63718                 // types to the nonPrimitive type and narrow with that.
63719                 var switchTypes = getSwitchClauseTypes(switchStatement);
63720                 if (!switchTypes.length) {
63721                     return type;
63722                 }
63723                 var clauseTypes = switchTypes.slice(clauseStart, clauseEnd);
63724                 var hasDefaultClause = clauseStart === clauseEnd || ts.contains(clauseTypes, neverType);
63725                 if ((type.flags & 2 /* Unknown */) && !hasDefaultClause) {
63726                     var groundClauseTypes = void 0;
63727                     for (var i = 0; i < clauseTypes.length; i += 1) {
63728                         var t = clauseTypes[i];
63729                         if (t.flags & (131068 /* Primitive */ | 67108864 /* NonPrimitive */)) {
63730                             if (groundClauseTypes !== undefined) {
63731                                 groundClauseTypes.push(t);
63732                             }
63733                         }
63734                         else if (t.flags & 524288 /* Object */) {
63735                             if (groundClauseTypes === undefined) {
63736                                 groundClauseTypes = clauseTypes.slice(0, i);
63737                             }
63738                             groundClauseTypes.push(nonPrimitiveType);
63739                         }
63740                         else {
63741                             return type;
63742                         }
63743                     }
63744                     return getUnionType(groundClauseTypes === undefined ? clauseTypes : groundClauseTypes);
63745                 }
63746                 var discriminantType = getUnionType(clauseTypes);
63747                 var caseType = discriminantType.flags & 131072 /* Never */ ? neverType :
63748                     replacePrimitivesWithLiterals(filterType(type, function (t) { return areTypesComparable(discriminantType, t); }), discriminantType);
63749                 if (!hasDefaultClause) {
63750                     return caseType;
63751                 }
63752                 var defaultType = filterType(type, function (t) { return !(isUnitType(t) && ts.contains(switchTypes, getRegularTypeOfLiteralType(t))); });
63753                 return caseType.flags & 131072 /* Never */ ? defaultType : getUnionType([caseType, defaultType]);
63754             }
63755             function getImpliedTypeFromTypeofGuard(type, text) {
63756                 switch (text) {
63757                     case "function":
63758                         return type.flags & 1 /* Any */ ? type : globalFunctionType;
63759                     case "object":
63760                         return type.flags & 2 /* Unknown */ ? getUnionType([nonPrimitiveType, nullType]) : type;
63761                     default:
63762                         return typeofTypesByName.get(text);
63763                 }
63764             }
63765             // When narrowing a union type by a `typeof` guard using type-facts alone, constituent types that are
63766             // super-types of the implied guard will be retained in the final type: this is because type-facts only
63767             // filter. Instead, we would like to replace those union constituents with the more precise type implied by
63768             // the guard. For example: narrowing `{} | undefined` by `"boolean"` should produce the type `boolean`, not
63769             // the filtered type `{}`. For this reason we narrow constituents of the union individually, in addition to
63770             // filtering by type-facts.
63771             function narrowUnionMemberByTypeof(candidate) {
63772                 return function (type) {
63773                     if (isTypeSubtypeOf(type, candidate)) {
63774                         return type;
63775                     }
63776                     if (isTypeSubtypeOf(candidate, type)) {
63777                         return candidate;
63778                     }
63779                     if (type.flags & 465829888 /* Instantiable */) {
63780                         var constraint = getBaseConstraintOfType(type) || anyType;
63781                         if (isTypeSubtypeOf(candidate, constraint)) {
63782                             return getIntersectionType([type, candidate]);
63783                         }
63784                     }
63785                     return type;
63786                 };
63787             }
63788             function narrowBySwitchOnTypeOf(type, switchStatement, clauseStart, clauseEnd) {
63789                 var switchWitnesses = getSwitchClauseTypeOfWitnesses(switchStatement, /*retainDefault*/ true);
63790                 if (!switchWitnesses.length) {
63791                     return type;
63792                 }
63793                 //  Equal start and end denotes implicit fallthrough; undefined marks explicit default clause
63794                 var defaultCaseLocation = ts.findIndex(switchWitnesses, function (elem) { return elem === undefined; });
63795                 var hasDefaultClause = clauseStart === clauseEnd || (defaultCaseLocation >= clauseStart && defaultCaseLocation < clauseEnd);
63796                 var clauseWitnesses;
63797                 var switchFacts;
63798                 if (defaultCaseLocation > -1) {
63799                     // We no longer need the undefined denoting an explicit default case. Remove the undefined and
63800                     // fix-up clauseStart and clauseEnd.  This means that we don't have to worry about undefined in the
63801                     // witness array.
63802                     var witnesses = switchWitnesses.filter(function (witness) { return witness !== undefined; });
63803                     // The adjusted clause start and end after removing the `default` statement.
63804                     var fixedClauseStart = defaultCaseLocation < clauseStart ? clauseStart - 1 : clauseStart;
63805                     var fixedClauseEnd = defaultCaseLocation < clauseEnd ? clauseEnd - 1 : clauseEnd;
63806                     clauseWitnesses = witnesses.slice(fixedClauseStart, fixedClauseEnd);
63807                     switchFacts = getFactsFromTypeofSwitch(fixedClauseStart, fixedClauseEnd, witnesses, hasDefaultClause);
63808                 }
63809                 else {
63810                     clauseWitnesses = switchWitnesses.slice(clauseStart, clauseEnd);
63811                     switchFacts = getFactsFromTypeofSwitch(clauseStart, clauseEnd, switchWitnesses, hasDefaultClause);
63812                 }
63813                 if (hasDefaultClause) {
63814                     return filterType(type, function (t) { return (getTypeFacts(t) & switchFacts) === switchFacts; });
63815                 }
63816                 /*
63817                   The implied type is the raw type suggested by a
63818                   value being caught in this clause.
63819
63820                   When the clause contains a default case we ignore
63821                   the implied type and try to narrow using any facts
63822                   we can learn: see `switchFacts`.
63823
63824                   Example:
63825                   switch (typeof x) {
63826                       case 'number':
63827                       case 'string': break;
63828                       default: break;
63829                       case 'number':
63830                       case 'boolean': break
63831                   }
63832
63833                   In the first clause (case `number` and `string`) the
63834                   implied type is number | string.
63835
63836                   In the default clause we de not compute an implied type.
63837
63838                   In the third clause (case `number` and `boolean`)
63839                   the naive implied type is number | boolean, however
63840                   we use the type facts to narrow the implied type to
63841                   boolean. We know that number cannot be selected
63842                   because it is caught in the first clause.
63843                 */
63844                 var impliedType = getTypeWithFacts(getUnionType(clauseWitnesses.map(function (text) { return getImpliedTypeFromTypeofGuard(type, text) || type; })), switchFacts);
63845                 return getTypeWithFacts(mapType(type, narrowUnionMemberByTypeof(impliedType)), switchFacts);
63846             }
63847             function isMatchingConstructorReference(expr) {
63848                 return (ts.isPropertyAccessExpression(expr) && ts.idText(expr.name) === "constructor" ||
63849                     ts.isElementAccessExpression(expr) && ts.isStringLiteralLike(expr.argumentExpression) && expr.argumentExpression.text === "constructor") &&
63850                     isMatchingReference(reference, expr.expression);
63851             }
63852             function narrowTypeByConstructor(type, operator, identifier, assumeTrue) {
63853                 // Do not narrow when checking inequality.
63854                 if (assumeTrue ? (operator !== 34 /* EqualsEqualsToken */ && operator !== 36 /* EqualsEqualsEqualsToken */) : (operator !== 35 /* ExclamationEqualsToken */ && operator !== 37 /* ExclamationEqualsEqualsToken */)) {
63855                     return type;
63856                 }
63857                 // Get the type of the constructor identifier expression, if it is not a function then do not narrow.
63858                 var identifierType = getTypeOfExpression(identifier);
63859                 if (!isFunctionType(identifierType) && !isConstructorType(identifierType)) {
63860                     return type;
63861                 }
63862                 // Get the prototype property of the type identifier so we can find out its type.
63863                 var prototypeProperty = getPropertyOfType(identifierType, "prototype");
63864                 if (!prototypeProperty) {
63865                     return type;
63866                 }
63867                 // Get the type of the prototype, if it is undefined, or the global `Object` or `Function` types then do not narrow.
63868                 var prototypeType = getTypeOfSymbol(prototypeProperty);
63869                 var candidate = !isTypeAny(prototypeType) ? prototypeType : undefined;
63870                 if (!candidate || candidate === globalObjectType || candidate === globalFunctionType) {
63871                     return type;
63872                 }
63873                 // If the type that is being narrowed is `any` then just return the `candidate` type since every type is a subtype of `any`.
63874                 if (isTypeAny(type)) {
63875                     return candidate;
63876                 }
63877                 // Filter out types that are not considered to be "constructed by" the `candidate` type.
63878                 return filterType(type, function (t) { return isConstructedBy(t, candidate); });
63879                 function isConstructedBy(source, target) {
63880                     // If either the source or target type are a class type then we need to check that they are the same exact type.
63881                     // This is because you may have a class `A` that defines some set of properties, and another class `B`
63882                     // that defines the same set of properties as class `A`, in that case they are structurally the same
63883                     // type, but when you do something like `instanceOfA.constructor === B` it will return false.
63884                     if (source.flags & 524288 /* Object */ && ts.getObjectFlags(source) & 1 /* Class */ ||
63885                         target.flags & 524288 /* Object */ && ts.getObjectFlags(target) & 1 /* Class */) {
63886                         return source.symbol === target.symbol;
63887                     }
63888                     // For all other types just check that the `source` type is a subtype of the `target` type.
63889                     return isTypeSubtypeOf(source, target);
63890                 }
63891             }
63892             function narrowTypeByInstanceof(type, expr, assumeTrue) {
63893                 var left = getReferenceCandidate(expr.left);
63894                 if (!isMatchingReference(reference, left)) {
63895                     if (assumeTrue && strictNullChecks && optionalChainContainsReference(left, reference)) {
63896                         return getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
63897                     }
63898                     return type;
63899                 }
63900                 // Check that right operand is a function type with a prototype property
63901                 var rightType = getTypeOfExpression(expr.right);
63902                 if (!isTypeDerivedFrom(rightType, globalFunctionType)) {
63903                     return type;
63904                 }
63905                 var targetType;
63906                 var prototypeProperty = getPropertyOfType(rightType, "prototype");
63907                 if (prototypeProperty) {
63908                     // Target type is type of the prototype property
63909                     var prototypePropertyType = getTypeOfSymbol(prototypeProperty);
63910                     if (!isTypeAny(prototypePropertyType)) {
63911                         targetType = prototypePropertyType;
63912                     }
63913                 }
63914                 // Don't narrow from 'any' if the target type is exactly 'Object' or 'Function'
63915                 if (isTypeAny(type) && (targetType === globalObjectType || targetType === globalFunctionType)) {
63916                     return type;
63917                 }
63918                 if (!targetType) {
63919                     var constructSignatures = getSignaturesOfType(rightType, 1 /* Construct */);
63920                     targetType = constructSignatures.length ?
63921                         getUnionType(ts.map(constructSignatures, function (signature) { return getReturnTypeOfSignature(getErasedSignature(signature)); })) :
63922                         emptyObjectType;
63923                 }
63924                 // We can't narrow a union based off instanceof without negated types see #31576 for more info
63925                 if (!assumeTrue && rightType.flags & 1048576 /* Union */) {
63926                     var nonConstructorTypeInUnion = ts.find(rightType.types, function (t) { return !isConstructorType(t); });
63927                     if (!nonConstructorTypeInUnion)
63928                         return type;
63929                 }
63930                 return getNarrowedType(type, targetType, assumeTrue, isTypeDerivedFrom);
63931             }
63932             function getNarrowedType(type, candidate, assumeTrue, isRelated) {
63933                 if (!assumeTrue) {
63934                     return filterType(type, function (t) { return !isRelated(t, candidate); });
63935                 }
63936                 // If the current type is a union type, remove all constituents that couldn't be instances of
63937                 // the candidate type. If one or more constituents remain, return a union of those.
63938                 if (type.flags & 1048576 /* Union */) {
63939                     var assignableType = filterType(type, function (t) { return isRelated(t, candidate); });
63940                     if (!(assignableType.flags & 131072 /* Never */)) {
63941                         return assignableType;
63942                     }
63943                 }
63944                 // If the candidate type is a subtype of the target type, narrow to the candidate type,
63945                 // if the target type is a subtype of the candidate type, narrow to the target type,
63946                 // otherwise, narrow to an intersection of the two types.
63947                 return isTypeSubtypeOf(candidate, type) ? candidate : isTypeSubtypeOf(type, candidate) ? type : getIntersectionType([type, candidate]);
63948             }
63949             function narrowTypeByCallExpression(type, callExpression, assumeTrue) {
63950                 if (hasMatchingArgument(callExpression, reference)) {
63951                     var signature = assumeTrue || !ts.isCallChain(callExpression) ? getEffectsSignature(callExpression) : undefined;
63952                     var predicate = signature && getTypePredicateOfSignature(signature);
63953                     if (predicate && (predicate.kind === 0 /* This */ || predicate.kind === 1 /* Identifier */)) {
63954                         return narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue);
63955                     }
63956                 }
63957                 return type;
63958             }
63959             function narrowTypeByTypePredicate(type, predicate, callExpression, assumeTrue) {
63960                 // Don't narrow from 'any' if the predicate type is exactly 'Object' or 'Function'
63961                 if (predicate.type && !(isTypeAny(type) && (predicate.type === globalObjectType || predicate.type === globalFunctionType))) {
63962                     var predicateArgument = getTypePredicateArgument(predicate, callExpression);
63963                     if (predicateArgument) {
63964                         if (isMatchingReference(reference, predicateArgument)) {
63965                             return getNarrowedType(type, predicate.type, assumeTrue, isTypeSubtypeOf);
63966                         }
63967                         if (strictNullChecks && assumeTrue && optionalChainContainsReference(predicateArgument, reference) &&
63968                             !(getTypeFacts(predicate.type) & 65536 /* EQUndefined */)) {
63969                             type = getTypeWithFacts(type, 2097152 /* NEUndefinedOrNull */);
63970                         }
63971                         if (isMatchingReferenceDiscriminant(predicateArgument, type)) {
63972                             return narrowTypeByDiscriminant(type, predicateArgument, function (t) { return getNarrowedType(t, predicate.type, assumeTrue, isTypeSubtypeOf); });
63973                         }
63974                     }
63975                 }
63976                 return type;
63977             }
63978             // Narrow the given type based on the given expression having the assumed boolean value. The returned type
63979             // will be a subtype or the same type as the argument.
63980             function narrowType(type, expr, assumeTrue) {
63981                 // for `a?.b`, we emulate a synthetic `a !== null && a !== undefined` condition for `a`
63982                 if (ts.isExpressionOfOptionalChainRoot(expr) ||
63983                     ts.isBinaryExpression(expr.parent) && expr.parent.operatorToken.kind === 60 /* QuestionQuestionToken */ && expr.parent.left === expr) {
63984                     return narrowTypeByOptionality(type, expr, assumeTrue);
63985                 }
63986                 switch (expr.kind) {
63987                     case 78 /* Identifier */:
63988                     case 107 /* ThisKeyword */:
63989                     case 105 /* SuperKeyword */:
63990                     case 201 /* PropertyAccessExpression */:
63991                     case 202 /* ElementAccessExpression */:
63992                         return narrowTypeByTruthiness(type, expr, assumeTrue);
63993                     case 203 /* CallExpression */:
63994                         return narrowTypeByCallExpression(type, expr, assumeTrue);
63995                     case 207 /* ParenthesizedExpression */:
63996                     case 225 /* NonNullExpression */:
63997                         return narrowType(type, expr.expression, assumeTrue);
63998                     case 216 /* BinaryExpression */:
63999                         return narrowTypeByBinaryExpression(type, expr, assumeTrue);
64000                     case 214 /* PrefixUnaryExpression */:
64001                         if (expr.operator === 53 /* ExclamationToken */) {
64002                             return narrowType(type, expr.operand, !assumeTrue);
64003                         }
64004                         break;
64005                 }
64006                 return type;
64007             }
64008             function narrowTypeByOptionality(type, expr, assumePresent) {
64009                 if (isMatchingReference(reference, expr)) {
64010                     return getTypeWithFacts(type, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */);
64011                 }
64012                 if (isMatchingReferenceDiscriminant(expr, type)) {
64013                     return narrowTypeByDiscriminant(type, expr, function (t) { return getTypeWithFacts(t, assumePresent ? 2097152 /* NEUndefinedOrNull */ : 262144 /* EQUndefinedOrNull */); });
64014                 }
64015                 return type;
64016             }
64017         }
64018         function getTypeOfSymbolAtLocation(symbol, location) {
64019             symbol = symbol.exportSymbol || symbol;
64020             // If we have an identifier or a property access at the given location, if the location is
64021             // an dotted name expression, and if the location is not an assignment target, obtain the type
64022             // of the expression (which will reflect control flow analysis). If the expression indeed
64023             // resolved to the given symbol, return the narrowed type.
64024             if (location.kind === 78 /* Identifier */) {
64025                 if (ts.isRightSideOfQualifiedNameOrPropertyAccess(location)) {
64026                     location = location.parent;
64027                 }
64028                 if (ts.isExpressionNode(location) && !ts.isAssignmentTarget(location)) {
64029                     var type = getTypeOfExpression(location);
64030                     if (getExportSymbolOfValueSymbolIfExported(getNodeLinks(location).resolvedSymbol) === symbol) {
64031                         return type;
64032                     }
64033                 }
64034             }
64035             // The location isn't a reference to the given symbol, meaning we're being asked
64036             // a hypothetical question of what type the symbol would have if there was a reference
64037             // to it at the given location. Since we have no control flow information for the
64038             // hypothetical reference (control flow information is created and attached by the
64039             // binder), we simply return the declared type of the symbol.
64040             return getTypeOfSymbol(symbol);
64041         }
64042         function getControlFlowContainer(node) {
64043             return ts.findAncestor(node.parent, function (node) {
64044                 return ts.isFunctionLike(node) && !ts.getImmediatelyInvokedFunctionExpression(node) ||
64045                     node.kind === 257 /* ModuleBlock */ ||
64046                     node.kind === 297 /* SourceFile */ ||
64047                     node.kind === 163 /* PropertyDeclaration */;
64048             });
64049         }
64050         // Check if a parameter is assigned anywhere within its declaring function.
64051         function isParameterAssigned(symbol) {
64052             var func = ts.getRootDeclaration(symbol.valueDeclaration).parent;
64053             var links = getNodeLinks(func);
64054             if (!(links.flags & 8388608 /* AssignmentsMarked */)) {
64055                 links.flags |= 8388608 /* AssignmentsMarked */;
64056                 if (!hasParentWithAssignmentsMarked(func)) {
64057                     markParameterAssignments(func);
64058                 }
64059             }
64060             return symbol.isAssigned || false;
64061         }
64062         function hasParentWithAssignmentsMarked(node) {
64063             return !!ts.findAncestor(node.parent, function (node) { return ts.isFunctionLike(node) && !!(getNodeLinks(node).flags & 8388608 /* AssignmentsMarked */); });
64064         }
64065         function markParameterAssignments(node) {
64066             if (node.kind === 78 /* Identifier */) {
64067                 if (ts.isAssignmentTarget(node)) {
64068                     var symbol = getResolvedSymbol(node);
64069                     if (symbol.valueDeclaration && ts.getRootDeclaration(symbol.valueDeclaration).kind === 160 /* Parameter */) {
64070                         symbol.isAssigned = true;
64071                     }
64072                 }
64073             }
64074             else {
64075                 ts.forEachChild(node, markParameterAssignments);
64076             }
64077         }
64078         function isConstVariable(symbol) {
64079             return symbol.flags & 3 /* Variable */ && (getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */) !== 0 && getTypeOfSymbol(symbol) !== autoArrayType;
64080         }
64081         /** remove undefined from the annotated type of a parameter when there is an initializer (that doesn't include undefined) */
64082         function removeOptionalityFromDeclaredType(declaredType, declaration) {
64083             if (pushTypeResolution(declaration.symbol, 2 /* DeclaredType */)) {
64084                 var annotationIncludesUndefined = strictNullChecks &&
64085                     declaration.kind === 160 /* Parameter */ &&
64086                     declaration.initializer &&
64087                     getFalsyFlags(declaredType) & 32768 /* Undefined */ &&
64088                     !(getFalsyFlags(checkExpression(declaration.initializer)) & 32768 /* Undefined */);
64089                 popTypeResolution();
64090                 return annotationIncludesUndefined ? getTypeWithFacts(declaredType, 524288 /* NEUndefined */) : declaredType;
64091             }
64092             else {
64093                 reportCircularityError(declaration.symbol);
64094                 return declaredType;
64095             }
64096         }
64097         function isConstraintPosition(node) {
64098             var parent = node.parent;
64099             return parent.kind === 201 /* PropertyAccessExpression */ ||
64100                 parent.kind === 203 /* CallExpression */ && parent.expression === node ||
64101                 parent.kind === 202 /* ElementAccessExpression */ && parent.expression === node ||
64102                 parent.kind === 198 /* BindingElement */ && parent.name === node && !!parent.initializer;
64103         }
64104         function typeHasNullableConstraint(type) {
64105             return type.flags & 58982400 /* InstantiableNonPrimitive */ && maybeTypeOfKind(getBaseConstraintOfType(type) || unknownType, 98304 /* Nullable */);
64106         }
64107         function getConstraintForLocation(type, node) {
64108             // When a node is the left hand expression of a property access, element access, or call expression,
64109             // and the type of the node includes type variables with constraints that are nullable, we fetch the
64110             // apparent type of the node *before* performing control flow analysis such that narrowings apply to
64111             // the constraint type.
64112             if (type && isConstraintPosition(node) && forEachType(type, typeHasNullableConstraint)) {
64113                 return mapType(getWidenedType(type), getBaseConstraintOrType);
64114             }
64115             return type;
64116         }
64117         function isExportOrExportExpression(location) {
64118             return !!ts.findAncestor(location, function (e) { return e.parent && ts.isExportAssignment(e.parent) && e.parent.expression === e && ts.isEntityNameExpression(e); });
64119         }
64120         function markAliasReferenced(symbol, location) {
64121             if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !isInTypeQuery(location) && !getTypeOnlyAliasDeclaration(symbol)) {
64122                 if (compilerOptions.preserveConstEnums && isExportOrExportExpression(location) || !isConstEnumOrConstEnumOnlyModule(resolveAlias(symbol))) {
64123                     markAliasSymbolAsReferenced(symbol);
64124                 }
64125                 else {
64126                     markConstEnumAliasAsReferenced(symbol);
64127                 }
64128             }
64129         }
64130         function checkIdentifier(node) {
64131             var symbol = getResolvedSymbol(node);
64132             if (symbol === unknownSymbol) {
64133                 return errorType;
64134             }
64135             // As noted in ECMAScript 6 language spec, arrow functions never have an arguments objects.
64136             // Although in down-level emit of arrow function, we emit it using function expression which means that
64137             // arguments objects will be bound to the inner object; emitting arrow function natively in ES6, arguments objects
64138             // will be bound to non-arrow function that contain this arrow function. This results in inconsistent behavior.
64139             // To avoid that we will give an error to users if they use arguments objects in arrow function so that they
64140             // can explicitly bound arguments objects
64141             if (symbol === argumentsSymbol) {
64142                 var container = ts.getContainingFunction(node);
64143                 if (languageVersion < 2 /* ES2015 */) {
64144                     if (container.kind === 209 /* ArrowFunction */) {
64145                         error(node, ts.Diagnostics.The_arguments_object_cannot_be_referenced_in_an_arrow_function_in_ES3_and_ES5_Consider_using_a_standard_function_expression);
64146                     }
64147                     else if (ts.hasSyntacticModifier(container, 256 /* Async */)) {
64148                         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);
64149                     }
64150                 }
64151                 getNodeLinks(container).flags |= 8192 /* CaptureArguments */;
64152                 return getTypeOfSymbol(symbol);
64153             }
64154             // We should only mark aliases as referenced if there isn't a local value declaration
64155             // for the symbol. Also, don't mark any property access expression LHS - checkPropertyAccessExpression will handle that
64156             if (!(node.parent && ts.isPropertyAccessExpression(node.parent) && node.parent.expression === node)) {
64157                 markAliasReferenced(symbol, node);
64158             }
64159             var localOrExportSymbol = getExportSymbolOfValueSymbolIfExported(symbol);
64160             var sourceSymbol = localOrExportSymbol.flags & 2097152 /* Alias */ ? resolveAlias(localOrExportSymbol) : localOrExportSymbol;
64161             if (getDeclarationNodeFlagsFromSymbol(sourceSymbol) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node.parent, sourceSymbol)) {
64162                 errorOrSuggestion(/* isError */ false, node, ts.Diagnostics._0_is_deprecated, node.escapedText);
64163             }
64164             var declaration = localOrExportSymbol.valueDeclaration;
64165             if (localOrExportSymbol.flags & 32 /* Class */) {
64166                 // Due to the emit for class decorators, any reference to the class from inside of the class body
64167                 // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
64168                 // behavior of class names in ES6.
64169                 if (declaration.kind === 252 /* ClassDeclaration */
64170                     && ts.nodeIsDecorated(declaration)) {
64171                     var container = ts.getContainingClass(node);
64172                     while (container !== undefined) {
64173                         if (container === declaration && container.name !== node) {
64174                             getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
64175                             getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
64176                             break;
64177                         }
64178                         container = ts.getContainingClass(container);
64179                     }
64180                 }
64181                 else if (declaration.kind === 221 /* ClassExpression */) {
64182                     // When we emit a class expression with static members that contain a reference
64183                     // to the constructor in the initializer, we will need to substitute that
64184                     // binding with an alias as the class name is not in scope.
64185                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
64186                     while (container.kind !== 297 /* SourceFile */) {
64187                         if (container.parent === declaration) {
64188                             if (container.kind === 163 /* PropertyDeclaration */ && ts.hasSyntacticModifier(container, 32 /* Static */)) {
64189                                 getNodeLinks(declaration).flags |= 16777216 /* ClassWithConstructorReference */;
64190                                 getNodeLinks(node).flags |= 33554432 /* ConstructorReferenceInClass */;
64191                             }
64192                             break;
64193                         }
64194                         container = ts.getThisContainer(container, /*includeArrowFunctions*/ false);
64195                     }
64196                 }
64197             }
64198             checkNestedBlockScopedBinding(node, symbol);
64199             var type = getConstraintForLocation(getTypeOfSymbol(localOrExportSymbol), node);
64200             var assignmentKind = ts.getAssignmentTargetKind(node);
64201             if (assignmentKind) {
64202                 if (!(localOrExportSymbol.flags & 3 /* Variable */) &&
64203                     !(ts.isInJSFile(node) && localOrExportSymbol.flags & 512 /* ValueModule */)) {
64204                     error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_not_a_variable, symbolToString(symbol));
64205                     return errorType;
64206                 }
64207                 if (isReadonlySymbol(localOrExportSymbol)) {
64208                     if (localOrExportSymbol.flags & 3 /* Variable */) {
64209                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_constant, symbolToString(symbol));
64210                     }
64211                     else {
64212                         error(node, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, symbolToString(symbol));
64213                     }
64214                     return errorType;
64215                 }
64216             }
64217             var isAlias = localOrExportSymbol.flags & 2097152 /* Alias */;
64218             // We only narrow variables and parameters occurring in a non-assignment position. For all other
64219             // entities we simply return the declared type.
64220             if (localOrExportSymbol.flags & 3 /* Variable */) {
64221                 if (assignmentKind === 1 /* Definite */) {
64222                     return type;
64223                 }
64224             }
64225             else if (isAlias) {
64226                 declaration = ts.find(symbol.declarations, isSomeImportDeclaration);
64227             }
64228             else {
64229                 return type;
64230             }
64231             if (!declaration) {
64232                 return type;
64233             }
64234             // The declaration container is the innermost function that encloses the declaration of the variable
64235             // or parameter. The flow container is the innermost function starting with which we analyze the control
64236             // flow graph to determine the control flow based type.
64237             var isParameter = ts.getRootDeclaration(declaration).kind === 160 /* Parameter */;
64238             var declarationContainer = getControlFlowContainer(declaration);
64239             var flowContainer = getControlFlowContainer(node);
64240             var isOuterVariable = flowContainer !== declarationContainer;
64241             var isSpreadDestructuringAssignmentTarget = node.parent && node.parent.parent && ts.isSpreadAssignment(node.parent) && isDestructuringAssignmentTarget(node.parent.parent);
64242             var isModuleExports = symbol.flags & 134217728 /* ModuleExports */;
64243             // When the control flow originates in a function expression or arrow function and we are referencing
64244             // a const variable or parameter from an outer function, we extend the origin of the control flow
64245             // analysis to include the immediately enclosing function.
64246             while (flowContainer !== declarationContainer && (flowContainer.kind === 208 /* FunctionExpression */ ||
64247                 flowContainer.kind === 209 /* ArrowFunction */ || ts.isObjectLiteralOrClassExpressionMethod(flowContainer)) &&
64248                 (isConstVariable(localOrExportSymbol) || isParameter && !isParameterAssigned(localOrExportSymbol))) {
64249                 flowContainer = getControlFlowContainer(flowContainer);
64250             }
64251             // We only look for uninitialized variables in strict null checking mode, and only when we can analyze
64252             // the entire control flow graph from the variable's declaration (i.e. when the flow container and
64253             // declaration container are the same).
64254             var assumeInitialized = isParameter || isAlias || isOuterVariable || isSpreadDestructuringAssignmentTarget || isModuleExports || ts.isBindingElement(declaration) ||
64255                 type !== autoType && type !== autoArrayType && (!strictNullChecks || (type.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */)) !== 0 ||
64256                     isInTypeQuery(node) || node.parent.kind === 270 /* ExportSpecifier */) ||
64257                 node.parent.kind === 225 /* NonNullExpression */ ||
64258                 declaration.kind === 249 /* VariableDeclaration */ && declaration.exclamationToken ||
64259                 declaration.flags & 8388608 /* Ambient */;
64260             var initialType = assumeInitialized ? (isParameter ? removeOptionalityFromDeclaredType(type, declaration) : type) :
64261                 type === autoType || type === autoArrayType ? undefinedType :
64262                     getOptionalType(type);
64263             var flowType = getFlowTypeOfReference(node, type, initialType, flowContainer, !assumeInitialized);
64264             // A variable is considered uninitialized when it is possible to analyze the entire control flow graph
64265             // from declaration to use, and when the variable's declared type doesn't include undefined but the
64266             // control flow based type does include undefined.
64267             if (!isEvolvingArrayOperationTarget(node) && (type === autoType || type === autoArrayType)) {
64268                 if (flowType === autoType || flowType === autoArrayType) {
64269                     if (noImplicitAny) {
64270                         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));
64271                         error(node, ts.Diagnostics.Variable_0_implicitly_has_an_1_type, symbolToString(symbol), typeToString(flowType));
64272                     }
64273                     return convertAutoToAny(flowType);
64274                 }
64275             }
64276             else if (!assumeInitialized && !(getFalsyFlags(type) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
64277                 error(node, ts.Diagnostics.Variable_0_is_used_before_being_assigned, symbolToString(symbol));
64278                 // Return the declared type to reduce follow-on errors
64279                 return type;
64280             }
64281             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
64282         }
64283         function isInsideFunction(node, threshold) {
64284             return !!ts.findAncestor(node, function (n) { return n === threshold ? "quit" : ts.isFunctionLike(n); });
64285         }
64286         function getPartOfForStatementContainingNode(node, container) {
64287             return ts.findAncestor(node, function (n) { return n === container ? "quit" : n === container.initializer || n === container.condition || n === container.incrementor || n === container.statement; });
64288         }
64289         function checkNestedBlockScopedBinding(node, symbol) {
64290             if (languageVersion >= 2 /* ES2015 */ ||
64291                 (symbol.flags & (2 /* BlockScopedVariable */ | 32 /* Class */)) === 0 ||
64292                 ts.isSourceFile(symbol.valueDeclaration) ||
64293                 symbol.valueDeclaration.parent.kind === 287 /* CatchClause */) {
64294                 return;
64295             }
64296             // 1. walk from the use site up to the declaration and check
64297             // if there is anything function like between declaration and use-site (is binding/class is captured in function).
64298             // 2. walk from the declaration up to the boundary of lexical environment and check
64299             // if there is an iteration statement in between declaration and boundary (is binding/class declared inside iteration statement)
64300             var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
64301             var usedInFunction = isInsideFunction(node.parent, container);
64302             var current = container;
64303             var containedInIterationStatement = false;
64304             while (current && !ts.nodeStartsNewLexicalEnvironment(current)) {
64305                 if (ts.isIterationStatement(current, /*lookInLabeledStatements*/ false)) {
64306                     containedInIterationStatement = true;
64307                     break;
64308                 }
64309                 current = current.parent;
64310             }
64311             if (containedInIterationStatement) {
64312                 if (usedInFunction) {
64313                     // mark iteration statement as containing block-scoped binding captured in some function
64314                     var capturesBlockScopeBindingInLoopBody = true;
64315                     if (ts.isForStatement(container)) {
64316                         var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */);
64317                         if (varDeclList && varDeclList.parent === container) {
64318                             var part = getPartOfForStatementContainingNode(node.parent, container);
64319                             if (part) {
64320                                 var links = getNodeLinks(part);
64321                                 links.flags |= 131072 /* ContainsCapturedBlockScopeBinding */;
64322                                 var capturedBindings = links.capturedBlockScopeBindings || (links.capturedBlockScopeBindings = []);
64323                                 ts.pushIfUnique(capturedBindings, symbol);
64324                                 if (part === container.initializer) {
64325                                     capturesBlockScopeBindingInLoopBody = false; // Initializer is outside of loop body
64326                                 }
64327                             }
64328                         }
64329                     }
64330                     if (capturesBlockScopeBindingInLoopBody) {
64331                         getNodeLinks(current).flags |= 65536 /* LoopWithCapturedBlockScopedBinding */;
64332                     }
64333                 }
64334                 // mark variables that are declared in loop initializer and reassigned inside the body of ForStatement.
64335                 // if body of ForStatement will be converted to function then we'll need a extra machinery to propagate reassigned values back.
64336                 if (ts.isForStatement(container)) {
64337                     var varDeclList = ts.getAncestor(symbol.valueDeclaration, 250 /* VariableDeclarationList */);
64338                     if (varDeclList && varDeclList.parent === container && isAssignedInBodyOfForStatement(node, container)) {
64339                         getNodeLinks(symbol.valueDeclaration).flags |= 4194304 /* NeedsLoopOutParameter */;
64340                     }
64341                 }
64342                 // set 'declared inside loop' bit on the block-scoped binding
64343                 getNodeLinks(symbol.valueDeclaration).flags |= 524288 /* BlockScopedBindingInLoop */;
64344             }
64345             if (usedInFunction) {
64346                 getNodeLinks(symbol.valueDeclaration).flags |= 262144 /* CapturedBlockScopedBinding */;
64347             }
64348         }
64349         function isBindingCapturedByNode(node, decl) {
64350             var links = getNodeLinks(node);
64351             return !!links && ts.contains(links.capturedBlockScopeBindings, getSymbolOfNode(decl));
64352         }
64353         function isAssignedInBodyOfForStatement(node, container) {
64354             // skip parenthesized nodes
64355             var current = node;
64356             while (current.parent.kind === 207 /* ParenthesizedExpression */) {
64357                 current = current.parent;
64358             }
64359             // check if node is used as LHS in some assignment expression
64360             var isAssigned = false;
64361             if (ts.isAssignmentTarget(current)) {
64362                 isAssigned = true;
64363             }
64364             else if ((current.parent.kind === 214 /* PrefixUnaryExpression */ || current.parent.kind === 215 /* PostfixUnaryExpression */)) {
64365                 var expr = current.parent;
64366                 isAssigned = expr.operator === 45 /* PlusPlusToken */ || expr.operator === 46 /* MinusMinusToken */;
64367             }
64368             if (!isAssigned) {
64369                 return false;
64370             }
64371             // at this point we know that node is the target of assignment
64372             // now check that modification happens inside the statement part of the ForStatement
64373             return !!ts.findAncestor(current, function (n) { return n === container ? "quit" : n === container.statement; });
64374         }
64375         function captureLexicalThis(node, container) {
64376             getNodeLinks(node).flags |= 2 /* LexicalThis */;
64377             if (container.kind === 163 /* PropertyDeclaration */ || container.kind === 166 /* Constructor */) {
64378                 var classNode = container.parent;
64379                 getNodeLinks(classNode).flags |= 4 /* CaptureThis */;
64380             }
64381             else {
64382                 getNodeLinks(container).flags |= 4 /* CaptureThis */;
64383             }
64384         }
64385         function findFirstSuperCall(node) {
64386             return ts.isSuperCall(node) ? node :
64387                 ts.isFunctionLike(node) ? undefined :
64388                     ts.forEachChild(node, findFirstSuperCall);
64389         }
64390         /**
64391          * Check if the given class-declaration extends null then return true.
64392          * Otherwise, return false
64393          * @param classDecl a class declaration to check if it extends null
64394          */
64395         function classDeclarationExtendsNull(classDecl) {
64396             var classSymbol = getSymbolOfNode(classDecl);
64397             var classInstanceType = getDeclaredTypeOfSymbol(classSymbol);
64398             var baseConstructorType = getBaseConstructorTypeOfClass(classInstanceType);
64399             return baseConstructorType === nullWideningType;
64400         }
64401         function checkThisBeforeSuper(node, container, diagnosticMessage) {
64402             var containingClassDecl = container.parent;
64403             var baseTypeNode = ts.getClassExtendsHeritageElement(containingClassDecl);
64404             // If a containing class does not have extends clause or the class extends null
64405             // skip checking whether super statement is called before "this" accessing.
64406             if (baseTypeNode && !classDeclarationExtendsNull(containingClassDecl)) {
64407                 if (node.flowNode && !isPostSuperFlowNode(node.flowNode, /*noCacheCheck*/ false)) {
64408                     error(node, diagnosticMessage);
64409                 }
64410             }
64411         }
64412         function checkThisExpression(node) {
64413             // Stop at the first arrow function so that we can
64414             // tell whether 'this' needs to be captured.
64415             var container = ts.getThisContainer(node, /* includeArrowFunctions */ true);
64416             var capturedByArrowFunction = false;
64417             if (container.kind === 166 /* Constructor */) {
64418                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_this_in_the_constructor_of_a_derived_class);
64419             }
64420             // Now skip arrow functions to get the "real" owner of 'this'.
64421             if (container.kind === 209 /* ArrowFunction */) {
64422                 container = ts.getThisContainer(container, /* includeArrowFunctions */ false);
64423                 capturedByArrowFunction = true;
64424             }
64425             switch (container.kind) {
64426                 case 256 /* ModuleDeclaration */:
64427                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_module_or_namespace_body);
64428                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
64429                     break;
64430                 case 255 /* EnumDeclaration */:
64431                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_current_location);
64432                     // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
64433                     break;
64434                 case 166 /* Constructor */:
64435                     if (isInConstructorArgumentInitializer(node, container)) {
64436                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_constructor_arguments);
64437                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
64438                     }
64439                     break;
64440                 case 163 /* PropertyDeclaration */:
64441                 case 162 /* PropertySignature */:
64442                     if (ts.hasSyntacticModifier(container, 32 /* Static */) && !(compilerOptions.target === 99 /* ESNext */ && compilerOptions.useDefineForClassFields)) {
64443                         error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_static_property_initializer);
64444                         // do not return here so in case if lexical this is captured - it will be reflected in flags on NodeLinks
64445                     }
64446                     break;
64447                 case 158 /* ComputedPropertyName */:
64448                     error(node, ts.Diagnostics.this_cannot_be_referenced_in_a_computed_property_name);
64449                     break;
64450             }
64451             // When targeting es6, mark that we'll need to capture `this` in its lexically bound scope.
64452             if (capturedByArrowFunction && languageVersion < 2 /* ES2015 */) {
64453                 captureLexicalThis(node, container);
64454             }
64455             var type = tryGetThisTypeAt(node, /*includeGlobalThis*/ true, container);
64456             if (noImplicitThis) {
64457                 var globalThisType_1 = getTypeOfSymbol(globalThisSymbol);
64458                 if (type === globalThisType_1 && capturedByArrowFunction) {
64459                     error(node, ts.Diagnostics.The_containing_arrow_function_captures_the_global_value_of_this);
64460                 }
64461                 else if (!type) {
64462                     // With noImplicitThis, functions may not reference 'this' if it has type 'any'
64463                     var diag = error(node, ts.Diagnostics.this_implicitly_has_type_any_because_it_does_not_have_a_type_annotation);
64464                     if (!ts.isSourceFile(container)) {
64465                         var outsideThis = tryGetThisTypeAt(container);
64466                         if (outsideThis && outsideThis !== globalThisType_1) {
64467                             ts.addRelatedInfo(diag, ts.createDiagnosticForNode(container, ts.Diagnostics.An_outer_value_of_this_is_shadowed_by_this_container));
64468                         }
64469                     }
64470                 }
64471             }
64472             return type || anyType;
64473         }
64474         function tryGetThisTypeAt(node, includeGlobalThis, container) {
64475             if (includeGlobalThis === void 0) { includeGlobalThis = true; }
64476             if (container === void 0) { container = ts.getThisContainer(node, /*includeArrowFunctions*/ false); }
64477             var isInJS = ts.isInJSFile(node);
64478             if (ts.isFunctionLike(container) &&
64479                 (!isInParameterInitializerBeforeContainingFunction(node) || ts.getThisParameter(container))) {
64480                 var thisType = getThisTypeOfDeclaration(container) || isInJS && getTypeForThisExpressionFromJSDoc(container);
64481                 // Note: a parameter initializer should refer to class-this unless function-this is explicitly annotated.
64482                 // If this is a function in a JS file, it might be a class method.
64483                 if (!thisType) {
64484                     var className = getClassNameFromPrototypeMethod(container);
64485                     if (isInJS && className) {
64486                         var classSymbol = checkExpression(className).symbol;
64487                         if (classSymbol && classSymbol.members && (classSymbol.flags & 16 /* Function */)) {
64488                             thisType = getDeclaredTypeOfSymbol(classSymbol).thisType;
64489                         }
64490                     }
64491                     else if (isJSConstructor(container)) {
64492                         thisType = getDeclaredTypeOfSymbol(getMergedSymbol(container.symbol)).thisType;
64493                     }
64494                     thisType || (thisType = getContextualThisParameterType(container));
64495                 }
64496                 if (thisType) {
64497                     return getFlowTypeOfReference(node, thisType);
64498                 }
64499             }
64500             if (ts.isClassLike(container.parent)) {
64501                 var symbol = getSymbolOfNode(container.parent);
64502                 var type = ts.hasSyntacticModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
64503                 return getFlowTypeOfReference(node, type);
64504             }
64505             if (ts.isSourceFile(container)) {
64506                 // look up in the source file's locals or exports
64507                 if (container.commonJsModuleIndicator) {
64508                     var fileSymbol = getSymbolOfNode(container);
64509                     return fileSymbol && getTypeOfSymbol(fileSymbol);
64510                 }
64511                 else if (container.externalModuleIndicator) {
64512                     // TODO: Maybe issue a better error than 'object is possibly undefined'
64513                     return undefinedType;
64514                 }
64515                 else if (includeGlobalThis) {
64516                     return getTypeOfSymbol(globalThisSymbol);
64517                 }
64518             }
64519         }
64520         function getExplicitThisType(node) {
64521             var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
64522             if (ts.isFunctionLike(container)) {
64523                 var signature = getSignatureFromDeclaration(container);
64524                 if (signature.thisParameter) {
64525                     return getExplicitTypeOfSymbol(signature.thisParameter);
64526                 }
64527             }
64528             if (ts.isClassLike(container.parent)) {
64529                 var symbol = getSymbolOfNode(container.parent);
64530                 return ts.hasSyntacticModifier(container, 32 /* Static */) ? getTypeOfSymbol(symbol) : getDeclaredTypeOfSymbol(symbol).thisType;
64531             }
64532         }
64533         function getClassNameFromPrototypeMethod(container) {
64534             // Check if it's the RHS of a x.prototype.y = function [name]() { .... }
64535             if (container.kind === 208 /* FunctionExpression */ &&
64536                 ts.isBinaryExpression(container.parent) &&
64537                 ts.getAssignmentDeclarationKind(container.parent) === 3 /* PrototypeProperty */) {
64538                 // Get the 'x' of 'x.prototype.y = container'
64539                 return container.parent // x.prototype.y = container
64540                     .left // x.prototype.y
64541                     .expression // x.prototype
64542                     .expression; // x
64543             }
64544             // x.prototype = { method() { } }
64545             else if (container.kind === 165 /* MethodDeclaration */ &&
64546                 container.parent.kind === 200 /* ObjectLiteralExpression */ &&
64547                 ts.isBinaryExpression(container.parent.parent) &&
64548                 ts.getAssignmentDeclarationKind(container.parent.parent) === 6 /* Prototype */) {
64549                 return container.parent.parent.left.expression;
64550             }
64551             // x.prototype = { method: function() { } }
64552             else if (container.kind === 208 /* FunctionExpression */ &&
64553                 container.parent.kind === 288 /* PropertyAssignment */ &&
64554                 container.parent.parent.kind === 200 /* ObjectLiteralExpression */ &&
64555                 ts.isBinaryExpression(container.parent.parent.parent) &&
64556                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 6 /* Prototype */) {
64557                 return container.parent.parent.parent.left.expression;
64558             }
64559             // Object.defineProperty(x, "method", { value: function() { } });
64560             // Object.defineProperty(x, "method", { set: (x: () => void) => void });
64561             // Object.defineProperty(x, "method", { get: () => function() { }) });
64562             else if (container.kind === 208 /* FunctionExpression */ &&
64563                 ts.isPropertyAssignment(container.parent) &&
64564                 ts.isIdentifier(container.parent.name) &&
64565                 (container.parent.name.escapedText === "value" || container.parent.name.escapedText === "get" || container.parent.name.escapedText === "set") &&
64566                 ts.isObjectLiteralExpression(container.parent.parent) &&
64567                 ts.isCallExpression(container.parent.parent.parent) &&
64568                 container.parent.parent.parent.arguments[2] === container.parent.parent &&
64569                 ts.getAssignmentDeclarationKind(container.parent.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
64570                 return container.parent.parent.parent.arguments[0].expression;
64571             }
64572             // Object.defineProperty(x, "method", { value() { } });
64573             // Object.defineProperty(x, "method", { set(x: () => void) {} });
64574             // Object.defineProperty(x, "method", { get() { return () => {} } });
64575             else if (ts.isMethodDeclaration(container) &&
64576                 ts.isIdentifier(container.name) &&
64577                 (container.name.escapedText === "value" || container.name.escapedText === "get" || container.name.escapedText === "set") &&
64578                 ts.isObjectLiteralExpression(container.parent) &&
64579                 ts.isCallExpression(container.parent.parent) &&
64580                 container.parent.parent.arguments[2] === container.parent &&
64581                 ts.getAssignmentDeclarationKind(container.parent.parent) === 9 /* ObjectDefinePrototypeProperty */) {
64582                 return container.parent.parent.arguments[0].expression;
64583             }
64584         }
64585         function getTypeForThisExpressionFromJSDoc(node) {
64586             var jsdocType = ts.getJSDocType(node);
64587             if (jsdocType && jsdocType.kind === 308 /* JSDocFunctionType */) {
64588                 var jsDocFunctionType = jsdocType;
64589                 if (jsDocFunctionType.parameters.length > 0 &&
64590                     jsDocFunctionType.parameters[0].name &&
64591                     jsDocFunctionType.parameters[0].name.escapedText === "this" /* This */) {
64592                     return getTypeFromTypeNode(jsDocFunctionType.parameters[0].type);
64593                 }
64594             }
64595             var thisTag = ts.getJSDocThisTag(node);
64596             if (thisTag && thisTag.typeExpression) {
64597                 return getTypeFromTypeNode(thisTag.typeExpression);
64598             }
64599         }
64600         function isInConstructorArgumentInitializer(node, constructorDecl) {
64601             return !!ts.findAncestor(node, function (n) { return ts.isFunctionLikeDeclaration(n) ? "quit" : n.kind === 160 /* Parameter */ && n.parent === constructorDecl; });
64602         }
64603         function checkSuperExpression(node) {
64604             var isCallExpression = node.parent.kind === 203 /* CallExpression */ && node.parent.expression === node;
64605             var immediateContainer = ts.getSuperContainer(node, /*stopOnFunctions*/ true);
64606             var container = immediateContainer;
64607             var needToCaptureLexicalThis = false;
64608             // adjust the container reference in case if super is used inside arrow functions with arbitrarily deep nesting
64609             if (!isCallExpression) {
64610                 while (container && container.kind === 209 /* ArrowFunction */) {
64611                     container = ts.getSuperContainer(container, /*stopOnFunctions*/ true);
64612                     needToCaptureLexicalThis = languageVersion < 2 /* ES2015 */;
64613                 }
64614             }
64615             var canUseSuperExpression = isLegalUsageOfSuperExpression(container);
64616             var nodeCheckFlag = 0;
64617             if (!canUseSuperExpression) {
64618                 // issue more specific error if super is used in computed property name
64619                 // class A { foo() { return "1" }}
64620                 // class B {
64621                 //     [super.foo()]() {}
64622                 // }
64623                 var current = ts.findAncestor(node, function (n) { return n === container ? "quit" : n.kind === 158 /* ComputedPropertyName */; });
64624                 if (current && current.kind === 158 /* ComputedPropertyName */) {
64625                     error(node, ts.Diagnostics.super_cannot_be_referenced_in_a_computed_property_name);
64626                 }
64627                 else if (isCallExpression) {
64628                     error(node, ts.Diagnostics.Super_calls_are_not_permitted_outside_constructors_or_in_nested_functions_inside_constructors);
64629                 }
64630                 else if (!container || !container.parent || !(ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */)) {
64631                     error(node, ts.Diagnostics.super_can_only_be_referenced_in_members_of_derived_classes_or_object_literal_expressions);
64632                 }
64633                 else {
64634                     error(node, ts.Diagnostics.super_property_access_is_permitted_only_in_a_constructor_member_function_or_member_accessor_of_a_derived_class);
64635                 }
64636                 return errorType;
64637             }
64638             if (!isCallExpression && immediateContainer.kind === 166 /* Constructor */) {
64639                 checkThisBeforeSuper(node, container, ts.Diagnostics.super_must_be_called_before_accessing_a_property_of_super_in_the_constructor_of_a_derived_class);
64640             }
64641             if (ts.hasSyntacticModifier(container, 32 /* Static */) || isCallExpression) {
64642                 nodeCheckFlag = 512 /* SuperStatic */;
64643             }
64644             else {
64645                 nodeCheckFlag = 256 /* SuperInstance */;
64646             }
64647             getNodeLinks(node).flags |= nodeCheckFlag;
64648             // Due to how we emit async functions, we need to specialize the emit for an async method that contains a `super` reference.
64649             // This is due to the fact that we emit the body of an async function inside of a generator function. As generator
64650             // functions cannot reference `super`, we emit a helper inside of the method body, but outside of the generator. This helper
64651             // uses an arrow function, which is permitted to reference `super`.
64652             //
64653             // There are two primary ways we can access `super` from within an async method. The first is getting the value of a property
64654             // or indexed access on super, either as part of a right-hand-side expression or call expression. The second is when setting the value
64655             // of a property or indexed access, either as part of an assignment expression or destructuring assignment.
64656             //
64657             // The simplest case is reading a value, in which case we will emit something like the following:
64658             //
64659             //  // ts
64660             //  ...
64661             //  async asyncMethod() {
64662             //    let x = await super.asyncMethod();
64663             //    return x;
64664             //  }
64665             //  ...
64666             //
64667             //  // js
64668             //  ...
64669             //  asyncMethod() {
64670             //      const _super = Object.create(null, {
64671             //        asyncMethod: { get: () => super.asyncMethod },
64672             //      });
64673             //      return __awaiter(this, arguments, Promise, function *() {
64674             //          let x = yield _super.asyncMethod.call(this);
64675             //          return x;
64676             //      });
64677             //  }
64678             //  ...
64679             //
64680             // The more complex case is when we wish to assign a value, especially as part of a destructuring assignment. As both cases
64681             // are legal in ES6, but also likely less frequent, we only emit setters if there is an assignment:
64682             //
64683             //  // ts
64684             //  ...
64685             //  async asyncMethod(ar: Promise<any[]>) {
64686             //      [super.a, super.b] = await ar;
64687             //  }
64688             //  ...
64689             //
64690             //  // js
64691             //  ...
64692             //  asyncMethod(ar) {
64693             //      const _super = Object.create(null, {
64694             //        a: { get: () => super.a, set: (v) => super.a = v },
64695             //        b: { get: () => super.b, set: (v) => super.b = v }
64696             //      };
64697             //      return __awaiter(this, arguments, Promise, function *() {
64698             //          [_super.a, _super.b] = yield ar;
64699             //      });
64700             //  }
64701             //  ...
64702             //
64703             // Creating an object that has getter and setters instead of just an accessor function is required for destructuring assignments
64704             // as a call expression cannot be used as the target of a destructuring assignment while a property access can.
64705             //
64706             // For element access expressions (`super[x]`), we emit a generic helper that forwards the element access in both situations.
64707             if (container.kind === 165 /* MethodDeclaration */ && ts.hasSyntacticModifier(container, 256 /* Async */)) {
64708                 if (ts.isSuperProperty(node.parent) && ts.isAssignmentTarget(node.parent)) {
64709                     getNodeLinks(container).flags |= 4096 /* AsyncMethodWithSuperBinding */;
64710                 }
64711                 else {
64712                     getNodeLinks(container).flags |= 2048 /* AsyncMethodWithSuper */;
64713                 }
64714             }
64715             if (needToCaptureLexicalThis) {
64716                 // call expressions are allowed only in constructors so they should always capture correct 'this'
64717                 // super property access expressions can also appear in arrow functions -
64718                 // in this case they should also use correct lexical this
64719                 captureLexicalThis(node.parent, container);
64720             }
64721             if (container.parent.kind === 200 /* ObjectLiteralExpression */) {
64722                 if (languageVersion < 2 /* ES2015 */) {
64723                     error(node, ts.Diagnostics.super_is_only_allowed_in_members_of_object_literal_expressions_when_option_target_is_ES2015_or_higher);
64724                     return errorType;
64725                 }
64726                 else {
64727                     // for object literal assume that type of 'super' is 'any'
64728                     return anyType;
64729                 }
64730             }
64731             // at this point the only legal case for parent is ClassLikeDeclaration
64732             var classLikeDeclaration = container.parent;
64733             if (!ts.getClassExtendsHeritageElement(classLikeDeclaration)) {
64734                 error(node, ts.Diagnostics.super_can_only_be_referenced_in_a_derived_class);
64735                 return errorType;
64736             }
64737             var classType = getDeclaredTypeOfSymbol(getSymbolOfNode(classLikeDeclaration));
64738             var baseClassType = classType && getBaseTypes(classType)[0];
64739             if (!baseClassType) {
64740                 return errorType;
64741             }
64742             if (container.kind === 166 /* Constructor */ && isInConstructorArgumentInitializer(node, container)) {
64743                 // issue custom error message for super property access in constructor arguments (to be aligned with old compiler)
64744                 error(node, ts.Diagnostics.super_cannot_be_referenced_in_constructor_arguments);
64745                 return errorType;
64746             }
64747             return nodeCheckFlag === 512 /* SuperStatic */
64748                 ? getBaseConstructorTypeOfClass(classType)
64749                 : getTypeWithThisArgument(baseClassType, classType.thisType);
64750             function isLegalUsageOfSuperExpression(container) {
64751                 if (!container) {
64752                     return false;
64753                 }
64754                 if (isCallExpression) {
64755                     // TS 1.0 SPEC (April 2014): 4.8.1
64756                     // Super calls are only permitted in constructors of derived classes
64757                     return container.kind === 166 /* Constructor */;
64758                 }
64759                 else {
64760                     // TS 1.0 SPEC (April 2014)
64761                     // 'super' property access is allowed
64762                     // - In a constructor, instance member function, instance member accessor, or instance member variable initializer where this references a derived class instance
64763                     // - In a static member function or static member accessor
64764                     // topmost container must be something that is directly nested in the class declaration\object literal expression
64765                     if (ts.isClassLike(container.parent) || container.parent.kind === 200 /* ObjectLiteralExpression */) {
64766                         if (ts.hasSyntacticModifier(container, 32 /* Static */)) {
64767                             return container.kind === 165 /* MethodDeclaration */ ||
64768                                 container.kind === 164 /* MethodSignature */ ||
64769                                 container.kind === 167 /* GetAccessor */ ||
64770                                 container.kind === 168 /* SetAccessor */;
64771                         }
64772                         else {
64773                             return container.kind === 165 /* MethodDeclaration */ ||
64774                                 container.kind === 164 /* MethodSignature */ ||
64775                                 container.kind === 167 /* GetAccessor */ ||
64776                                 container.kind === 168 /* SetAccessor */ ||
64777                                 container.kind === 163 /* PropertyDeclaration */ ||
64778                                 container.kind === 162 /* PropertySignature */ ||
64779                                 container.kind === 166 /* Constructor */;
64780                         }
64781                     }
64782                 }
64783                 return false;
64784             }
64785         }
64786         function getContainingObjectLiteral(func) {
64787             return (func.kind === 165 /* MethodDeclaration */ ||
64788                 func.kind === 167 /* GetAccessor */ ||
64789                 func.kind === 168 /* SetAccessor */) && func.parent.kind === 200 /* ObjectLiteralExpression */ ? func.parent :
64790                 func.kind === 208 /* FunctionExpression */ && func.parent.kind === 288 /* PropertyAssignment */ ? func.parent.parent :
64791                     undefined;
64792         }
64793         function getThisTypeArgument(type) {
64794             return ts.getObjectFlags(type) & 4 /* Reference */ && type.target === globalThisType ? getTypeArguments(type)[0] : undefined;
64795         }
64796         function getThisTypeFromContextualType(type) {
64797             return mapType(type, function (t) {
64798                 return t.flags & 2097152 /* Intersection */ ? ts.forEach(t.types, getThisTypeArgument) : getThisTypeArgument(t);
64799             });
64800         }
64801         function getContextualThisParameterType(func) {
64802             if (func.kind === 209 /* ArrowFunction */) {
64803                 return undefined;
64804             }
64805             if (isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
64806                 var contextualSignature = getContextualSignature(func);
64807                 if (contextualSignature) {
64808                     var thisParameter = contextualSignature.thisParameter;
64809                     if (thisParameter) {
64810                         return getTypeOfSymbol(thisParameter);
64811                     }
64812                 }
64813             }
64814             var inJs = ts.isInJSFile(func);
64815             if (noImplicitThis || inJs) {
64816                 var containingLiteral = getContainingObjectLiteral(func);
64817                 if (containingLiteral) {
64818                     // We have an object literal method. Check if the containing object literal has a contextual type
64819                     // that includes a ThisType<T>. If so, T is the contextual type for 'this'. We continue looking in
64820                     // any directly enclosing object literals.
64821                     var contextualType = getApparentTypeOfContextualType(containingLiteral);
64822                     var literal = containingLiteral;
64823                     var type = contextualType;
64824                     while (type) {
64825                         var thisType = getThisTypeFromContextualType(type);
64826                         if (thisType) {
64827                             return instantiateType(thisType, getMapperFromContext(getInferenceContext(containingLiteral)));
64828                         }
64829                         if (literal.parent.kind !== 288 /* PropertyAssignment */) {
64830                             break;
64831                         }
64832                         literal = literal.parent.parent;
64833                         type = getApparentTypeOfContextualType(literal);
64834                     }
64835                     // There was no contextual ThisType<T> for the containing object literal, so the contextual type
64836                     // for 'this' is the non-null form of the contextual type for the containing object literal or
64837                     // the type of the object literal itself.
64838                     return getWidenedType(contextualType ? getNonNullableType(contextualType) : checkExpressionCached(containingLiteral));
64839                 }
64840                 // In an assignment of the form 'obj.xxx = function(...)' or 'obj[xxx] = function(...)', the
64841                 // contextual type for 'this' is 'obj'.
64842                 var parent = ts.walkUpParenthesizedExpressions(func.parent);
64843                 if (parent.kind === 216 /* BinaryExpression */ && parent.operatorToken.kind === 62 /* EqualsToken */) {
64844                     var target = parent.left;
64845                     if (ts.isAccessExpression(target)) {
64846                         var expression = target.expression;
64847                         // Don't contextually type `this` as `exports` in `exports.Point = function(x, y) { this.x = x; this.y = y; }`
64848                         if (inJs && ts.isIdentifier(expression)) {
64849                             var sourceFile = ts.getSourceFileOfNode(parent);
64850                             if (sourceFile.commonJsModuleIndicator && getResolvedSymbol(expression) === sourceFile.symbol) {
64851                                 return undefined;
64852                             }
64853                         }
64854                         return getWidenedType(checkExpressionCached(expression));
64855                     }
64856                 }
64857             }
64858             return undefined;
64859         }
64860         // Return contextual type of parameter or undefined if no contextual type is available
64861         function getContextuallyTypedParameterType(parameter) {
64862             var func = parameter.parent;
64863             if (!isContextSensitiveFunctionOrObjectLiteralMethod(func)) {
64864                 return undefined;
64865             }
64866             var iife = ts.getImmediatelyInvokedFunctionExpression(func);
64867             if (iife && iife.arguments) {
64868                 var args = getEffectiveCallArguments(iife);
64869                 var indexOfParameter = func.parameters.indexOf(parameter);
64870                 if (parameter.dotDotDotToken) {
64871                     return getSpreadArgumentType(args, indexOfParameter, args.length, anyType, /*context*/ undefined, 0 /* Normal */);
64872                 }
64873                 var links = getNodeLinks(iife);
64874                 var cached = links.resolvedSignature;
64875                 links.resolvedSignature = anySignature;
64876                 var type = indexOfParameter < args.length ?
64877                     getWidenedLiteralType(checkExpression(args[indexOfParameter])) :
64878                     parameter.initializer ? undefined : undefinedWideningType;
64879                 links.resolvedSignature = cached;
64880                 return type;
64881             }
64882             var contextualSignature = getContextualSignature(func);
64883             if (contextualSignature) {
64884                 var index = func.parameters.indexOf(parameter) - (ts.getThisParameter(func) ? 1 : 0);
64885                 return parameter.dotDotDotToken && ts.lastOrUndefined(func.parameters) === parameter ?
64886                     getRestTypeAtPosition(contextualSignature, index) :
64887                     tryGetTypeAtPosition(contextualSignature, index);
64888             }
64889         }
64890         function getContextualTypeForVariableLikeDeclaration(declaration) {
64891             var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
64892             if (typeNode) {
64893                 return getTypeFromTypeNode(typeNode);
64894             }
64895             switch (declaration.kind) {
64896                 case 160 /* Parameter */:
64897                     return getContextuallyTypedParameterType(declaration);
64898                 case 198 /* BindingElement */:
64899                     return getContextualTypeForBindingElement(declaration);
64900                 case 163 /* PropertyDeclaration */:
64901                     if (ts.hasSyntacticModifier(declaration, 32 /* Static */)) {
64902                         return getContextualTypeForStaticPropertyDeclaration(declaration);
64903                     }
64904                 // By default, do nothing and return undefined - only the above cases have context implied by a parent
64905             }
64906         }
64907         function getContextualTypeForBindingElement(declaration) {
64908             var parent = declaration.parent.parent;
64909             var name = declaration.propertyName || declaration.name;
64910             var parentType = getContextualTypeForVariableLikeDeclaration(parent) ||
64911                 parent.kind !== 198 /* BindingElement */ && parent.initializer && checkDeclarationInitializer(parent);
64912             if (!parentType || ts.isBindingPattern(name) || ts.isComputedNonLiteralName(name))
64913                 return undefined;
64914             if (parent.name.kind === 197 /* ArrayBindingPattern */) {
64915                 var index = ts.indexOfNode(declaration.parent.elements, declaration);
64916                 if (index < 0)
64917                     return undefined;
64918                 return getContextualTypeForElementExpression(parentType, index);
64919             }
64920             var nameType = getLiteralTypeFromPropertyName(name);
64921             if (isTypeUsableAsPropertyName(nameType)) {
64922                 var text = getPropertyNameFromType(nameType);
64923                 return getTypeOfPropertyOfType(parentType, text);
64924             }
64925         }
64926         function getContextualTypeForStaticPropertyDeclaration(declaration) {
64927             var parentType = ts.isExpression(declaration.parent) && getContextualType(declaration.parent);
64928             if (!parentType)
64929                 return undefined;
64930             return getTypeOfPropertyOfContextualType(parentType, getSymbolOfNode(declaration).escapedName);
64931         }
64932         // In a variable, parameter or property declaration with a type annotation,
64933         //   the contextual type of an initializer expression is the type of the variable, parameter or property.
64934         // Otherwise, in a parameter declaration of a contextually typed function expression,
64935         //   the contextual type of an initializer expression is the contextual type of the parameter.
64936         // Otherwise, in a variable or parameter declaration with a binding pattern name,
64937         //   the contextual type of an initializer expression is the type implied by the binding pattern.
64938         // Otherwise, in a binding pattern inside a variable or parameter declaration,
64939         //   the contextual type of an initializer expression is the type annotation of the containing declaration, if present.
64940         function getContextualTypeForInitializerExpression(node, contextFlags) {
64941             var declaration = node.parent;
64942             if (ts.hasInitializer(declaration) && node === declaration.initializer) {
64943                 var result = getContextualTypeForVariableLikeDeclaration(declaration);
64944                 if (result) {
64945                     return result;
64946                 }
64947                 if (!(contextFlags & 8 /* SkipBindingPatterns */) && ts.isBindingPattern(declaration.name)) { // This is less a contextual type and more an implied shape - in some cases, this may be undesirable
64948                     return getTypeFromBindingPattern(declaration.name, /*includePatternInType*/ true, /*reportErrors*/ false);
64949                 }
64950             }
64951             return undefined;
64952         }
64953         function getContextualTypeForReturnExpression(node) {
64954             var func = ts.getContainingFunction(node);
64955             if (func) {
64956                 var contextualReturnType = getContextualReturnType(func);
64957                 if (contextualReturnType) {
64958                     var functionFlags = ts.getFunctionFlags(func);
64959                     if (functionFlags & 1 /* Generator */) { // Generator or AsyncGenerator function
64960                         var use = functionFlags & 2 /* Async */ ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
64961                         var iterationTypes = getIterationTypesOfIterable(contextualReturnType, use, /*errorNode*/ undefined);
64962                         if (!iterationTypes) {
64963                             return undefined;
64964                         }
64965                         contextualReturnType = iterationTypes.returnType;
64966                         // falls through to unwrap Promise for AsyncGenerators
64967                     }
64968                     if (functionFlags & 2 /* Async */) { // Async function or AsyncGenerator function
64969                         var contextualAwaitedType = mapType(contextualReturnType, getAwaitedType);
64970                         return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
64971                     }
64972                     return contextualReturnType; // Regular function or Generator function
64973                 }
64974             }
64975             return undefined;
64976         }
64977         function getContextualTypeForAwaitOperand(node, contextFlags) {
64978             var contextualType = getContextualType(node, contextFlags);
64979             if (contextualType) {
64980                 var contextualAwaitedType = getAwaitedType(contextualType);
64981                 return contextualAwaitedType && getUnionType([contextualAwaitedType, createPromiseLikeType(contextualAwaitedType)]);
64982             }
64983             return undefined;
64984         }
64985         function getContextualTypeForYieldOperand(node) {
64986             var func = ts.getContainingFunction(node);
64987             if (func) {
64988                 var functionFlags = ts.getFunctionFlags(func);
64989                 var contextualReturnType = getContextualReturnType(func);
64990                 if (contextualReturnType) {
64991                     return node.asteriskToken
64992                         ? contextualReturnType
64993                         : getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, contextualReturnType, (functionFlags & 2 /* Async */) !== 0);
64994                 }
64995             }
64996             return undefined;
64997         }
64998         function isInParameterInitializerBeforeContainingFunction(node) {
64999             var inBindingInitializer = false;
65000             while (node.parent && !ts.isFunctionLike(node.parent)) {
65001                 if (ts.isParameter(node.parent) && (inBindingInitializer || node.parent.initializer === node)) {
65002                     return true;
65003                 }
65004                 if (ts.isBindingElement(node.parent) && node.parent.initializer === node) {
65005                     inBindingInitializer = true;
65006                 }
65007                 node = node.parent;
65008             }
65009             return false;
65010         }
65011         function getContextualIterationType(kind, functionDecl) {
65012             var isAsync = !!(ts.getFunctionFlags(functionDecl) & 2 /* Async */);
65013             var contextualReturnType = getContextualReturnType(functionDecl);
65014             if (contextualReturnType) {
65015                 return getIterationTypeOfGeneratorFunctionReturnType(kind, contextualReturnType, isAsync)
65016                     || undefined;
65017             }
65018             return undefined;
65019         }
65020         function getContextualReturnType(functionDecl) {
65021             // If the containing function has a return type annotation, is a constructor, or is a get accessor whose
65022             // corresponding set accessor has a type annotation, return statements in the function are contextually typed
65023             var returnType = getReturnTypeFromAnnotation(functionDecl);
65024             if (returnType) {
65025                 return returnType;
65026             }
65027             // Otherwise, if the containing function is contextually typed by a function type with exactly one call signature
65028             // and that call signature is non-generic, return statements are contextually typed by the return type of the signature
65029             var signature = getContextualSignatureForFunctionLikeDeclaration(functionDecl);
65030             if (signature && !isResolvingReturnTypeOfSignature(signature)) {
65031                 return getReturnTypeOfSignature(signature);
65032             }
65033             return undefined;
65034         }
65035         // In a typed function call, an argument or substitution expression is contextually typed by the type of the corresponding parameter.
65036         function getContextualTypeForArgument(callTarget, arg) {
65037             var args = getEffectiveCallArguments(callTarget);
65038             var argIndex = args.indexOf(arg); // -1 for e.g. the expression of a CallExpression, or the tag of a TaggedTemplateExpression
65039             return argIndex === -1 ? undefined : getContextualTypeForArgumentAtIndex(callTarget, argIndex);
65040         }
65041         function getContextualTypeForArgumentAtIndex(callTarget, argIndex) {
65042             // If we're already in the process of resolving the given signature, don't resolve again as
65043             // that could cause infinite recursion. Instead, return anySignature.
65044             var signature = getNodeLinks(callTarget).resolvedSignature === resolvingSignature ? resolvingSignature : getResolvedSignature(callTarget);
65045             if (ts.isJsxOpeningLikeElement(callTarget) && argIndex === 0) {
65046                 return getEffectiveFirstArgumentForJsxSignature(signature, callTarget);
65047             }
65048             return getTypeAtPosition(signature, argIndex);
65049         }
65050         function getContextualTypeForSubstitutionExpression(template, substitutionExpression) {
65051             if (template.parent.kind === 205 /* TaggedTemplateExpression */) {
65052                 return getContextualTypeForArgument(template.parent, substitutionExpression);
65053             }
65054             return undefined;
65055         }
65056         function getContextualTypeForBinaryOperand(node, contextFlags) {
65057             var binaryExpression = node.parent;
65058             var left = binaryExpression.left, operatorToken = binaryExpression.operatorToken, right = binaryExpression.right;
65059             switch (operatorToken.kind) {
65060                 case 62 /* EqualsToken */:
65061                 case 75 /* AmpersandAmpersandEqualsToken */:
65062                 case 74 /* BarBarEqualsToken */:
65063                 case 76 /* QuestionQuestionEqualsToken */:
65064                     return node === right ? getContextualTypeForAssignmentDeclaration(binaryExpression) : undefined;
65065                 case 56 /* BarBarToken */:
65066                 case 60 /* QuestionQuestionToken */:
65067                     // When an || expression has a contextual type, the operands are contextually typed by that type, except
65068                     // when that type originates in a binding pattern, the right operand is contextually typed by the type of
65069                     // the left operand. When an || expression has no contextual type, the right operand is contextually typed
65070                     // by the type of the left operand, except for the special case of Javascript declarations of the form
65071                     // `namespace.prop = namespace.prop || {}`.
65072                     var type = getContextualType(binaryExpression, contextFlags);
65073                     return node === right && (type && type.pattern || !type && !ts.isDefaultedExpandoInitializer(binaryExpression)) ?
65074                         getTypeOfExpression(left) : type;
65075                 case 55 /* AmpersandAmpersandToken */:
65076                 case 27 /* CommaToken */:
65077                     return node === right ? getContextualType(binaryExpression, contextFlags) : undefined;
65078                 default:
65079                     return undefined;
65080             }
65081         }
65082         // In an assignment expression, the right operand is contextually typed by the type of the left operand.
65083         // Don't do this for assignment declarations unless there is a type tag on the assignment, to avoid circularity from checking the right operand.
65084         function getContextualTypeForAssignmentDeclaration(binaryExpression) {
65085             var kind = ts.getAssignmentDeclarationKind(binaryExpression);
65086             switch (kind) {
65087                 case 0 /* None */:
65088                     return getTypeOfExpression(binaryExpression.left);
65089                 case 5 /* Property */:
65090                 case 1 /* ExportsProperty */:
65091                 case 6 /* Prototype */:
65092                 case 3 /* PrototypeProperty */:
65093                     if (isPossiblyAliasedThisProperty(binaryExpression, kind)) {
65094                         return getContextualTypeForThisPropertyAssignment(binaryExpression, kind);
65095                     }
65096                     // If `binaryExpression.left` was assigned a symbol, then this is a new declaration; otherwise it is an assignment to an existing declaration.
65097                     // See `bindStaticPropertyAssignment` in `binder.ts`.
65098                     else if (!binaryExpression.left.symbol) {
65099                         return getTypeOfExpression(binaryExpression.left);
65100                     }
65101                     else {
65102                         var decl = binaryExpression.left.symbol.valueDeclaration;
65103                         if (!decl) {
65104                             return undefined;
65105                         }
65106                         var lhs = ts.cast(binaryExpression.left, ts.isAccessExpression);
65107                         var overallAnnotation = ts.getEffectiveTypeAnnotationNode(decl);
65108                         if (overallAnnotation) {
65109                             return getTypeFromTypeNode(overallAnnotation);
65110                         }
65111                         else if (ts.isIdentifier(lhs.expression)) {
65112                             var id = lhs.expression;
65113                             var parentSymbol = resolveName(id, id.escapedText, 111551 /* Value */, undefined, id.escapedText, /*isUse*/ true);
65114                             if (parentSymbol) {
65115                                 var annotated = parentSymbol.valueDeclaration && ts.getEffectiveTypeAnnotationNode(parentSymbol.valueDeclaration);
65116                                 if (annotated) {
65117                                     var nameStr = ts.getElementOrPropertyAccessName(lhs);
65118                                     if (nameStr !== undefined) {
65119                                         return getTypeOfPropertyOfContextualType(getTypeFromTypeNode(annotated), nameStr);
65120                                     }
65121                                 }
65122                                 return undefined;
65123                             }
65124                         }
65125                         return ts.isInJSFile(decl) ? undefined : getTypeOfExpression(binaryExpression.left);
65126                     }
65127                 case 2 /* ModuleExports */:
65128                 case 4 /* ThisProperty */:
65129                     return getContextualTypeForThisPropertyAssignment(binaryExpression, kind);
65130                 case 7 /* ObjectDefinePropertyValue */:
65131                 case 8 /* ObjectDefinePropertyExports */:
65132                 case 9 /* ObjectDefinePrototypeProperty */:
65133                     return ts.Debug.fail("Does not apply");
65134                 default:
65135                     return ts.Debug.assertNever(kind);
65136             }
65137         }
65138         function isPossiblyAliasedThisProperty(declaration, kind) {
65139             if (kind === void 0) { kind = ts.getAssignmentDeclarationKind(declaration); }
65140             if (kind === 4 /* ThisProperty */) {
65141                 return true;
65142             }
65143             if (!ts.isInJSFile(declaration) || kind !== 5 /* Property */ || !ts.isIdentifier(declaration.left.expression)) {
65144                 return false;
65145             }
65146             var name = declaration.left.expression.escapedText;
65147             var symbol = resolveName(declaration.left, name, 111551 /* Value */, undefined, undefined, /*isUse*/ true, /*excludeGlobals*/ true);
65148             return ts.isThisInitializedDeclaration(symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration);
65149         }
65150         function getContextualTypeForThisPropertyAssignment(binaryExpression, kind) {
65151             if (!binaryExpression.symbol)
65152                 return getTypeOfExpression(binaryExpression.left);
65153             if (binaryExpression.symbol.valueDeclaration) {
65154                 var annotated = ts.getEffectiveTypeAnnotationNode(binaryExpression.symbol.valueDeclaration);
65155                 if (annotated) {
65156                     var type = getTypeFromTypeNode(annotated);
65157                     if (type) {
65158                         return type;
65159                     }
65160                 }
65161             }
65162             if (kind === 2 /* ModuleExports */)
65163                 return undefined;
65164             var thisAccess = ts.cast(binaryExpression.left, ts.isAccessExpression);
65165             if (!ts.isObjectLiteralMethod(ts.getThisContainer(thisAccess.expression, /*includeArrowFunctions*/ false))) {
65166                 return undefined;
65167             }
65168             var thisType = checkThisExpression(thisAccess.expression);
65169             var nameStr = ts.getElementOrPropertyAccessName(thisAccess);
65170             return nameStr !== undefined && getTypeOfPropertyOfContextualType(thisType, nameStr) || undefined;
65171         }
65172         function isCircularMappedProperty(symbol) {
65173             return !!(ts.getCheckFlags(symbol) & 262144 /* Mapped */ && !symbol.type && findResolutionCycleStartIndex(symbol, 0 /* Type */) >= 0);
65174         }
65175         function getTypeOfPropertyOfContextualType(type, name) {
65176             return mapType(type, function (t) {
65177                 if (isGenericMappedType(t)) {
65178                     var constraint = getConstraintTypeFromMappedType(t);
65179                     var constraintOfConstraint = getBaseConstraintOfType(constraint) || constraint;
65180                     var propertyNameType = getLiteralType(ts.unescapeLeadingUnderscores(name));
65181                     if (isTypeAssignableTo(propertyNameType, constraintOfConstraint)) {
65182                         return substituteIndexedMappedType(t, propertyNameType);
65183                     }
65184                 }
65185                 else if (t.flags & 3670016 /* StructuredType */) {
65186                     var prop = getPropertyOfType(t, name);
65187                     if (prop) {
65188                         return isCircularMappedProperty(prop) ? undefined : getTypeOfSymbol(prop);
65189                     }
65190                     if (isTupleType(t)) {
65191                         var restType = getRestTypeOfTupleType(t);
65192                         if (restType && isNumericLiteralName(name) && +name >= 0) {
65193                             return restType;
65194                         }
65195                     }
65196                     return isNumericLiteralName(name) && getIndexTypeOfContextualType(t, 1 /* Number */) ||
65197                         getIndexTypeOfContextualType(t, 0 /* String */);
65198                 }
65199                 return undefined;
65200             }, /*noReductions*/ true);
65201         }
65202         function getIndexTypeOfContextualType(type, kind) {
65203             return mapType(type, function (t) { return getIndexTypeOfStructuredType(t, kind); }, /*noReductions*/ true);
65204         }
65205         // In an object literal contextually typed by a type T, the contextual type of a property assignment is the type of
65206         // the matching property in T, if one exists. Otherwise, it is the type of the numeric index signature in T, if one
65207         // exists. Otherwise, it is the type of the string index signature in T, if one exists.
65208         function getContextualTypeForObjectLiteralMethod(node, contextFlags) {
65209             ts.Debug.assert(ts.isObjectLiteralMethod(node));
65210             if (node.flags & 16777216 /* InWithStatement */) {
65211                 // We cannot answer semantic questions within a with block, do not proceed any further
65212                 return undefined;
65213             }
65214             return getContextualTypeForObjectLiteralElement(node, contextFlags);
65215         }
65216         function getContextualTypeForObjectLiteralElement(element, contextFlags) {
65217             var objectLiteral = element.parent;
65218             var type = getApparentTypeOfContextualType(objectLiteral, contextFlags);
65219             if (type) {
65220                 if (!hasNonBindableDynamicName(element)) {
65221                     // For a (non-symbol) computed property, there is no reason to look up the name
65222                     // in the type. It will just be "__computed", which does not appear in any
65223                     // SymbolTable.
65224                     var symbolName_3 = getSymbolOfNode(element).escapedName;
65225                     var propertyType = getTypeOfPropertyOfContextualType(type, symbolName_3);
65226                     if (propertyType) {
65227                         return propertyType;
65228                     }
65229                 }
65230                 return isNumericName(element.name) && getIndexTypeOfContextualType(type, 1 /* Number */) ||
65231                     getIndexTypeOfContextualType(type, 0 /* String */);
65232             }
65233             return undefined;
65234         }
65235         // In an array literal contextually typed by a type T, the contextual type of an element expression at index N is
65236         // the type of the property with the numeric name N in T, if one exists. Otherwise, if T has a numeric index signature,
65237         // it is the type of the numeric index signature in T. Otherwise, in ES6 and higher, the contextual type is the iterated
65238         // type of T.
65239         function getContextualTypeForElementExpression(arrayContextualType, index) {
65240             return arrayContextualType && (getTypeOfPropertyOfContextualType(arrayContextualType, "" + index)
65241                 || mapType(arrayContextualType, function (t) { return getIteratedTypeOrElementType(1 /* Element */, t, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false); }, 
65242                 /*noReductions*/ true));
65243         }
65244         // In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
65245         function getContextualTypeForConditionalOperand(node, contextFlags) {
65246             var conditional = node.parent;
65247             return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional, contextFlags) : undefined;
65248         }
65249         function getContextualTypeForChildJsxExpression(node, child) {
65250             var attributesType = getApparentTypeOfContextualType(node.openingElement.tagName);
65251             // JSX expression is in children of JSX Element, we will look for an "children" atttribute (we get the name from JSX.ElementAttributesProperty)
65252             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(node));
65253             if (!(attributesType && !isTypeAny(attributesType) && jsxChildrenPropertyName && jsxChildrenPropertyName !== "")) {
65254                 return undefined;
65255             }
65256             var realChildren = ts.getSemanticJsxChildren(node.children);
65257             var childIndex = realChildren.indexOf(child);
65258             var childFieldType = getTypeOfPropertyOfContextualType(attributesType, jsxChildrenPropertyName);
65259             return childFieldType && (realChildren.length === 1 ? childFieldType : mapType(childFieldType, function (t) {
65260                 if (isArrayLikeType(t)) {
65261                     return getIndexedAccessType(t, getLiteralType(childIndex));
65262                 }
65263                 else {
65264                     return t;
65265                 }
65266             }, /*noReductions*/ true));
65267         }
65268         function getContextualTypeForJsxExpression(node) {
65269             var exprParent = node.parent;
65270             return ts.isJsxAttributeLike(exprParent)
65271                 ? getContextualType(node)
65272                 : ts.isJsxElement(exprParent)
65273                     ? getContextualTypeForChildJsxExpression(exprParent, node)
65274                     : undefined;
65275         }
65276         function getContextualTypeForJsxAttribute(attribute) {
65277             // When we trying to resolve JsxOpeningLikeElement as a stateless function element, we will already give its attributes a contextual type
65278             // which is a type of the parameter of the signature we are trying out.
65279             // If there is no contextual type (e.g. we are trying to resolve stateful component), get attributes type from resolving element's tagName
65280             if (ts.isJsxAttribute(attribute)) {
65281                 var attributesType = getApparentTypeOfContextualType(attribute.parent);
65282                 if (!attributesType || isTypeAny(attributesType)) {
65283                     return undefined;
65284                 }
65285                 return getTypeOfPropertyOfContextualType(attributesType, attribute.name.escapedText);
65286             }
65287             else {
65288                 return getContextualType(attribute.parent);
65289             }
65290         }
65291         // Return true if the given expression is possibly a discriminant value. We limit the kinds of
65292         // expressions we check to those that don't depend on their contextual type in order not to cause
65293         // recursive (and possibly infinite) invocations of getContextualType.
65294         function isPossiblyDiscriminantValue(node) {
65295             switch (node.kind) {
65296                 case 10 /* StringLiteral */:
65297                 case 8 /* NumericLiteral */:
65298                 case 9 /* BigIntLiteral */:
65299                 case 14 /* NoSubstitutionTemplateLiteral */:
65300                 case 109 /* TrueKeyword */:
65301                 case 94 /* FalseKeyword */:
65302                 case 103 /* NullKeyword */:
65303                 case 78 /* Identifier */:
65304                 case 150 /* UndefinedKeyword */:
65305                     return true;
65306                 case 201 /* PropertyAccessExpression */:
65307                 case 207 /* ParenthesizedExpression */:
65308                     return isPossiblyDiscriminantValue(node.expression);
65309                 case 283 /* JsxExpression */:
65310                     return !node.expression || isPossiblyDiscriminantValue(node.expression);
65311             }
65312             return false;
65313         }
65314         function discriminateContextualTypeByObjectMembers(node, contextualType) {
65315             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 288 /* PropertyAssignment */ && isPossiblyDiscriminantValue(p.initializer) && isDiscriminantProperty(contextualType, p.symbol.escapedName); }), function (prop) { return [function () { return checkExpression(prop.initializer); }, prop.symbol.escapedName]; }), isTypeAssignableTo, contextualType);
65316         }
65317         function discriminateContextualTypeByJSXAttributes(node, contextualType) {
65318             return discriminateTypeByDiscriminableItems(contextualType, ts.map(ts.filter(node.properties, function (p) { return !!p.symbol && p.kind === 280 /* 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);
65319         }
65320         // Return the contextual type for a given expression node. During overload resolution, a contextual type may temporarily
65321         // be "pushed" onto a node using the contextualType property.
65322         function getApparentTypeOfContextualType(node, contextFlags) {
65323             var contextualType = ts.isObjectLiteralMethod(node) ?
65324                 getContextualTypeForObjectLiteralMethod(node, contextFlags) :
65325                 getContextualType(node, contextFlags);
65326             var instantiatedType = instantiateContextualType(contextualType, node, contextFlags);
65327             if (instantiatedType && !(contextFlags && contextFlags & 2 /* NoConstraints */ && instantiatedType.flags & 8650752 /* TypeVariable */)) {
65328                 var apparentType = mapType(instantiatedType, getApparentType, /*noReductions*/ true);
65329                 if (apparentType.flags & 1048576 /* Union */) {
65330                     if (ts.isObjectLiteralExpression(node)) {
65331                         return discriminateContextualTypeByObjectMembers(node, apparentType);
65332                     }
65333                     else if (ts.isJsxAttributes(node)) {
65334                         return discriminateContextualTypeByJSXAttributes(node, apparentType);
65335                     }
65336                 }
65337                 return apparentType;
65338             }
65339         }
65340         // If the given contextual type contains instantiable types and if a mapper representing
65341         // return type inferences is available, instantiate those types using that mapper.
65342         function instantiateContextualType(contextualType, node, contextFlags) {
65343             if (contextualType && maybeTypeOfKind(contextualType, 465829888 /* Instantiable */)) {
65344                 var inferenceContext = getInferenceContext(node);
65345                 // If no inferences have been made, nothing is gained from instantiating as type parameters
65346                 // would just be replaced with their defaults similar to the apparent type.
65347                 if (inferenceContext && ts.some(inferenceContext.inferences, hasInferenceCandidates)) {
65348                     // For contextual signatures we incorporate all inferences made so far, e.g. from return
65349                     // types as well as arguments to the left in a function call.
65350                     if (contextFlags && contextFlags & 1 /* Signature */) {
65351                         return instantiateInstantiableTypes(contextualType, inferenceContext.nonFixingMapper);
65352                     }
65353                     // For other purposes (e.g. determining whether to produce literal types) we only
65354                     // incorporate inferences made from the return type in a function call.
65355                     if (inferenceContext.returnMapper) {
65356                         return instantiateInstantiableTypes(contextualType, inferenceContext.returnMapper);
65357                     }
65358                 }
65359             }
65360             return contextualType;
65361         }
65362         // This function is similar to instantiateType, except that (a) it only instantiates types that
65363         // are classified as instantiable (i.e. it doesn't instantiate object types), and (b) it performs
65364         // no reductions on instantiated union types.
65365         function instantiateInstantiableTypes(type, mapper) {
65366             if (type.flags & 465829888 /* Instantiable */) {
65367                 return instantiateType(type, mapper);
65368             }
65369             if (type.flags & 1048576 /* Union */) {
65370                 return getUnionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }), 0 /* None */);
65371             }
65372             if (type.flags & 2097152 /* Intersection */) {
65373                 return getIntersectionType(ts.map(type.types, function (t) { return instantiateInstantiableTypes(t, mapper); }));
65374             }
65375             return type;
65376         }
65377         /**
65378          * Whoa! Do you really want to use this function?
65379          *
65380          * Unless you're trying to get the *non-apparent* type for a
65381          * value-literal type or you're authoring relevant portions of this algorithm,
65382          * you probably meant to use 'getApparentTypeOfContextualType'.
65383          * Otherwise this may not be very useful.
65384          *
65385          * In cases where you *are* working on this function, you should understand
65386          * when it is appropriate to use 'getContextualType' and 'getApparentTypeOfContextualType'.
65387          *
65388          *   - Use 'getContextualType' when you are simply going to propagate the result to the expression.
65389          *   - Use 'getApparentTypeOfContextualType' when you're going to need the members of the type.
65390          *
65391          * @param node the expression whose contextual type will be returned.
65392          * @returns the contextual type of an expression.
65393          */
65394         function getContextualType(node, contextFlags) {
65395             if (node.flags & 16777216 /* InWithStatement */) {
65396                 // We cannot answer semantic questions within a with block, do not proceed any further
65397                 return undefined;
65398             }
65399             if (node.contextualType) {
65400                 return node.contextualType;
65401             }
65402             var parent = node.parent;
65403             switch (parent.kind) {
65404                 case 249 /* VariableDeclaration */:
65405                 case 160 /* Parameter */:
65406                 case 163 /* PropertyDeclaration */:
65407                 case 162 /* PropertySignature */:
65408                 case 198 /* BindingElement */:
65409                     return getContextualTypeForInitializerExpression(node, contextFlags);
65410                 case 209 /* ArrowFunction */:
65411                 case 242 /* ReturnStatement */:
65412                     return getContextualTypeForReturnExpression(node);
65413                 case 219 /* YieldExpression */:
65414                     return getContextualTypeForYieldOperand(parent);
65415                 case 213 /* AwaitExpression */:
65416                     return getContextualTypeForAwaitOperand(parent, contextFlags);
65417                 case 203 /* CallExpression */:
65418                     if (parent.expression.kind === 99 /* ImportKeyword */) {
65419                         return stringType;
65420                     }
65421                 /* falls through */
65422                 case 204 /* NewExpression */:
65423                     return getContextualTypeForArgument(parent, node);
65424                 case 206 /* TypeAssertionExpression */:
65425                 case 224 /* AsExpression */:
65426                     return ts.isConstTypeReference(parent.type) ? tryFindWhenConstTypeReference(parent) : getTypeFromTypeNode(parent.type);
65427                 case 216 /* BinaryExpression */:
65428                     return getContextualTypeForBinaryOperand(node, contextFlags);
65429                 case 288 /* PropertyAssignment */:
65430                 case 289 /* ShorthandPropertyAssignment */:
65431                     return getContextualTypeForObjectLiteralElement(parent, contextFlags);
65432                 case 290 /* SpreadAssignment */:
65433                     return getApparentTypeOfContextualType(parent.parent, contextFlags);
65434                 case 199 /* ArrayLiteralExpression */: {
65435                     var arrayLiteral = parent;
65436                     var type = getApparentTypeOfContextualType(arrayLiteral, contextFlags);
65437                     return getContextualTypeForElementExpression(type, ts.indexOfNode(arrayLiteral.elements, node));
65438                 }
65439                 case 217 /* ConditionalExpression */:
65440                     return getContextualTypeForConditionalOperand(node, contextFlags);
65441                 case 228 /* TemplateSpan */:
65442                     ts.Debug.assert(parent.parent.kind === 218 /* TemplateExpression */);
65443                     return getContextualTypeForSubstitutionExpression(parent.parent, node);
65444                 case 207 /* ParenthesizedExpression */: {
65445                     // Like in `checkParenthesizedExpression`, an `/** @type {xyz} */` comment before a parenthesized expression acts as a type cast.
65446                     var tag = ts.isInJSFile(parent) ? ts.getJSDocTypeTag(parent) : undefined;
65447                     return tag ? getTypeFromTypeNode(tag.typeExpression.type) : getContextualType(parent, contextFlags);
65448                 }
65449                 case 283 /* JsxExpression */:
65450                     return getContextualTypeForJsxExpression(parent);
65451                 case 280 /* JsxAttribute */:
65452                 case 282 /* JsxSpreadAttribute */:
65453                     return getContextualTypeForJsxAttribute(parent);
65454                 case 275 /* JsxOpeningElement */:
65455                 case 274 /* JsxSelfClosingElement */:
65456                     return getContextualJsxElementAttributesType(parent, contextFlags);
65457             }
65458             return undefined;
65459             function tryFindWhenConstTypeReference(node) {
65460                 if (ts.isCallLikeExpression(node.parent)) {
65461                     return getContextualTypeForArgument(node.parent, node);
65462                 }
65463                 return undefined;
65464             }
65465         }
65466         function getInferenceContext(node) {
65467             var ancestor = ts.findAncestor(node, function (n) { return !!n.inferenceContext; });
65468             return ancestor && ancestor.inferenceContext;
65469         }
65470         function getContextualJsxElementAttributesType(node, contextFlags) {
65471             if (ts.isJsxOpeningElement(node) && node.parent.contextualType && contextFlags !== 4 /* Completions */) {
65472                 // Contextually applied type is moved from attributes up to the outer jsx attributes so when walking up from the children they get hit
65473                 // _However_ to hit them from the _attributes_ we must look for them here; otherwise we'll used the declared type
65474                 // (as below) instead!
65475                 return node.parent.contextualType;
65476             }
65477             return getContextualTypeForArgumentAtIndex(node, 0);
65478         }
65479         function getEffectiveFirstArgumentForJsxSignature(signature, node) {
65480             return getJsxReferenceKind(node) !== 0 /* Component */
65481                 ? getJsxPropsTypeFromCallSignature(signature, node)
65482                 : getJsxPropsTypeFromClassType(signature, node);
65483         }
65484         function getJsxPropsTypeFromCallSignature(sig, context) {
65485             var propsType = getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType);
65486             propsType = getJsxManagedAttributesFromLocatedAttributes(context, getJsxNamespaceAt(context), propsType);
65487             var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
65488             if (intrinsicAttribs !== errorType) {
65489                 propsType = intersectTypes(intrinsicAttribs, propsType);
65490             }
65491             return propsType;
65492         }
65493         function getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation) {
65494             if (sig.unionSignatures) {
65495                 // JSX Elements using the legacy `props`-field based lookup (eg, react class components) need to treat the `props` member as an input
65496                 // instead of an output position when resolving the signature. We need to go back to the input signatures of the composite signature,
65497                 // get the type of `props` on each return type individually, and then _intersect them_, rather than union them (as would normally occur
65498                 // 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.
65499                 // The default behavior of `getTypeOfFirstParameterOfSignatureWithFallback` when no `props` member name is defined is much more sane.
65500                 var results = [];
65501                 for (var _i = 0, _a = sig.unionSignatures; _i < _a.length; _i++) {
65502                     var signature = _a[_i];
65503                     var instance = getReturnTypeOfSignature(signature);
65504                     if (isTypeAny(instance)) {
65505                         return instance;
65506                     }
65507                     var propType = getTypeOfPropertyOfType(instance, forcedLookupLocation);
65508                     if (!propType) {
65509                         return;
65510                     }
65511                     results.push(propType);
65512                 }
65513                 return getIntersectionType(results);
65514             }
65515             var instanceType = getReturnTypeOfSignature(sig);
65516             return isTypeAny(instanceType) ? instanceType : getTypeOfPropertyOfType(instanceType, forcedLookupLocation);
65517         }
65518         function getStaticTypeOfReferencedJsxConstructor(context) {
65519             if (isJsxIntrinsicIdentifier(context.tagName)) {
65520                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(context);
65521                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
65522                 return getOrCreateTypeFromSignature(fakeSignature);
65523             }
65524             var tagType = checkExpressionCached(context.tagName);
65525             if (tagType.flags & 128 /* StringLiteral */) {
65526                 var result = getIntrinsicAttributesTypeFromStringLiteralType(tagType, context);
65527                 if (!result) {
65528                     return errorType;
65529                 }
65530                 var fakeSignature = createSignatureForJSXIntrinsic(context, result);
65531                 return getOrCreateTypeFromSignature(fakeSignature);
65532             }
65533             return tagType;
65534         }
65535         function getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType) {
65536             var managedSym = getJsxLibraryManagedAttributes(ns);
65537             if (managedSym) {
65538                 var declaredManagedType = getDeclaredTypeOfSymbol(managedSym);
65539                 var ctorType = getStaticTypeOfReferencedJsxConstructor(context);
65540                 if (ts.length(declaredManagedType.typeParameters) >= 2) {
65541                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.typeParameters, 2, ts.isInJSFile(context));
65542                     return createTypeReference(declaredManagedType, args);
65543                 }
65544                 else if (ts.length(declaredManagedType.aliasTypeArguments) >= 2) {
65545                     var args = fillMissingTypeArguments([ctorType, attributesType], declaredManagedType.aliasTypeArguments, 2, ts.isInJSFile(context));
65546                     return getTypeAliasInstantiation(declaredManagedType.aliasSymbol, args);
65547                 }
65548             }
65549             return attributesType;
65550         }
65551         function getJsxPropsTypeFromClassType(sig, context) {
65552             var ns = getJsxNamespaceAt(context);
65553             var forcedLookupLocation = getJsxElementPropertiesName(ns);
65554             var attributesType = forcedLookupLocation === undefined
65555                 // If there is no type ElementAttributesProperty, return the type of the first parameter of the signature, which should be the props type
65556                 ? getTypeOfFirstParameterOfSignatureWithFallback(sig, unknownType)
65557                 : forcedLookupLocation === ""
65558                     // If there is no e.g. 'props' member in ElementAttributesProperty, use the element class type instead
65559                     ? getReturnTypeOfSignature(sig)
65560                     // Otherwise get the type of the property on the signature return type
65561                     : getJsxPropsTypeForSignatureFromMember(sig, forcedLookupLocation);
65562             if (!attributesType) {
65563                 // There is no property named 'props' on this instance type
65564                 if (!!forcedLookupLocation && !!ts.length(context.attributes.properties)) {
65565                     error(context, ts.Diagnostics.JSX_element_class_does_not_support_attributes_because_it_does_not_have_a_0_property, ts.unescapeLeadingUnderscores(forcedLookupLocation));
65566                 }
65567                 return unknownType;
65568             }
65569             attributesType = getJsxManagedAttributesFromLocatedAttributes(context, ns, attributesType);
65570             if (isTypeAny(attributesType)) {
65571                 // Props is of type 'any' or unknown
65572                 return attributesType;
65573             }
65574             else {
65575                 // Normal case -- add in IntrinsicClassElements<T> and IntrinsicElements
65576                 var apparentAttributesType = attributesType;
65577                 var intrinsicClassAttribs = getJsxType(JsxNames.IntrinsicClassAttributes, context);
65578                 if (intrinsicClassAttribs !== errorType) {
65579                     var typeParams = getLocalTypeParametersOfClassOrInterfaceOrTypeAlias(intrinsicClassAttribs.symbol);
65580                     var hostClassType = getReturnTypeOfSignature(sig);
65581                     apparentAttributesType = intersectTypes(typeParams
65582                         ? createTypeReference(intrinsicClassAttribs, fillMissingTypeArguments([hostClassType], typeParams, getMinTypeArgumentCount(typeParams), ts.isInJSFile(context)))
65583                         : intrinsicClassAttribs, apparentAttributesType);
65584                 }
65585                 var intrinsicAttribs = getJsxType(JsxNames.IntrinsicAttributes, context);
65586                 if (intrinsicAttribs !== errorType) {
65587                     apparentAttributesType = intersectTypes(intrinsicAttribs, apparentAttributesType);
65588                 }
65589                 return apparentAttributesType;
65590             }
65591         }
65592         // If the given type is an object or union type with a single signature, and if that signature has at
65593         // least as many parameters as the given function, return the signature. Otherwise return undefined.
65594         function getContextualCallSignature(type, node) {
65595             var signatures = getSignaturesOfType(type, 0 /* Call */);
65596             if (signatures.length === 1) {
65597                 var signature = signatures[0];
65598                 if (!isAritySmaller(signature, node)) {
65599                     return signature;
65600                 }
65601             }
65602         }
65603         /** If the contextual signature has fewer parameters than the function expression, do not use it */
65604         function isAritySmaller(signature, target) {
65605             var targetParameterCount = 0;
65606             for (; targetParameterCount < target.parameters.length; targetParameterCount++) {
65607                 var param = target.parameters[targetParameterCount];
65608                 if (param.initializer || param.questionToken || param.dotDotDotToken || isJSDocOptionalParameter(param)) {
65609                     break;
65610                 }
65611             }
65612             if (target.parameters.length && ts.parameterIsThisKeyword(target.parameters[0])) {
65613                 targetParameterCount--;
65614             }
65615             return !hasEffectiveRestParameter(signature) && getParameterCount(signature) < targetParameterCount;
65616         }
65617         function isFunctionExpressionOrArrowFunction(node) {
65618             return node.kind === 208 /* FunctionExpression */ || node.kind === 209 /* ArrowFunction */;
65619         }
65620         function getContextualSignatureForFunctionLikeDeclaration(node) {
65621             // Only function expressions, arrow functions, and object literal methods are contextually typed.
65622             return isFunctionExpressionOrArrowFunction(node) || ts.isObjectLiteralMethod(node)
65623                 ? getContextualSignature(node)
65624                 : undefined;
65625         }
65626         // Return the contextual signature for a given expression node. A contextual type provides a
65627         // contextual signature if it has a single call signature and if that call signature is non-generic.
65628         // If the contextual type is a union type, get the signature from each type possible and if they are
65629         // all identical ignoring their return type, the result is same signature but with return type as
65630         // union type of return types from these signatures
65631         function getContextualSignature(node) {
65632             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
65633             var typeTagSignature = getSignatureOfTypeTag(node);
65634             if (typeTagSignature) {
65635                 return typeTagSignature;
65636             }
65637             var type = getApparentTypeOfContextualType(node, 1 /* Signature */);
65638             if (!type) {
65639                 return undefined;
65640             }
65641             if (!(type.flags & 1048576 /* Union */)) {
65642                 return getContextualCallSignature(type, node);
65643             }
65644             var signatureList;
65645             var types = type.types;
65646             for (var _i = 0, types_18 = types; _i < types_18.length; _i++) {
65647                 var current = types_18[_i];
65648                 var signature = getContextualCallSignature(current, node);
65649                 if (signature) {
65650                     if (!signatureList) {
65651                         // This signature will contribute to contextual union signature
65652                         signatureList = [signature];
65653                     }
65654                     else if (!compareSignaturesIdentical(signatureList[0], signature, /*partialMatch*/ false, /*ignoreThisTypes*/ true, /*ignoreReturnTypes*/ true, compareTypesIdentical)) {
65655                         // Signatures aren't identical, do not use
65656                         return undefined;
65657                     }
65658                     else {
65659                         // Use this signature for contextual union signature
65660                         signatureList.push(signature);
65661                     }
65662                 }
65663             }
65664             // Result is union of signatures collected (return type is union of return types of this signature set)
65665             if (signatureList) {
65666                 return signatureList.length === 1 ? signatureList[0] : createUnionSignature(signatureList[0], signatureList);
65667             }
65668         }
65669         function checkSpreadExpression(node, checkMode) {
65670             if (languageVersion < 2 /* ES2015 */) {
65671                 checkExternalEmitHelpers(node, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
65672             }
65673             var arrayOrIterableType = checkExpression(node.expression, checkMode);
65674             return checkIteratedTypeOrElementType(33 /* Spread */, arrayOrIterableType, undefinedType, node.expression);
65675         }
65676         function checkSyntheticExpression(node) {
65677             return node.isSpread ? getIndexedAccessType(node.type, numberType) : node.type;
65678         }
65679         function hasDefaultValue(node) {
65680             return (node.kind === 198 /* BindingElement */ && !!node.initializer) ||
65681                 (node.kind === 216 /* BinaryExpression */ && node.operatorToken.kind === 62 /* EqualsToken */);
65682         }
65683         function checkArrayLiteral(node, checkMode, forceTuple) {
65684             var elements = node.elements;
65685             var elementCount = elements.length;
65686             var elementTypes = [];
65687             var elementFlags = [];
65688             var contextualType = getApparentTypeOfContextualType(node);
65689             var inDestructuringPattern = ts.isAssignmentTarget(node);
65690             var inConstContext = isConstContext(node);
65691             for (var i = 0; i < elementCount; i++) {
65692                 var e = elements[i];
65693                 if (e.kind === 220 /* SpreadElement */) {
65694                     if (languageVersion < 2 /* ES2015 */) {
65695                         checkExternalEmitHelpers(e, compilerOptions.downlevelIteration ? 1536 /* SpreadIncludes */ : 2048 /* SpreadArrays */);
65696                     }
65697                     var spreadType = checkExpression(e.expression, checkMode, forceTuple);
65698                     if (isArrayLikeType(spreadType)) {
65699                         elementTypes.push(spreadType);
65700                         elementFlags.push(8 /* Variadic */);
65701                     }
65702                     else if (inDestructuringPattern) {
65703                         // Given the following situation:
65704                         //    var c: {};
65705                         //    [...c] = ["", 0];
65706                         //
65707                         // c is represented in the tree as a spread element in an array literal.
65708                         // But c really functions as a rest element, and its purpose is to provide
65709                         // a contextual type for the right hand side of the assignment. Therefore,
65710                         // instead of calling checkExpression on "...c", which will give an error
65711                         // if c is not iterable/array-like, we need to act as if we are trying to
65712                         // get the contextual element type from it. So we do something similar to
65713                         // getContextualTypeForElementExpression, which will crucially not error
65714                         // if there is no index type / iterated type.
65715                         var restElementType = getIndexTypeOfType(spreadType, 1 /* Number */) ||
65716                             getIteratedTypeOrElementType(65 /* Destructuring */, spreadType, undefinedType, /*errorNode*/ undefined, /*checkAssignability*/ false) ||
65717                             unknownType;
65718                         elementTypes.push(restElementType);
65719                         elementFlags.push(4 /* Rest */);
65720                     }
65721                     else {
65722                         elementTypes.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, e.expression));
65723                         elementFlags.push(4 /* Rest */);
65724                     }
65725                 }
65726                 else {
65727                     var elementContextualType = getContextualTypeForElementExpression(contextualType, elementTypes.length);
65728                     var type = checkExpressionForMutableLocation(e, checkMode, elementContextualType, forceTuple);
65729                     elementTypes.push(type);
65730                     elementFlags.push(1 /* Required */);
65731                 }
65732             }
65733             if (inDestructuringPattern) {
65734                 return createTupleType(elementTypes, elementFlags);
65735             }
65736             if (forceTuple || inConstContext || contextualType && forEachType(contextualType, isTupleLikeType)) {
65737                 return createArrayLiteralType(createTupleType(elementTypes, elementFlags, /*readonly*/ inConstContext));
65738             }
65739             return createArrayLiteralType(createArrayType(elementTypes.length ?
65740                 getUnionType(ts.sameMap(elementTypes, function (t, i) { return elementFlags[i] & 8 /* Variadic */ ? getIndexedAccessTypeOrUndefined(t, numberType) || anyType : t; }), 2 /* Subtype */) :
65741                 strictNullChecks ? implicitNeverType : undefinedWideningType, inConstContext));
65742         }
65743         function createArrayLiteralType(type) {
65744             if (!(ts.getObjectFlags(type) & 4 /* Reference */)) {
65745                 return type;
65746             }
65747             var literalType = type.literalType;
65748             if (!literalType) {
65749                 literalType = type.literalType = cloneTypeReference(type);
65750                 literalType.objectFlags |= 65536 /* ArrayLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
65751             }
65752             return literalType;
65753         }
65754         function isNumericName(name) {
65755             switch (name.kind) {
65756                 case 158 /* ComputedPropertyName */:
65757                     return isNumericComputedName(name);
65758                 case 78 /* Identifier */:
65759                     return isNumericLiteralName(name.escapedText);
65760                 case 8 /* NumericLiteral */:
65761                 case 10 /* StringLiteral */:
65762                     return isNumericLiteralName(name.text);
65763                 default:
65764                     return false;
65765             }
65766         }
65767         function isNumericComputedName(name) {
65768             // It seems odd to consider an expression of type Any to result in a numeric name,
65769             // but this behavior is consistent with checkIndexedAccess
65770             return isTypeAssignableToKind(checkComputedPropertyName(name), 296 /* NumberLike */);
65771         }
65772         function isInfinityOrNaNString(name) {
65773             return name === "Infinity" || name === "-Infinity" || name === "NaN";
65774         }
65775         function isNumericLiteralName(name) {
65776             // The intent of numeric names is that
65777             //     - they are names with text in a numeric form, and that
65778             //     - setting properties/indexing with them is always equivalent to doing so with the numeric literal 'numLit',
65779             //         acquired by applying the abstract 'ToNumber' operation on the name's text.
65780             //
65781             // The subtlety is in the latter portion, as we cannot reliably say that anything that looks like a numeric literal is a numeric name.
65782             // In fact, it is the case that the text of the name must be equal to 'ToString(numLit)' for this to hold.
65783             //
65784             // Consider the property name '"0xF00D"'. When one indexes with '0xF00D', they are actually indexing with the value of 'ToString(0xF00D)'
65785             // according to the ECMAScript specification, so it is actually as if the user indexed with the string '"61453"'.
65786             // Thus, the text of all numeric literals equivalent to '61543' such as '0xF00D', '0xf00D', '0170015', etc. are not valid numeric names
65787             // because their 'ToString' representation is not equal to their original text.
65788             // This is motivated by ECMA-262 sections 9.3.1, 9.8.1, 11.1.5, and 11.2.1.
65789             //
65790             // Here, we test whether 'ToString(ToNumber(name))' is exactly equal to 'name'.
65791             // The '+' prefix operator is equivalent here to applying the abstract ToNumber operation.
65792             // Applying the 'toString()' method on a number gives us the abstract ToString operation on a number.
65793             //
65794             // Note that this accepts the values 'Infinity', '-Infinity', and 'NaN', and that this is intentional.
65795             // This is desired behavior, because when indexing with them as numeric entities, you are indexing
65796             // with the strings '"Infinity"', '"-Infinity"', and '"NaN"' respectively.
65797             return (+name).toString() === name;
65798         }
65799         function checkComputedPropertyName(node) {
65800             var links = getNodeLinks(node.expression);
65801             if (!links.resolvedType) {
65802                 links.resolvedType = checkExpression(node.expression);
65803                 // This will allow types number, string, symbol or any. It will also allow enums, the unknown
65804                 // type, and any union of these types (like string | number).
65805                 if (links.resolvedType.flags & 98304 /* Nullable */ ||
65806                     !isTypeAssignableToKind(links.resolvedType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) &&
65807                         !isTypeAssignableTo(links.resolvedType, stringNumberSymbolType)) {
65808                     error(node, ts.Diagnostics.A_computed_property_name_must_be_of_type_string_number_symbol_or_any);
65809                 }
65810                 else {
65811                     checkThatExpressionIsProperSymbolReference(node.expression, links.resolvedType, /*reportError*/ true);
65812                 }
65813             }
65814             return links.resolvedType;
65815         }
65816         function isSymbolWithNumericName(symbol) {
65817             var _a;
65818             var firstDecl = (_a = symbol.declarations) === null || _a === void 0 ? void 0 : _a[0];
65819             return isNumericLiteralName(symbol.escapedName) || (firstDecl && ts.isNamedDeclaration(firstDecl) && isNumericName(firstDecl.name));
65820         }
65821         function getObjectLiteralIndexInfo(node, offset, properties, kind) {
65822             var propTypes = [];
65823             for (var i = offset; i < properties.length; i++) {
65824                 if (kind === 0 /* String */ || isSymbolWithNumericName(properties[i])) {
65825                     propTypes.push(getTypeOfSymbol(properties[i]));
65826                 }
65827             }
65828             var unionType = propTypes.length ? getUnionType(propTypes, 2 /* Subtype */) : undefinedType;
65829             return createIndexInfo(unionType, isConstContext(node));
65830         }
65831         function getImmediateAliasedSymbol(symbol) {
65832             ts.Debug.assert((symbol.flags & 2097152 /* Alias */) !== 0, "Should only get Alias here.");
65833             var links = getSymbolLinks(symbol);
65834             if (!links.immediateTarget) {
65835                 var node = getDeclarationOfAliasSymbol(symbol);
65836                 if (!node)
65837                     return ts.Debug.fail();
65838                 links.immediateTarget = getTargetOfAliasDeclaration(node, /*dontRecursivelyResolve*/ true);
65839             }
65840             return links.immediateTarget;
65841         }
65842         function checkObjectLiteral(node, checkMode) {
65843             var inDestructuringPattern = ts.isAssignmentTarget(node);
65844             // Grammar checking
65845             checkGrammarObjectLiteralExpression(node, inDestructuringPattern);
65846             var allPropertiesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
65847             var propertiesTable = ts.createSymbolTable();
65848             var propertiesArray = [];
65849             var spread = emptyObjectType;
65850             var contextualType = getApparentTypeOfContextualType(node);
65851             var contextualTypeHasPattern = contextualType && contextualType.pattern &&
65852                 (contextualType.pattern.kind === 196 /* ObjectBindingPattern */ || contextualType.pattern.kind === 200 /* ObjectLiteralExpression */);
65853             var inConstContext = isConstContext(node);
65854             var checkFlags = inConstContext ? 8 /* Readonly */ : 0;
65855             var isInJavascript = ts.isInJSFile(node) && !ts.isInJsonFile(node);
65856             var enumTag = ts.getJSDocEnumTag(node);
65857             var isJSObjectLiteral = !contextualType && isInJavascript && !enumTag;
65858             var objectFlags = freshObjectLiteralFlag;
65859             var patternWithComputedProperties = false;
65860             var hasComputedStringProperty = false;
65861             var hasComputedNumberProperty = false;
65862             // Spreads may cause an early bail; ensure computed names are always checked (this is cached)
65863             // As otherwise they may not be checked until exports for the type at this position are retrieved,
65864             // which may never occur.
65865             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
65866                 var elem = _a[_i];
65867                 if (elem.name && ts.isComputedPropertyName(elem.name) && !ts.isWellKnownSymbolSyntactically(elem.name)) {
65868                     checkComputedPropertyName(elem.name);
65869                 }
65870             }
65871             var offset = 0;
65872             for (var _b = 0, _c = node.properties; _b < _c.length; _b++) {
65873                 var memberDecl = _c[_b];
65874                 var member = getSymbolOfNode(memberDecl);
65875                 var computedNameType = memberDecl.name && memberDecl.name.kind === 158 /* ComputedPropertyName */ && !ts.isWellKnownSymbolSyntactically(memberDecl.name.expression) ?
65876                     checkComputedPropertyName(memberDecl.name) : undefined;
65877                 if (memberDecl.kind === 288 /* PropertyAssignment */ ||
65878                     memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ||
65879                     ts.isObjectLiteralMethod(memberDecl)) {
65880                     var type = memberDecl.kind === 288 /* PropertyAssignment */ ? checkPropertyAssignment(memberDecl, checkMode) :
65881                         // avoid resolving the left side of the ShorthandPropertyAssignment outside of the destructuring
65882                         // for error recovery purposes. For example, if a user wrote `{ a = 100 }` instead of `{ a: 100 }`.
65883                         // we don't want to say "could not find 'a'".
65884                         memberDecl.kind === 289 /* ShorthandPropertyAssignment */ ? checkExpressionForMutableLocation(!inDestructuringPattern && memberDecl.objectAssignmentInitializer ? memberDecl.objectAssignmentInitializer : memberDecl.name, checkMode) :
65885                             checkObjectLiteralMethod(memberDecl, checkMode);
65886                     if (isInJavascript) {
65887                         var jsDocType = getTypeForDeclarationFromJSDocComment(memberDecl);
65888                         if (jsDocType) {
65889                             checkTypeAssignableTo(type, jsDocType, memberDecl);
65890                             type = jsDocType;
65891                         }
65892                         else if (enumTag && enumTag.typeExpression) {
65893                             checkTypeAssignableTo(type, getTypeFromTypeNode(enumTag.typeExpression), memberDecl);
65894                         }
65895                     }
65896                     objectFlags |= ts.getObjectFlags(type) & 3670016 /* PropagatingFlags */;
65897                     var nameType = computedNameType && isTypeUsableAsPropertyName(computedNameType) ? computedNameType : undefined;
65898                     var prop = nameType ?
65899                         createSymbol(4 /* Property */ | member.flags, getPropertyNameFromType(nameType), checkFlags | 4096 /* Late */) :
65900                         createSymbol(4 /* Property */ | member.flags, member.escapedName, checkFlags);
65901                     if (nameType) {
65902                         prop.nameType = nameType;
65903                     }
65904                     if (inDestructuringPattern) {
65905                         // If object literal is an assignment pattern and if the assignment pattern specifies a default value
65906                         // for the property, make the property optional.
65907                         var isOptional = (memberDecl.kind === 288 /* PropertyAssignment */ && hasDefaultValue(memberDecl.initializer)) ||
65908                             (memberDecl.kind === 289 /* ShorthandPropertyAssignment */ && memberDecl.objectAssignmentInitializer);
65909                         if (isOptional) {
65910                             prop.flags |= 16777216 /* Optional */;
65911                         }
65912                     }
65913                     else if (contextualTypeHasPattern && !(ts.getObjectFlags(contextualType) & 512 /* ObjectLiteralPatternWithComputedProperties */)) {
65914                         // If object literal is contextually typed by the implied type of a binding pattern, and if the
65915                         // binding pattern specifies a default value for the property, make the property optional.
65916                         var impliedProp = getPropertyOfType(contextualType, member.escapedName);
65917                         if (impliedProp) {
65918                             prop.flags |= impliedProp.flags & 16777216 /* Optional */;
65919                         }
65920                         else if (!compilerOptions.suppressExcessPropertyErrors && !getIndexInfoOfType(contextualType, 0 /* String */)) {
65921                             error(memberDecl.name, ts.Diagnostics.Object_literal_may_only_specify_known_properties_and_0_does_not_exist_in_type_1, symbolToString(member), typeToString(contextualType));
65922                         }
65923                     }
65924                     prop.declarations = member.declarations;
65925                     prop.parent = member.parent;
65926                     if (member.valueDeclaration) {
65927                         prop.valueDeclaration = member.valueDeclaration;
65928                     }
65929                     prop.type = type;
65930                     prop.target = member;
65931                     member = prop;
65932                     allPropertiesTable === null || allPropertiesTable === void 0 ? void 0 : allPropertiesTable.set(prop.escapedName, prop);
65933                 }
65934                 else if (memberDecl.kind === 290 /* SpreadAssignment */) {
65935                     if (languageVersion < 2 /* ES2015 */) {
65936                         checkExternalEmitHelpers(memberDecl, 2 /* Assign */);
65937                     }
65938                     if (propertiesArray.length > 0) {
65939                         spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
65940                         propertiesArray = [];
65941                         propertiesTable = ts.createSymbolTable();
65942                         hasComputedStringProperty = false;
65943                         hasComputedNumberProperty = false;
65944                     }
65945                     var type = getReducedType(checkExpression(memberDecl.expression));
65946                     if (!isValidSpreadType(type)) {
65947                         error(memberDecl, ts.Diagnostics.Spread_types_may_only_be_created_from_object_types);
65948                         return errorType;
65949                     }
65950                     if (allPropertiesTable) {
65951                         checkSpreadPropOverrides(type, allPropertiesTable, memberDecl);
65952                     }
65953                     spread = getSpreadType(spread, type, node.symbol, objectFlags, inConstContext);
65954                     offset = propertiesArray.length;
65955                     continue;
65956                 }
65957                 else {
65958                     // TypeScript 1.0 spec (April 2014)
65959                     // A get accessor declaration is processed in the same manner as
65960                     // an ordinary function declaration(section 6.1) with no parameters.
65961                     // A set accessor declaration is processed in the same manner
65962                     // as an ordinary function declaration with a single parameter and a Void return type.
65963                     ts.Debug.assert(memberDecl.kind === 167 /* GetAccessor */ || memberDecl.kind === 168 /* SetAccessor */);
65964                     checkNodeDeferred(memberDecl);
65965                 }
65966                 if (computedNameType && !(computedNameType.flags & 8576 /* StringOrNumberLiteralOrUnique */)) {
65967                     if (isTypeAssignableTo(computedNameType, stringNumberSymbolType)) {
65968                         if (isTypeAssignableTo(computedNameType, numberType)) {
65969                             hasComputedNumberProperty = true;
65970                         }
65971                         else {
65972                             hasComputedStringProperty = true;
65973                         }
65974                         if (inDestructuringPattern) {
65975                             patternWithComputedProperties = true;
65976                         }
65977                     }
65978                 }
65979                 else {
65980                     propertiesTable.set(member.escapedName, member);
65981                 }
65982                 propertiesArray.push(member);
65983             }
65984             // If object literal is contextually typed by the implied type of a binding pattern, augment the result
65985             // type with those properties for which the binding pattern specifies a default value.
65986             // If the object literal is spread into another object literal, skip this step and let the top-level object
65987             // literal handle it instead.
65988             if (contextualTypeHasPattern && node.parent.kind !== 290 /* SpreadAssignment */) {
65989                 for (var _d = 0, _e = getPropertiesOfType(contextualType); _d < _e.length; _d++) {
65990                     var prop = _e[_d];
65991                     if (!propertiesTable.get(prop.escapedName) && !getPropertyOfType(spread, prop.escapedName)) {
65992                         if (!(prop.flags & 16777216 /* Optional */)) {
65993                             error(prop.valueDeclaration || prop.bindingElement, ts.Diagnostics.Initializer_provides_no_value_for_this_binding_element_and_the_binding_element_has_no_default_value);
65994                         }
65995                         propertiesTable.set(prop.escapedName, prop);
65996                         propertiesArray.push(prop);
65997                     }
65998                 }
65999             }
66000             if (spread !== emptyObjectType) {
66001                 if (propertiesArray.length > 0) {
66002                     spread = getSpreadType(spread, createObjectLiteralType(), node.symbol, objectFlags, inConstContext);
66003                     propertiesArray = [];
66004                     propertiesTable = ts.createSymbolTable();
66005                     hasComputedStringProperty = false;
66006                     hasComputedNumberProperty = false;
66007                 }
66008                 // remap the raw emptyObjectType fed in at the top into a fresh empty object literal type, unique to this use site
66009                 return mapType(spread, function (t) { return t === emptyObjectType ? createObjectLiteralType() : t; });
66010             }
66011             return createObjectLiteralType();
66012             function createObjectLiteralType() {
66013                 var stringIndexInfo = hasComputedStringProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 0 /* String */) : undefined;
66014                 var numberIndexInfo = hasComputedNumberProperty ? getObjectLiteralIndexInfo(node, offset, propertiesArray, 1 /* Number */) : undefined;
66015                 var result = createAnonymousType(node.symbol, propertiesTable, ts.emptyArray, ts.emptyArray, stringIndexInfo, numberIndexInfo);
66016                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
66017                 if (isJSObjectLiteral) {
66018                     result.objectFlags |= 16384 /* JSLiteral */;
66019                 }
66020                 if (patternWithComputedProperties) {
66021                     result.objectFlags |= 512 /* ObjectLiteralPatternWithComputedProperties */;
66022                 }
66023                 if (inDestructuringPattern) {
66024                     result.pattern = node;
66025                 }
66026                 return result;
66027             }
66028         }
66029         function isValidSpreadType(type) {
66030             if (type.flags & 465829888 /* Instantiable */) {
66031                 var constraint = getBaseConstraintOfType(type);
66032                 if (constraint !== undefined) {
66033                     return isValidSpreadType(constraint);
66034                 }
66035             }
66036             return !!(type.flags & (1 /* Any */ | 67108864 /* NonPrimitive */ | 524288 /* Object */ | 58982400 /* InstantiableNonPrimitive */) ||
66037                 getFalsyFlags(type) & 117632 /* DefinitelyFalsy */ && isValidSpreadType(removeDefinitelyFalsyTypes(type)) ||
66038                 type.flags & 3145728 /* UnionOrIntersection */ && ts.every(type.types, isValidSpreadType));
66039         }
66040         function checkJsxSelfClosingElementDeferred(node) {
66041             checkJsxOpeningLikeElementOrOpeningFragment(node);
66042         }
66043         function checkJsxSelfClosingElement(node, _checkMode) {
66044             checkNodeDeferred(node);
66045             return getJsxElementTypeAt(node) || anyType;
66046         }
66047         function checkJsxElementDeferred(node) {
66048             // Check attributes
66049             checkJsxOpeningLikeElementOrOpeningFragment(node.openingElement);
66050             // Perform resolution on the closing tag so that rename/go to definition/etc work
66051             if (isJsxIntrinsicIdentifier(node.closingElement.tagName)) {
66052                 getIntrinsicTagSymbol(node.closingElement);
66053             }
66054             else {
66055                 checkExpression(node.closingElement.tagName);
66056             }
66057             checkJsxChildren(node);
66058         }
66059         function checkJsxElement(node, _checkMode) {
66060             checkNodeDeferred(node);
66061             return getJsxElementTypeAt(node) || anyType;
66062         }
66063         function checkJsxFragment(node) {
66064             checkJsxOpeningLikeElementOrOpeningFragment(node.openingFragment);
66065             // by default, jsx:'react' will use jsxFactory = React.createElement and jsxFragmentFactory = React.Fragment
66066             // if jsxFactory compiler option is provided, ensure jsxFragmentFactory compiler option or @jsxFrag pragma is provided too
66067             var nodeSourceFile = ts.getSourceFileOfNode(node);
66068             if (ts.getJSXTransformEnabled(compilerOptions) && (compilerOptions.jsxFactory || nodeSourceFile.pragmas.has("jsx"))
66069                 && !compilerOptions.jsxFragmentFactory && !nodeSourceFile.pragmas.has("jsxfrag")) {
66070                 error(node, compilerOptions.jsxFactory
66071                     ? ts.Diagnostics.The_jsxFragmentFactory_compiler_option_must_be_provided_to_use_JSX_fragments_with_the_jsxFactory_compiler_option
66072                     : ts.Diagnostics.An_jsxFrag_pragma_is_required_when_using_an_jsx_pragma_with_JSX_fragments);
66073             }
66074             checkJsxChildren(node);
66075             return getJsxElementTypeAt(node) || anyType;
66076         }
66077         /**
66078          * Returns true iff the JSX element name would be a valid JS identifier, ignoring restrictions about keywords not being identifiers
66079          */
66080         function isUnhyphenatedJsxName(name) {
66081             // - is the only character supported in JSX attribute names that isn't valid in JavaScript identifiers
66082             return !ts.stringContains(name, "-");
66083         }
66084         /**
66085          * Returns true iff React would emit this tag name as a string rather than an identifier or qualified name
66086          */
66087         function isJsxIntrinsicIdentifier(tagName) {
66088             return tagName.kind === 78 /* Identifier */ && ts.isIntrinsicJsxName(tagName.escapedText);
66089         }
66090         function checkJsxAttribute(node, checkMode) {
66091             return node.initializer
66092                 ? checkExpressionForMutableLocation(node.initializer, checkMode)
66093                 : trueType; // <Elem attr /> is sugar for <Elem attr={true} />
66094         }
66095         /**
66096          * Get attributes type of the JSX opening-like element. The result is from resolving "attributes" property of the opening-like element.
66097          *
66098          * @param openingLikeElement a JSX opening-like element
66099          * @param filter a function to remove attributes that will not participate in checking whether attributes are assignable
66100          * @return an anonymous type (similar to the one returned by checkObjectLiteral) in which its properties are attributes property.
66101          * @remarks Because this function calls getSpreadType, it needs to use the same checks as checkObjectLiteral,
66102          * which also calls getSpreadType.
66103          */
66104         function createJsxAttributesTypeFromAttributesProperty(openingLikeElement, checkMode) {
66105             var attributes = openingLikeElement.attributes;
66106             var allAttributesTable = strictNullChecks ? ts.createSymbolTable() : undefined;
66107             var attributesTable = ts.createSymbolTable();
66108             var spread = emptyJsxObjectType;
66109             var hasSpreadAnyType = false;
66110             var typeToIntersect;
66111             var explicitlySpecifyChildrenAttribute = false;
66112             var objectFlags = 4096 /* JsxAttributes */;
66113             var jsxChildrenPropertyName = getJsxElementChildrenPropertyName(getJsxNamespaceAt(openingLikeElement));
66114             for (var _i = 0, _a = attributes.properties; _i < _a.length; _i++) {
66115                 var attributeDecl = _a[_i];
66116                 var member = attributeDecl.symbol;
66117                 if (ts.isJsxAttribute(attributeDecl)) {
66118                     var exprType = checkJsxAttribute(attributeDecl, checkMode);
66119                     objectFlags |= ts.getObjectFlags(exprType) & 3670016 /* PropagatingFlags */;
66120                     var attributeSymbol = createSymbol(4 /* Property */ | member.flags, member.escapedName);
66121                     attributeSymbol.declarations = member.declarations;
66122                     attributeSymbol.parent = member.parent;
66123                     if (member.valueDeclaration) {
66124                         attributeSymbol.valueDeclaration = member.valueDeclaration;
66125                     }
66126                     attributeSymbol.type = exprType;
66127                     attributeSymbol.target = member;
66128                     attributesTable.set(attributeSymbol.escapedName, attributeSymbol);
66129                     allAttributesTable === null || allAttributesTable === void 0 ? void 0 : allAttributesTable.set(attributeSymbol.escapedName, attributeSymbol);
66130                     if (attributeDecl.name.escapedText === jsxChildrenPropertyName) {
66131                         explicitlySpecifyChildrenAttribute = true;
66132                     }
66133                 }
66134                 else {
66135                     ts.Debug.assert(attributeDecl.kind === 282 /* JsxSpreadAttribute */);
66136                     if (attributesTable.size > 0) {
66137                         spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
66138                         attributesTable = ts.createSymbolTable();
66139                     }
66140                     var exprType = getReducedType(checkExpressionCached(attributeDecl.expression, checkMode));
66141                     if (isTypeAny(exprType)) {
66142                         hasSpreadAnyType = true;
66143                     }
66144                     if (isValidSpreadType(exprType)) {
66145                         spread = getSpreadType(spread, exprType, attributes.symbol, objectFlags, /*readonly*/ false);
66146                         if (allAttributesTable) {
66147                             checkSpreadPropOverrides(exprType, allAttributesTable, attributeDecl);
66148                         }
66149                     }
66150                     else {
66151                         typeToIntersect = typeToIntersect ? getIntersectionType([typeToIntersect, exprType]) : exprType;
66152                     }
66153                 }
66154             }
66155             if (!hasSpreadAnyType) {
66156                 if (attributesTable.size > 0) {
66157                     spread = getSpreadType(spread, createJsxAttributesType(), attributes.symbol, objectFlags, /*readonly*/ false);
66158                 }
66159             }
66160             // Handle children attribute
66161             var parent = openingLikeElement.parent.kind === 273 /* JsxElement */ ? openingLikeElement.parent : undefined;
66162             // We have to check that openingElement of the parent is the one we are visiting as this may not be true for selfClosingElement
66163             if (parent && parent.openingElement === openingLikeElement && parent.children.length > 0) {
66164                 var childrenTypes = checkJsxChildren(parent, checkMode);
66165                 if (!hasSpreadAnyType && jsxChildrenPropertyName && jsxChildrenPropertyName !== "") {
66166                     // Error if there is a attribute named "children" explicitly specified and children element.
66167                     // This is because children element will overwrite the value from attributes.
66168                     // Note: we will not warn "children" attribute overwritten if "children" attribute is specified in object spread.
66169                     if (explicitlySpecifyChildrenAttribute) {
66170                         error(attributes, ts.Diagnostics._0_are_specified_twice_The_attribute_named_0_will_be_overwritten, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName));
66171                     }
66172                     var contextualType = getApparentTypeOfContextualType(openingLikeElement.attributes);
66173                     var childrenContextualType = contextualType && getTypeOfPropertyOfContextualType(contextualType, jsxChildrenPropertyName);
66174                     // 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
66175                     var childrenPropSymbol = createSymbol(4 /* Property */, jsxChildrenPropertyName);
66176                     childrenPropSymbol.type = childrenTypes.length === 1 ? childrenTypes[0] :
66177                         childrenContextualType && forEachType(childrenContextualType, isTupleLikeType) ? createTupleType(childrenTypes) :
66178                             createArrayType(getUnionType(childrenTypes));
66179                     // Fake up a property declaration for the children
66180                     childrenPropSymbol.valueDeclaration = ts.factory.createPropertySignature(/*modifiers*/ undefined, ts.unescapeLeadingUnderscores(jsxChildrenPropertyName), /*questionToken*/ undefined, /*type*/ undefined);
66181                     ts.setParent(childrenPropSymbol.valueDeclaration, attributes);
66182                     childrenPropSymbol.valueDeclaration.symbol = childrenPropSymbol;
66183                     var childPropMap = ts.createSymbolTable();
66184                     childPropMap.set(jsxChildrenPropertyName, childrenPropSymbol);
66185                     spread = getSpreadType(spread, createAnonymousType(attributes.symbol, childPropMap, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined), attributes.symbol, objectFlags, /*readonly*/ false);
66186                 }
66187             }
66188             if (hasSpreadAnyType) {
66189                 return anyType;
66190             }
66191             if (typeToIntersect && spread !== emptyJsxObjectType) {
66192                 return getIntersectionType([typeToIntersect, spread]);
66193             }
66194             return typeToIntersect || (spread === emptyJsxObjectType ? createJsxAttributesType() : spread);
66195             /**
66196              * Create anonymous type from given attributes symbol table.
66197              * @param symbol a symbol of JsxAttributes containing attributes corresponding to attributesTable
66198              * @param attributesTable a symbol table of attributes property
66199              */
66200             function createJsxAttributesType() {
66201                 objectFlags |= freshObjectLiteralFlag;
66202                 var result = createAnonymousType(attributes.symbol, attributesTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
66203                 result.objectFlags |= objectFlags | 128 /* ObjectLiteral */ | 1048576 /* ContainsObjectOrArrayLiteral */;
66204                 return result;
66205             }
66206         }
66207         function checkJsxChildren(node, checkMode) {
66208             var childrenTypes = [];
66209             for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
66210                 var child = _a[_i];
66211                 // In React, JSX text that contains only whitespaces will be ignored so we don't want to type-check that
66212                 // because then type of children property will have constituent of string type.
66213                 if (child.kind === 11 /* JsxText */) {
66214                     if (!child.containsOnlyTriviaWhiteSpaces) {
66215                         childrenTypes.push(stringType);
66216                     }
66217                 }
66218                 else if (child.kind === 283 /* JsxExpression */ && !child.expression) {
66219                     continue; // empty jsx expressions don't *really* count as present children
66220                 }
66221                 else {
66222                     childrenTypes.push(checkExpressionForMutableLocation(child, checkMode));
66223                 }
66224             }
66225             return childrenTypes;
66226         }
66227         function checkSpreadPropOverrides(type, props, spread) {
66228             for (var _i = 0, _a = getPropertiesOfType(type); _i < _a.length; _i++) {
66229                 var right = _a[_i];
66230                 var left = props.get(right.escapedName);
66231                 var rightType = getTypeOfSymbol(right);
66232                 if (left && !maybeTypeOfKind(rightType, 98304 /* Nullable */) && !(maybeTypeOfKind(rightType, 3 /* AnyOrUnknown */) && right.flags & 16777216 /* Optional */)) {
66233                     var diagnostic = error(left.valueDeclaration, ts.Diagnostics._0_is_specified_more_than_once_so_this_usage_will_be_overwritten, ts.unescapeLeadingUnderscores(left.escapedName));
66234                     ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(spread, ts.Diagnostics.This_spread_always_overwrites_this_property));
66235                 }
66236             }
66237         }
66238         /**
66239          * Check attributes property of opening-like element. This function is called during chooseOverload to get call signature of a JSX opening-like element.
66240          * (See "checkApplicableSignatureForJsxOpeningLikeElement" for how the function is used)
66241          * @param node a JSXAttributes to be resolved of its type
66242          */
66243         function checkJsxAttributes(node, checkMode) {
66244             return createJsxAttributesTypeFromAttributesProperty(node.parent, checkMode);
66245         }
66246         function getJsxType(name, location) {
66247             var namespace = getJsxNamespaceAt(location);
66248             var exports = namespace && getExportsOfSymbol(namespace);
66249             var typeSymbol = exports && getSymbol(exports, name, 788968 /* Type */);
66250             return typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType;
66251         }
66252         /**
66253          * Looks up an intrinsic tag name and returns a symbol that either points to an intrinsic
66254          * property (in which case nodeLinks.jsxFlags will be IntrinsicNamedElement) or an intrinsic
66255          * string index signature (in which case nodeLinks.jsxFlags will be IntrinsicIndexedElement).
66256          * May also return unknownSymbol if both of these lookups fail.
66257          */
66258         function getIntrinsicTagSymbol(node) {
66259             var links = getNodeLinks(node);
66260             if (!links.resolvedSymbol) {
66261                 var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, node);
66262                 if (intrinsicElementsType !== errorType) {
66263                     // Property case
66264                     if (!ts.isIdentifier(node.tagName))
66265                         return ts.Debug.fail();
66266                     var intrinsicProp = getPropertyOfType(intrinsicElementsType, node.tagName.escapedText);
66267                     if (intrinsicProp) {
66268                         links.jsxFlags |= 1 /* IntrinsicNamedElement */;
66269                         return links.resolvedSymbol = intrinsicProp;
66270                     }
66271                     // Intrinsic string indexer case
66272                     var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
66273                     if (indexSignatureType) {
66274                         links.jsxFlags |= 2 /* IntrinsicIndexedElement */;
66275                         return links.resolvedSymbol = intrinsicElementsType.symbol;
66276                     }
66277                     // Wasn't found
66278                     error(node, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.idText(node.tagName), "JSX." + JsxNames.IntrinsicElements);
66279                     return links.resolvedSymbol = unknownSymbol;
66280                 }
66281                 else {
66282                     if (noImplicitAny) {
66283                         error(node, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_no_interface_JSX_0_exists, ts.unescapeLeadingUnderscores(JsxNames.IntrinsicElements));
66284                     }
66285                     return links.resolvedSymbol = unknownSymbol;
66286                 }
66287             }
66288             return links.resolvedSymbol;
66289         }
66290         function getJsxNamespaceContainerForImplicitImport(location) {
66291             var file = location && ts.getSourceFileOfNode(location);
66292             var links = file && getNodeLinks(file);
66293             if (links && links.jsxImplicitImportContainer === false) {
66294                 return undefined;
66295             }
66296             if (links && links.jsxImplicitImportContainer) {
66297                 return links.jsxImplicitImportContainer;
66298             }
66299             var runtimeImportSpecifier = ts.getJSXRuntimeImport(ts.getJSXImplicitImportBase(compilerOptions, file), compilerOptions);
66300             if (!runtimeImportSpecifier) {
66301                 return undefined;
66302             }
66303             var isClassic = ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.Classic;
66304             var errorMessage = isClassic
66305                 ? ts.Diagnostics.Cannot_find_module_0_Did_you_mean_to_set_the_moduleResolution_option_to_node_or_to_add_aliases_to_the_paths_option
66306                 : ts.Diagnostics.Cannot_find_module_0_or_its_corresponding_type_declarations;
66307             var mod = resolveExternalModule(location, runtimeImportSpecifier, errorMessage, location);
66308             var result = mod && mod !== unknownSymbol ? getMergedSymbol(resolveSymbol(mod)) : undefined;
66309             if (links) {
66310                 links.jsxImplicitImportContainer = result || false;
66311             }
66312             return result;
66313         }
66314         function getJsxNamespaceAt(location) {
66315             var links = location && getNodeLinks(location);
66316             if (links && links.jsxNamespace) {
66317                 return links.jsxNamespace;
66318             }
66319             if (!links || links.jsxNamespace !== false) {
66320                 var resolvedNamespace = getJsxNamespaceContainerForImplicitImport(location);
66321                 if (!resolvedNamespace || resolvedNamespace === unknownSymbol) {
66322                     var namespaceName = getJsxNamespace(location);
66323                     resolvedNamespace = resolveName(location, namespaceName, 1920 /* Namespace */, /*diagnosticMessage*/ undefined, namespaceName, /*isUse*/ false);
66324                 }
66325                 if (resolvedNamespace) {
66326                     var candidate = resolveSymbol(getSymbol(getExportsOfSymbol(resolveSymbol(resolvedNamespace)), JsxNames.JSX, 1920 /* Namespace */));
66327                     if (candidate && candidate !== unknownSymbol) {
66328                         if (links) {
66329                             links.jsxNamespace = candidate;
66330                         }
66331                         return candidate;
66332                     }
66333                 }
66334                 if (links) {
66335                     links.jsxNamespace = false;
66336                 }
66337             }
66338             // JSX global fallback
66339             var s = resolveSymbol(getGlobalSymbol(JsxNames.JSX, 1920 /* Namespace */, /*diagnosticMessage*/ undefined));
66340             if (s === unknownSymbol) {
66341                 return undefined; // TODO: GH#18217
66342             }
66343             return s; // TODO: GH#18217
66344         }
66345         /**
66346          * Look into JSX namespace and then look for container with matching name as nameOfAttribPropContainer.
66347          * Get a single property from that container if existed. Report an error if there are more than one property.
66348          *
66349          * @param nameOfAttribPropContainer a string of value JsxNames.ElementAttributesPropertyNameContainer or JsxNames.ElementChildrenAttributeNameContainer
66350          *          if other string is given or the container doesn't exist, return undefined.
66351          */
66352         function getNameFromJsxElementAttributesContainer(nameOfAttribPropContainer, jsxNamespace) {
66353             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [symbol]
66354             var jsxElementAttribPropInterfaceSym = jsxNamespace && getSymbol(jsxNamespace.exports, nameOfAttribPropContainer, 788968 /* Type */);
66355             // JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute [type]
66356             var jsxElementAttribPropInterfaceType = jsxElementAttribPropInterfaceSym && getDeclaredTypeOfSymbol(jsxElementAttribPropInterfaceSym);
66357             // The properties of JSX.ElementAttributesProperty | JSX.ElementChildrenAttribute
66358             var propertiesOfJsxElementAttribPropInterface = jsxElementAttribPropInterfaceType && getPropertiesOfType(jsxElementAttribPropInterfaceType);
66359             if (propertiesOfJsxElementAttribPropInterface) {
66360                 // Element Attributes has zero properties, so the element attributes type will be the class instance type
66361                 if (propertiesOfJsxElementAttribPropInterface.length === 0) {
66362                     return "";
66363                 }
66364                 // Element Attributes has one property, so the element attributes type will be the type of the corresponding
66365                 // property of the class instance type
66366                 else if (propertiesOfJsxElementAttribPropInterface.length === 1) {
66367                     return propertiesOfJsxElementAttribPropInterface[0].escapedName;
66368                 }
66369                 else if (propertiesOfJsxElementAttribPropInterface.length > 1) {
66370                     // More than one property on ElementAttributesProperty is an error
66371                     error(jsxElementAttribPropInterfaceSym.declarations[0], ts.Diagnostics.The_global_type_JSX_0_may_not_have_more_than_one_property, ts.unescapeLeadingUnderscores(nameOfAttribPropContainer));
66372                 }
66373             }
66374             return undefined;
66375         }
66376         function getJsxLibraryManagedAttributes(jsxNamespace) {
66377             // JSX.LibraryManagedAttributes [symbol]
66378             return jsxNamespace && getSymbol(jsxNamespace.exports, JsxNames.LibraryManagedAttributes, 788968 /* Type */);
66379         }
66380         /// e.g. "props" for React.d.ts,
66381         /// or 'undefined' if ElementAttributesProperty doesn't exist (which means all
66382         ///     non-intrinsic elements' attributes type is 'any'),
66383         /// or '' if it has 0 properties (which means every
66384         ///     non-intrinsic elements' attributes type is the element instance type)
66385         function getJsxElementPropertiesName(jsxNamespace) {
66386             return getNameFromJsxElementAttributesContainer(JsxNames.ElementAttributesPropertyNameContainer, jsxNamespace);
66387         }
66388         function getJsxElementChildrenPropertyName(jsxNamespace) {
66389             return getNameFromJsxElementAttributesContainer(JsxNames.ElementChildrenAttributeNameContainer, jsxNamespace);
66390         }
66391         function getUninstantiatedJsxSignaturesOfType(elementType, caller) {
66392             if (elementType.flags & 4 /* String */) {
66393                 return [anySignature];
66394             }
66395             else if (elementType.flags & 128 /* StringLiteral */) {
66396                 var intrinsicType = getIntrinsicAttributesTypeFromStringLiteralType(elementType, caller);
66397                 if (!intrinsicType) {
66398                     error(caller, ts.Diagnostics.Property_0_does_not_exist_on_type_1, elementType.value, "JSX." + JsxNames.IntrinsicElements);
66399                     return ts.emptyArray;
66400                 }
66401                 else {
66402                     var fakeSignature = createSignatureForJSXIntrinsic(caller, intrinsicType);
66403                     return [fakeSignature];
66404                 }
66405             }
66406             var apparentElemType = getApparentType(elementType);
66407             // Resolve the signatures, preferring constructor
66408             var signatures = getSignaturesOfType(apparentElemType, 1 /* Construct */);
66409             if (signatures.length === 0) {
66410                 // No construct signatures, try call signatures
66411                 signatures = getSignaturesOfType(apparentElemType, 0 /* Call */);
66412             }
66413             if (signatures.length === 0 && apparentElemType.flags & 1048576 /* Union */) {
66414                 // If each member has some combination of new/call signatures; make a union signature list for those
66415                 signatures = getUnionSignatures(ts.map(apparentElemType.types, function (t) { return getUninstantiatedJsxSignaturesOfType(t, caller); }));
66416             }
66417             return signatures;
66418         }
66419         function getIntrinsicAttributesTypeFromStringLiteralType(type, location) {
66420             // 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
66421             // For example:
66422             //      var CustomTag: "h1" = "h1";
66423             //      <CustomTag> Hello World </CustomTag>
66424             var intrinsicElementsType = getJsxType(JsxNames.IntrinsicElements, location);
66425             if (intrinsicElementsType !== errorType) {
66426                 var stringLiteralTypeName = type.value;
66427                 var intrinsicProp = getPropertyOfType(intrinsicElementsType, ts.escapeLeadingUnderscores(stringLiteralTypeName));
66428                 if (intrinsicProp) {
66429                     return getTypeOfSymbol(intrinsicProp);
66430                 }
66431                 var indexSignatureType = getIndexTypeOfType(intrinsicElementsType, 0 /* String */);
66432                 if (indexSignatureType) {
66433                     return indexSignatureType;
66434                 }
66435                 return undefined;
66436             }
66437             // If we need to report an error, we already done so here. So just return any to prevent any more error downstream
66438             return anyType;
66439         }
66440         function checkJsxReturnAssignableToAppropriateBound(refKind, elemInstanceType, openingLikeElement) {
66441             if (refKind === 1 /* Function */) {
66442                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
66443                 if (sfcReturnConstraint) {
66444                     checkTypeRelatedTo(elemInstanceType, sfcReturnConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_return_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
66445                 }
66446             }
66447             else if (refKind === 0 /* Component */) {
66448                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
66449                 if (classConstraint) {
66450                     // Issue an error if this return type isn't assignable to JSX.ElementClass, failing that
66451                     checkTypeRelatedTo(elemInstanceType, classConstraint, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_instance_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
66452                 }
66453             }
66454             else { // Mixed
66455                 var sfcReturnConstraint = getJsxStatelessElementTypeAt(openingLikeElement);
66456                 var classConstraint = getJsxElementClassTypeAt(openingLikeElement);
66457                 if (!sfcReturnConstraint || !classConstraint) {
66458                     return;
66459                 }
66460                 var combined = getUnionType([sfcReturnConstraint, classConstraint]);
66461                 checkTypeRelatedTo(elemInstanceType, combined, assignableRelation, openingLikeElement.tagName, ts.Diagnostics.Its_element_type_0_is_not_a_valid_JSX_element, generateInitialErrorChain);
66462             }
66463             function generateInitialErrorChain() {
66464                 var componentName = ts.getTextOfNode(openingLikeElement.tagName);
66465                 return ts.chainDiagnosticMessages(/* details */ undefined, ts.Diagnostics._0_cannot_be_used_as_a_JSX_component, componentName);
66466             }
66467         }
66468         /**
66469          * Get attributes type of the given intrinsic opening-like Jsx element by resolving the tag name.
66470          * The function is intended to be called from a function which has checked that the opening element is an intrinsic element.
66471          * @param node an intrinsic JSX opening-like element
66472          */
66473         function getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node) {
66474             ts.Debug.assert(isJsxIntrinsicIdentifier(node.tagName));
66475             var links = getNodeLinks(node);
66476             if (!links.resolvedJsxElementAttributesType) {
66477                 var symbol = getIntrinsicTagSymbol(node);
66478                 if (links.jsxFlags & 1 /* IntrinsicNamedElement */) {
66479                     return links.resolvedJsxElementAttributesType = getTypeOfSymbol(symbol);
66480                 }
66481                 else if (links.jsxFlags & 2 /* IntrinsicIndexedElement */) {
66482                     return links.resolvedJsxElementAttributesType =
66483                         getIndexTypeOfType(getDeclaredTypeOfSymbol(symbol), 0 /* String */);
66484                 }
66485                 else {
66486                     return links.resolvedJsxElementAttributesType = errorType;
66487                 }
66488             }
66489             return links.resolvedJsxElementAttributesType;
66490         }
66491         function getJsxElementClassTypeAt(location) {
66492             var type = getJsxType(JsxNames.ElementClass, location);
66493             if (type === errorType)
66494                 return undefined;
66495             return type;
66496         }
66497         function getJsxElementTypeAt(location) {
66498             return getJsxType(JsxNames.Element, location);
66499         }
66500         function getJsxStatelessElementTypeAt(location) {
66501             var jsxElementType = getJsxElementTypeAt(location);
66502             if (jsxElementType) {
66503                 return getUnionType([jsxElementType, nullType]);
66504             }
66505         }
66506         /**
66507          * Returns all the properties of the Jsx.IntrinsicElements interface
66508          */
66509         function getJsxIntrinsicTagNamesAt(location) {
66510             var intrinsics = getJsxType(JsxNames.IntrinsicElements, location);
66511             return intrinsics ? getPropertiesOfType(intrinsics) : ts.emptyArray;
66512         }
66513         function checkJsxPreconditions(errorNode) {
66514             // Preconditions for using JSX
66515             if ((compilerOptions.jsx || 0 /* None */) === 0 /* None */) {
66516                 error(errorNode, ts.Diagnostics.Cannot_use_JSX_unless_the_jsx_flag_is_provided);
66517             }
66518             if (getJsxElementTypeAt(errorNode) === undefined) {
66519                 if (noImplicitAny) {
66520                     error(errorNode, ts.Diagnostics.JSX_element_implicitly_has_type_any_because_the_global_type_JSX_Element_does_not_exist);
66521                 }
66522             }
66523         }
66524         function checkJsxOpeningLikeElementOrOpeningFragment(node) {
66525             var isNodeOpeningLikeElement = ts.isJsxOpeningLikeElement(node);
66526             if (isNodeOpeningLikeElement) {
66527                 checkGrammarJsxElement(node);
66528             }
66529             checkJsxPreconditions(node);
66530             if (!getJsxNamespaceContainerForImplicitImport(node)) {
66531                 // The reactNamespace/jsxFactory's root symbol should be marked as 'used' so we don't incorrectly elide its import.
66532                 // And if there is no reactNamespace/jsxFactory's symbol in scope when targeting React emit, we should issue an error.
66533                 var jsxFactoryRefErr = diagnostics && compilerOptions.jsx === 2 /* React */ ? ts.Diagnostics.Cannot_find_name_0 : undefined;
66534                 var jsxFactoryNamespace = getJsxNamespace(node);
66535                 var jsxFactoryLocation = isNodeOpeningLikeElement ? node.tagName : node;
66536                 // allow null as jsxFragmentFactory
66537                 var jsxFactorySym = void 0;
66538                 if (!(ts.isJsxOpeningFragment(node) && jsxFactoryNamespace === "null")) {
66539                     jsxFactorySym = resolveName(jsxFactoryLocation, jsxFactoryNamespace, 111551 /* Value */, jsxFactoryRefErr, jsxFactoryNamespace, /*isUse*/ true);
66540                 }
66541                 if (jsxFactorySym) {
66542                     // Mark local symbol as referenced here because it might not have been marked
66543                     // if jsx emit was not jsxFactory as there wont be error being emitted
66544                     jsxFactorySym.isReferenced = 67108863 /* All */;
66545                     // If react/jsxFactory symbol is alias, mark it as refereced
66546                     if (jsxFactorySym.flags & 2097152 /* Alias */ && !getTypeOnlyAliasDeclaration(jsxFactorySym)) {
66547                         markAliasSymbolAsReferenced(jsxFactorySym);
66548                     }
66549                 }
66550             }
66551             if (isNodeOpeningLikeElement) {
66552                 var jsxOpeningLikeNode = node;
66553                 var sig = getResolvedSignature(jsxOpeningLikeNode);
66554                 checkDeprecatedSignature(sig, node);
66555                 checkJsxReturnAssignableToAppropriateBound(getJsxReferenceKind(jsxOpeningLikeNode), getReturnTypeOfSignature(sig), jsxOpeningLikeNode);
66556             }
66557         }
66558         /**
66559          * Check if a property with the given name is known anywhere in the given type. In an object type, a property
66560          * is considered known if
66561          * 1. the object type is empty and the check is for assignability, or
66562          * 2. if the object type has index signatures, or
66563          * 3. if the property is actually declared in the object type
66564          *    (this means that 'toString', for example, is not usually a known property).
66565          * 4. In a union or intersection type,
66566          *    a property is considered known if it is known in any constituent type.
66567          * @param targetType a type to search a given name in
66568          * @param name a property name to search
66569          * @param isComparingJsxAttributes a boolean flag indicating whether we are searching in JsxAttributesType
66570          */
66571         function isKnownProperty(targetType, name, isComparingJsxAttributes) {
66572             if (targetType.flags & 524288 /* Object */) {
66573                 var resolved = resolveStructuredTypeMembers(targetType);
66574                 if (resolved.stringIndexInfo ||
66575                     resolved.numberIndexInfo && isNumericLiteralName(name) ||
66576                     getPropertyOfObjectType(targetType, name) ||
66577                     isComparingJsxAttributes && !isUnhyphenatedJsxName(name)) {
66578                     // For JSXAttributes, if the attribute has a hyphenated name, consider that the attribute to be known.
66579                     return true;
66580                 }
66581             }
66582             else if (targetType.flags & 3145728 /* UnionOrIntersection */ && isExcessPropertyCheckTarget(targetType)) {
66583                 for (var _i = 0, _a = targetType.types; _i < _a.length; _i++) {
66584                     var t = _a[_i];
66585                     if (isKnownProperty(t, name, isComparingJsxAttributes)) {
66586                         return true;
66587                     }
66588                 }
66589             }
66590             return false;
66591         }
66592         function isExcessPropertyCheckTarget(type) {
66593             return !!(type.flags & 524288 /* Object */ && !(ts.getObjectFlags(type) & 512 /* ObjectLiteralPatternWithComputedProperties */) ||
66594                 type.flags & 67108864 /* NonPrimitive */ ||
66595                 type.flags & 1048576 /* Union */ && ts.some(type.types, isExcessPropertyCheckTarget) ||
66596                 type.flags & 2097152 /* Intersection */ && ts.every(type.types, isExcessPropertyCheckTarget));
66597         }
66598         function checkJsxExpression(node, checkMode) {
66599             checkGrammarJsxExpression(node);
66600             if (node.expression) {
66601                 var type = checkExpression(node.expression, checkMode);
66602                 if (node.dotDotDotToken && type !== anyType && !isArrayType(type)) {
66603                     error(node, ts.Diagnostics.JSX_spread_child_must_be_an_array_type);
66604                 }
66605                 return type;
66606             }
66607             else {
66608                 return errorType;
66609             }
66610         }
66611         function getDeclarationNodeFlagsFromSymbol(s) {
66612             return s.valueDeclaration ? ts.getCombinedNodeFlags(s.valueDeclaration) : 0;
66613         }
66614         /**
66615          * Return whether this symbol is a member of a prototype somewhere
66616          * Note that this is not tracked well within the compiler, so the answer may be incorrect.
66617          */
66618         function isPrototypeProperty(symbol) {
66619             if (symbol.flags & 8192 /* Method */ || ts.getCheckFlags(symbol) & 4 /* SyntheticMethod */) {
66620                 return true;
66621             }
66622             if (ts.isInJSFile(symbol.valueDeclaration)) {
66623                 var parent = symbol.valueDeclaration.parent;
66624                 return parent && ts.isBinaryExpression(parent) &&
66625                     ts.getAssignmentDeclarationKind(parent) === 3 /* PrototypeProperty */;
66626             }
66627         }
66628         /**
66629          * Check whether the requested property access is valid.
66630          * Returns true if node is a valid property access, and false otherwise.
66631          * @param node The node to be checked.
66632          * @param isSuper True if the access is from `super.`.
66633          * @param type The type of the object whose property is being accessed. (Not the type of the property.)
66634          * @param prop The symbol for the property being accessed.
66635          */
66636         function checkPropertyAccessibility(node, isSuper, type, prop) {
66637             var flags = ts.getDeclarationModifierFlagsFromSymbol(prop);
66638             var errorNode = node.kind === 157 /* QualifiedName */ ? node.right : node.kind === 195 /* ImportType */ ? node : node.name;
66639             if (isSuper) {
66640                 // TS 1.0 spec (April 2014): 4.8.2
66641                 // - In a constructor, instance member function, instance member accessor, or
66642                 //   instance member variable initializer where this references a derived class instance,
66643                 //   a super property access is permitted and must specify a public instance member function of the base class.
66644                 // - In a static member function or static member accessor
66645                 //   where this references the constructor function object of a derived class,
66646                 //   a super property access is permitted and must specify a public static member function of the base class.
66647                 if (languageVersion < 2 /* ES2015 */) {
66648                     if (symbolHasNonMethodDeclaration(prop)) {
66649                         error(errorNode, ts.Diagnostics.Only_public_and_protected_methods_of_the_base_class_are_accessible_via_the_super_keyword);
66650                         return false;
66651                     }
66652                 }
66653                 if (flags & 128 /* Abstract */) {
66654                     // A method cannot be accessed in a super property access if the method is abstract.
66655                     // This error could mask a private property access error. But, a member
66656                     // cannot simultaneously be private and abstract, so this will trigger an
66657                     // additional error elsewhere.
66658                     error(errorNode, ts.Diagnostics.Abstract_method_0_in_class_1_cannot_be_accessed_via_super_expression, symbolToString(prop), typeToString(getDeclaringClass(prop)));
66659                     return false;
66660                 }
66661             }
66662             // Referencing abstract properties within their own constructors is not allowed
66663             if ((flags & 128 /* Abstract */) && ts.isThisProperty(node) && symbolHasNonMethodDeclaration(prop)) {
66664                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
66665                 if (declaringClassDeclaration && isNodeUsedDuringClassInitialization(node)) {
66666                     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
66667                     return false;
66668                 }
66669             }
66670             if (ts.isPropertyAccessExpression(node) && ts.isPrivateIdentifier(node.name)) {
66671                 if (!ts.getContainingClass(node)) {
66672                     error(errorNode, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
66673                     return false;
66674                 }
66675                 return true;
66676             }
66677             // Public properties are otherwise accessible.
66678             if (!(flags & 24 /* NonPublicAccessibilityModifier */)) {
66679                 return true;
66680             }
66681             // Property is known to be private or protected at this point
66682             // Private property is accessible if the property is within the declaring class
66683             if (flags & 8 /* Private */) {
66684                 var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(getParentOfSymbol(prop));
66685                 if (!isNodeWithinClass(node, declaringClassDeclaration)) {
66686                     error(errorNode, ts.Diagnostics.Property_0_is_private_and_only_accessible_within_class_1, symbolToString(prop), typeToString(getDeclaringClass(prop)));
66687                     return false;
66688                 }
66689                 return true;
66690             }
66691             // Property is known to be protected at this point
66692             // All protected properties of a supertype are accessible in a super access
66693             if (isSuper) {
66694                 return true;
66695             }
66696             // Find the first enclosing class that has the declaring classes of the protected constituents
66697             // of the property as base classes
66698             var enclosingClass = forEachEnclosingClass(node, function (enclosingDeclaration) {
66699                 var enclosingClass = getDeclaredTypeOfSymbol(getSymbolOfNode(enclosingDeclaration));
66700                 return isClassDerivedFromDeclaringClasses(enclosingClass, prop) ? enclosingClass : undefined;
66701             });
66702             // A protected property is accessible if the property is within the declaring class or classes derived from it
66703             if (!enclosingClass) {
66704                 // allow PropertyAccessibility if context is in function with this parameter
66705                 // static member access is disallow
66706                 var thisParameter = void 0;
66707                 if (flags & 32 /* Static */ || !(thisParameter = getThisParameterFromNodeContext(node)) || !thisParameter.type) {
66708                     error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_within_class_1_and_its_subclasses, symbolToString(prop), typeToString(getDeclaringClass(prop) || type));
66709                     return false;
66710                 }
66711                 var thisType = getTypeFromTypeNode(thisParameter.type);
66712                 enclosingClass = ((thisType.flags & 262144 /* TypeParameter */) ? getConstraintOfTypeParameter(thisType) : thisType).target;
66713             }
66714             // No further restrictions for static properties
66715             if (flags & 32 /* Static */) {
66716                 return true;
66717             }
66718             if (type.flags & 262144 /* TypeParameter */) {
66719                 // get the original type -- represented as the type constraint of the 'this' type
66720                 type = type.isThisType ? getConstraintOfTypeParameter(type) : getBaseConstraintOfType(type); // TODO: GH#18217 Use a different variable that's allowed to be undefined
66721             }
66722             if (!type || !hasBaseType(type, enclosingClass)) {
66723                 error(errorNode, ts.Diagnostics.Property_0_is_protected_and_only_accessible_through_an_instance_of_class_1, symbolToString(prop), typeToString(enclosingClass));
66724                 return false;
66725             }
66726             return true;
66727         }
66728         function getThisParameterFromNodeContext(node) {
66729             var thisContainer = ts.getThisContainer(node, /* includeArrowFunctions */ false);
66730             return thisContainer && ts.isFunctionLike(thisContainer) ? ts.getThisParameter(thisContainer) : undefined;
66731         }
66732         function symbolHasNonMethodDeclaration(symbol) {
66733             return !!forEachProperty(symbol, function (prop) { return !(prop.flags & 8192 /* Method */); });
66734         }
66735         function checkNonNullExpression(node) {
66736             return checkNonNullType(checkExpression(node), node);
66737         }
66738         function isNullableType(type) {
66739             return !!((strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */);
66740         }
66741         function getNonNullableTypeIfNeeded(type) {
66742             return isNullableType(type) ? getNonNullableType(type) : type;
66743         }
66744         function reportObjectPossiblyNullOrUndefinedError(node, flags) {
66745             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
66746                 ts.Diagnostics.Object_is_possibly_null_or_undefined :
66747                 ts.Diagnostics.Object_is_possibly_undefined :
66748                 ts.Diagnostics.Object_is_possibly_null);
66749         }
66750         function reportCannotInvokePossiblyNullOrUndefinedError(node, flags) {
66751             error(node, flags & 32768 /* Undefined */ ? flags & 65536 /* Null */ ?
66752                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null_or_undefined :
66753                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_undefined :
66754                 ts.Diagnostics.Cannot_invoke_an_object_which_is_possibly_null);
66755         }
66756         function checkNonNullTypeWithReporter(type, node, reportError) {
66757             if (strictNullChecks && type.flags & 2 /* Unknown */) {
66758                 error(node, ts.Diagnostics.Object_is_of_type_unknown);
66759                 return errorType;
66760             }
66761             var kind = (strictNullChecks ? getFalsyFlags(type) : type.flags) & 98304 /* Nullable */;
66762             if (kind) {
66763                 reportError(node, kind);
66764                 var t = getNonNullableType(type);
66765                 return t.flags & (98304 /* Nullable */ | 131072 /* Never */) ? errorType : t;
66766             }
66767             return type;
66768         }
66769         function checkNonNullType(type, node) {
66770             return checkNonNullTypeWithReporter(type, node, reportObjectPossiblyNullOrUndefinedError);
66771         }
66772         function checkNonNullNonVoidType(type, node) {
66773             var nonNullType = checkNonNullType(type, node);
66774             if (nonNullType !== errorType && nonNullType.flags & 16384 /* Void */) {
66775                 error(node, ts.Diagnostics.Object_is_possibly_undefined);
66776             }
66777             return nonNullType;
66778         }
66779         function checkPropertyAccessExpression(node) {
66780             return node.flags & 32 /* OptionalChain */ ? checkPropertyAccessChain(node) :
66781                 checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullExpression(node.expression), node.name);
66782         }
66783         function checkPropertyAccessChain(node) {
66784             var leftType = checkExpression(node.expression);
66785             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
66786             return propagateOptionalTypeMarker(checkPropertyAccessExpressionOrQualifiedName(node, node.expression, checkNonNullType(nonOptionalType, node.expression), node.name), node, nonOptionalType !== leftType);
66787         }
66788         function checkQualifiedName(node) {
66789             return checkPropertyAccessExpressionOrQualifiedName(node, node.left, checkNonNullExpression(node.left), node.right);
66790         }
66791         function isMethodAccessForCall(node) {
66792             while (node.parent.kind === 207 /* ParenthesizedExpression */) {
66793                 node = node.parent;
66794             }
66795             return ts.isCallOrNewExpression(node.parent) && node.parent.expression === node;
66796         }
66797         // Lookup the private identifier lexically.
66798         function lookupSymbolForPrivateIdentifierDeclaration(propName, location) {
66799             for (var containingClass = ts.getContainingClass(location); !!containingClass; containingClass = ts.getContainingClass(containingClass)) {
66800                 var symbol = containingClass.symbol;
66801                 var name = ts.getSymbolNameForPrivateIdentifier(symbol, propName);
66802                 var prop = (symbol.members && symbol.members.get(name)) || (symbol.exports && symbol.exports.get(name));
66803                 if (prop) {
66804                     return prop;
66805                 }
66806             }
66807         }
66808         function getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedIdentifier) {
66809             return getPropertyOfType(leftType, lexicallyScopedIdentifier.escapedName);
66810         }
66811         function checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedIdentifier) {
66812             // Either the identifier could not be looked up in the lexical scope OR the lexically scoped identifier did not exist on the type.
66813             // Find a private identifier with the same description on the type.
66814             var propertyOnType;
66815             var properties = getPropertiesOfType(leftType);
66816             if (properties) {
66817                 ts.forEach(properties, function (symbol) {
66818                     var decl = symbol.valueDeclaration;
66819                     if (decl && ts.isNamedDeclaration(decl) && ts.isPrivateIdentifier(decl.name) && decl.name.escapedText === right.escapedText) {
66820                         propertyOnType = symbol;
66821                         return true;
66822                     }
66823                 });
66824             }
66825             var diagName = diagnosticName(right);
66826             if (propertyOnType) {
66827                 var typeValueDecl = propertyOnType.valueDeclaration;
66828                 var typeClass_1 = ts.getContainingClass(typeValueDecl);
66829                 ts.Debug.assert(!!typeClass_1);
66830                 // We found a private identifier property with the same description.
66831                 // Either:
66832                 // - There is a lexically scoped private identifier AND it shadows the one we found on the type.
66833                 // - It is an attempt to access the private identifier outside of the class.
66834                 if (lexicallyScopedIdentifier) {
66835                     var lexicalValueDecl = lexicallyScopedIdentifier.valueDeclaration;
66836                     var lexicalClass = ts.getContainingClass(lexicalValueDecl);
66837                     ts.Debug.assert(!!lexicalClass);
66838                     if (ts.findAncestor(lexicalClass, function (n) { return typeClass_1 === n; })) {
66839                         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));
66840                         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));
66841                         return true;
66842                     }
66843                 }
66844                 error(right, ts.Diagnostics.Property_0_is_not_accessible_outside_class_1_because_it_has_a_private_identifier, diagName, diagnosticName(typeClass_1.name || anon));
66845                 return true;
66846             }
66847             return false;
66848         }
66849         function isThisPropertyAccessInConstructor(node, prop) {
66850             return (isConstructorDeclaredProperty(prop) || ts.isThisProperty(node) && isAutoTypedProperty(prop))
66851                 && ts.getThisContainer(node, /*includeArrowFunctions*/ true) === getDeclaringConstructor(prop);
66852         }
66853         function checkPropertyAccessExpressionOrQualifiedName(node, left, leftType, right) {
66854             var parentSymbol = getNodeLinks(left).resolvedSymbol;
66855             var assignmentKind = ts.getAssignmentTargetKind(node);
66856             var apparentType = getApparentType(assignmentKind !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(leftType) : leftType);
66857             if (ts.isPrivateIdentifier(right)) {
66858                 checkExternalEmitHelpers(node, 1048576 /* ClassPrivateFieldGet */);
66859             }
66860             var isAnyLike = isTypeAny(apparentType) || apparentType === silentNeverType;
66861             var prop;
66862             if (ts.isPrivateIdentifier(right)) {
66863                 var lexicallyScopedSymbol = lookupSymbolForPrivateIdentifierDeclaration(right.escapedText, right);
66864                 if (isAnyLike) {
66865                     if (lexicallyScopedSymbol) {
66866                         return apparentType;
66867                     }
66868                     if (!ts.getContainingClass(right)) {
66869                         grammarErrorOnNode(right, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
66870                         return anyType;
66871                     }
66872                 }
66873                 prop = lexicallyScopedSymbol ? getPrivateIdentifierPropertyOfType(leftType, lexicallyScopedSymbol) : undefined;
66874                 // Check for private-identifier-specific shadowing and lexical-scoping errors.
66875                 if (!prop && checkPrivateIdentifierPropertyAccess(leftType, right, lexicallyScopedSymbol)) {
66876                     return errorType;
66877                 }
66878             }
66879             else {
66880                 if (isAnyLike) {
66881                     if (ts.isIdentifier(left) && parentSymbol) {
66882                         markAliasReferenced(parentSymbol, node);
66883                     }
66884                     return apparentType;
66885                 }
66886                 prop = getPropertyOfType(apparentType, right.escapedText);
66887             }
66888             if (ts.isIdentifier(left) && parentSymbol && !(prop && isConstEnumOrConstEnumOnlyModule(prop))) {
66889                 markAliasReferenced(parentSymbol, node);
66890             }
66891             var propType;
66892             if (!prop) {
66893                 var indexInfo = !ts.isPrivateIdentifier(right) && (assignmentKind === 0 /* None */ || !isGenericObjectType(leftType) || isThisTypeParameter(leftType)) ? getIndexInfoOfType(apparentType, 0 /* String */) : undefined;
66894                 if (!(indexInfo && indexInfo.type)) {
66895                     if (isJSLiteralType(leftType)) {
66896                         return anyType;
66897                     }
66898                     if (leftType.symbol === globalThisSymbol) {
66899                         if (globalThisSymbol.exports.has(right.escapedText) && (globalThisSymbol.exports.get(right.escapedText).flags & 418 /* BlockScoped */)) {
66900                             error(right, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.unescapeLeadingUnderscores(right.escapedText), typeToString(leftType));
66901                         }
66902                         else if (noImplicitAny) {
66903                             error(right, ts.Diagnostics.Element_implicitly_has_an_any_type_because_type_0_has_no_index_signature, typeToString(leftType));
66904                         }
66905                         return anyType;
66906                     }
66907                     if (right.escapedText && !checkAndReportErrorForExtendingInterface(node)) {
66908                         reportNonexistentProperty(right, isThisTypeParameter(leftType) ? apparentType : leftType);
66909                     }
66910                     return errorType;
66911                 }
66912                 if (indexInfo.isReadonly && (ts.isAssignmentTarget(node) || ts.isDeleteTarget(node))) {
66913                     error(node, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(apparentType));
66914                 }
66915                 propType = (compilerOptions.noUncheckedIndexedAccess && !ts.isAssignmentTarget(node)) ? getUnionType([indexInfo.type, undefinedType]) : indexInfo.type;
66916             }
66917             else {
66918                 if (getDeclarationNodeFlagsFromSymbol(prop) & 134217728 /* Deprecated */ && isUncalledFunctionReference(node, prop)) {
66919                     errorOrSuggestion(/* isError */ false, right, ts.Diagnostics._0_is_deprecated, right.escapedText);
66920                 }
66921                 checkPropertyNotUsedBeforeDeclaration(prop, node, right);
66922                 markPropertyAsReferenced(prop, node, left.kind === 107 /* ThisKeyword */);
66923                 getNodeLinks(node).resolvedSymbol = prop;
66924                 checkPropertyAccessibility(node, left.kind === 105 /* SuperKeyword */, apparentType, prop);
66925                 if (isAssignmentToReadonlyEntity(node, prop, assignmentKind)) {
66926                     error(right, ts.Diagnostics.Cannot_assign_to_0_because_it_is_a_read_only_property, ts.idText(right));
66927                     return errorType;
66928                 }
66929                 propType = isThisPropertyAccessInConstructor(node, prop) ? autoType : getConstraintForLocation(getTypeOfSymbol(prop), node);
66930             }
66931             return getFlowTypeOfAccessExpression(node, prop, propType, right);
66932         }
66933         function getFlowTypeOfAccessExpression(node, prop, propType, errorNode) {
66934             // Only compute control flow type if this is a property access expression that isn't an
66935             // assignment target, and the referenced property was declared as a variable, property,
66936             // accessor, or optional method.
66937             var assignmentKind = ts.getAssignmentTargetKind(node);
66938             if (!ts.isAccessExpression(node) ||
66939                 assignmentKind === 1 /* Definite */ ||
66940                 prop && !(prop.flags & (3 /* Variable */ | 4 /* Property */ | 98304 /* Accessor */)) && !(prop.flags & 8192 /* Method */ && propType.flags & 1048576 /* Union */)) {
66941                 return propType;
66942             }
66943             if (propType === autoType) {
66944                 return getFlowTypeOfProperty(node, prop);
66945             }
66946             // If strict null checks and strict property initialization checks are enabled, if we have
66947             // a this.xxx property access, if the property is an instance property without an initializer,
66948             // and if we are in a constructor of the same class as the property declaration, assume that
66949             // the property is uninitialized at the top of the control flow.
66950             var assumeUninitialized = false;
66951             if (strictNullChecks && strictPropertyInitialization && node.expression.kind === 107 /* ThisKeyword */) {
66952                 var declaration = prop && prop.valueDeclaration;
66953                 if (declaration && isInstancePropertyWithoutInitializer(declaration)) {
66954                     var flowContainer = getControlFlowContainer(node);
66955                     if (flowContainer.kind === 166 /* Constructor */ && flowContainer.parent === declaration.parent && !(declaration.flags & 8388608 /* Ambient */)) {
66956                         assumeUninitialized = true;
66957                     }
66958                 }
66959             }
66960             else if (strictNullChecks && prop && prop.valueDeclaration &&
66961                 ts.isPropertyAccessExpression(prop.valueDeclaration) &&
66962                 ts.getAssignmentDeclarationPropertyAccessKind(prop.valueDeclaration) &&
66963                 getControlFlowContainer(node) === getControlFlowContainer(prop.valueDeclaration)) {
66964                 assumeUninitialized = true;
66965             }
66966             var flowType = getFlowTypeOfReference(node, propType, assumeUninitialized ? getOptionalType(propType) : propType);
66967             if (assumeUninitialized && !(getFalsyFlags(propType) & 32768 /* Undefined */) && getFalsyFlags(flowType) & 32768 /* Undefined */) {
66968                 error(errorNode, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(prop)); // TODO: GH#18217
66969                 // Return the declared type to reduce follow-on errors
66970                 return propType;
66971             }
66972             return assignmentKind ? getBaseTypeOfLiteralType(flowType) : flowType;
66973         }
66974         function checkPropertyNotUsedBeforeDeclaration(prop, node, right) {
66975             var valueDeclaration = prop.valueDeclaration;
66976             if (!valueDeclaration || ts.getSourceFileOfNode(node).isDeclarationFile) {
66977                 return;
66978             }
66979             var diagnosticMessage;
66980             var declarationName = ts.idText(right);
66981             if (isInPropertyInitializer(node)
66982                 && !(ts.isAccessExpression(node) && ts.isAccessExpression(node.expression))
66983                 && !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)
66984                 && !isPropertyDeclaredInAncestorClass(prop)) {
66985                 diagnosticMessage = error(right, ts.Diagnostics.Property_0_is_used_before_its_initialization, declarationName);
66986             }
66987             else if (valueDeclaration.kind === 252 /* ClassDeclaration */ &&
66988                 node.parent.kind !== 173 /* TypeReference */ &&
66989                 !(valueDeclaration.flags & 8388608 /* Ambient */) &&
66990                 !isBlockScopedNameDeclaredBeforeUse(valueDeclaration, right)) {
66991                 diagnosticMessage = error(right, ts.Diagnostics.Class_0_used_before_its_declaration, declarationName);
66992             }
66993             if (diagnosticMessage) {
66994                 ts.addRelatedInfo(diagnosticMessage, ts.createDiagnosticForNode(valueDeclaration, ts.Diagnostics._0_is_declared_here, declarationName));
66995             }
66996         }
66997         function isInPropertyInitializer(node) {
66998             return !!ts.findAncestor(node, function (node) {
66999                 switch (node.kind) {
67000                     case 163 /* PropertyDeclaration */:
67001                         return true;
67002                     case 288 /* PropertyAssignment */:
67003                     case 165 /* MethodDeclaration */:
67004                     case 167 /* GetAccessor */:
67005                     case 168 /* SetAccessor */:
67006                     case 290 /* SpreadAssignment */:
67007                     case 158 /* ComputedPropertyName */:
67008                     case 228 /* TemplateSpan */:
67009                     case 283 /* JsxExpression */:
67010                     case 280 /* JsxAttribute */:
67011                     case 281 /* JsxAttributes */:
67012                     case 282 /* JsxSpreadAttribute */:
67013                     case 275 /* JsxOpeningElement */:
67014                     case 223 /* ExpressionWithTypeArguments */:
67015                     case 286 /* HeritageClause */:
67016                         return false;
67017                     default:
67018                         return ts.isExpressionNode(node) ? false : "quit";
67019                 }
67020             });
67021         }
67022         /**
67023          * It's possible that "prop.valueDeclaration" is a local declaration, but the property was also declared in a superclass.
67024          * In that case we won't consider it used before its declaration, because it gets its value from the superclass' declaration.
67025          */
67026         function isPropertyDeclaredInAncestorClass(prop) {
67027             if (!(prop.parent.flags & 32 /* Class */)) {
67028                 return false;
67029             }
67030             var classType = getTypeOfSymbol(prop.parent);
67031             while (true) {
67032                 classType = classType.symbol && getSuperClass(classType);
67033                 if (!classType) {
67034                     return false;
67035                 }
67036                 var superProperty = getPropertyOfType(classType, prop.escapedName);
67037                 if (superProperty && superProperty.valueDeclaration) {
67038                     return true;
67039                 }
67040             }
67041         }
67042         function getSuperClass(classType) {
67043             var x = getBaseTypes(classType);
67044             if (x.length === 0) {
67045                 return undefined;
67046             }
67047             return getIntersectionType(x);
67048         }
67049         function reportNonexistentProperty(propNode, containingType) {
67050             var errorInfo;
67051             var relatedInfo;
67052             if (!ts.isPrivateIdentifier(propNode) && containingType.flags & 1048576 /* Union */ && !(containingType.flags & 131068 /* Primitive */)) {
67053                 for (var _i = 0, _a = containingType.types; _i < _a.length; _i++) {
67054                     var subtype = _a[_i];
67055                     if (!getPropertyOfType(subtype, propNode.escapedText) && !getIndexInfoOfType(subtype, 0 /* String */)) {
67056                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(subtype));
67057                         break;
67058                     }
67059                 }
67060             }
67061             if (typeHasStaticProperty(propNode.escapedText, containingType)) {
67062                 errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_is_a_static_member_of_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
67063             }
67064             else {
67065                 var promisedType = getPromisedTypeOfPromise(containingType);
67066                 if (promisedType && getPropertyOfType(promisedType, propNode.escapedText)) {
67067                     errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1, ts.declarationNameToString(propNode), typeToString(containingType));
67068                     relatedInfo = ts.createDiagnosticForNode(propNode, ts.Diagnostics.Did_you_forget_to_use_await);
67069                 }
67070                 else {
67071                     var missingProperty = ts.declarationNameToString(propNode);
67072                     var container = typeToString(containingType);
67073                     var libSuggestion = getSuggestedLibForNonExistentProperty(missingProperty, containingType);
67074                     if (libSuggestion !== undefined) {
67075                         errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Do_you_need_to_change_your_target_library_Try_changing_the_lib_compiler_option_to_2_or_later, missingProperty, container, libSuggestion);
67076                     }
67077                     else {
67078                         var suggestion = getSuggestedSymbolForNonexistentProperty(propNode, containingType);
67079                         if (suggestion !== undefined) {
67080                             var suggestedName = ts.symbolName(suggestion);
67081                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Property_0_does_not_exist_on_type_1_Did_you_mean_2, missingProperty, container, suggestedName);
67082                             relatedInfo = suggestion.valueDeclaration && ts.createDiagnosticForNode(suggestion.valueDeclaration, ts.Diagnostics._0_is_declared_here, suggestedName);
67083                         }
67084                         else {
67085                             errorInfo = ts.chainDiagnosticMessages(elaborateNeverIntersection(errorInfo, containingType), ts.Diagnostics.Property_0_does_not_exist_on_type_1, missingProperty, container);
67086                         }
67087                     }
67088                 }
67089             }
67090             var resultDiagnostic = ts.createDiagnosticForNodeFromMessageChain(propNode, errorInfo);
67091             if (relatedInfo) {
67092                 ts.addRelatedInfo(resultDiagnostic, relatedInfo);
67093             }
67094             diagnostics.add(resultDiagnostic);
67095         }
67096         function typeHasStaticProperty(propName, containingType) {
67097             var prop = containingType.symbol && getPropertyOfType(getTypeOfSymbol(containingType.symbol), propName);
67098             return prop !== undefined && prop.valueDeclaration && ts.hasSyntacticModifier(prop.valueDeclaration, 32 /* Static */);
67099         }
67100         function getSuggestedLibForNonExistentName(name) {
67101             var missingName = diagnosticName(name);
67102             var allFeatures = ts.getScriptTargetFeatures();
67103             var libTargets = ts.getOwnKeys(allFeatures);
67104             for (var _i = 0, libTargets_1 = libTargets; _i < libTargets_1.length; _i++) {
67105                 var libTarget = libTargets_1[_i];
67106                 var containingTypes = ts.getOwnKeys(allFeatures[libTarget]);
67107                 if (containingTypes !== undefined && ts.contains(containingTypes, missingName)) {
67108                     return libTarget;
67109                 }
67110             }
67111         }
67112         function getSuggestedLibForNonExistentProperty(missingProperty, containingType) {
67113             var container = getApparentType(containingType).symbol;
67114             if (!container) {
67115                 return undefined;
67116             }
67117             var allFeatures = ts.getScriptTargetFeatures();
67118             var libTargets = ts.getOwnKeys(allFeatures);
67119             for (var _i = 0, libTargets_2 = libTargets; _i < libTargets_2.length; _i++) {
67120                 var libTarget = libTargets_2[_i];
67121                 var featuresOfLib = allFeatures[libTarget];
67122                 var featuresOfContainingType = featuresOfLib[ts.symbolName(container)];
67123                 if (featuresOfContainingType !== undefined && ts.contains(featuresOfContainingType, missingProperty)) {
67124                     return libTarget;
67125                 }
67126             }
67127         }
67128         function getSuggestedSymbolForNonexistentProperty(name, containingType) {
67129             return getSpellingSuggestionForName(ts.isString(name) ? name : ts.idText(name), getPropertiesOfType(containingType), 111551 /* Value */);
67130         }
67131         function getSuggestedSymbolForNonexistentJSXAttribute(name, containingType) {
67132             var strName = ts.isString(name) ? name : ts.idText(name);
67133             var properties = getPropertiesOfType(containingType);
67134             var jsxSpecific = strName === "for" ? ts.find(properties, function (x) { return ts.symbolName(x) === "htmlFor"; })
67135                 : strName === "class" ? ts.find(properties, function (x) { return ts.symbolName(x) === "className"; })
67136                     : undefined;
67137             return jsxSpecific !== null && jsxSpecific !== void 0 ? jsxSpecific : getSpellingSuggestionForName(strName, properties, 111551 /* Value */);
67138         }
67139         function getSuggestionForNonexistentProperty(name, containingType) {
67140             var suggestion = getSuggestedSymbolForNonexistentProperty(name, containingType);
67141             return suggestion && ts.symbolName(suggestion);
67142         }
67143         function getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning) {
67144             ts.Debug.assert(outerName !== undefined, "outername should always be defined");
67145             var result = resolveNameHelper(location, outerName, meaning, /*nameNotFoundMessage*/ undefined, outerName, /*isUse*/ false, /*excludeGlobals*/ false, function (symbols, name, meaning) {
67146                 ts.Debug.assertEqual(outerName, name, "name should equal outerName");
67147                 var symbol = getSymbol(symbols, name, meaning);
67148                 // 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
67149                 // So the table *contains* `x` but `x` isn't actually in scope.
67150                 // However, resolveNameHelper will continue and call this callback again, so we'll eventually get a correct suggestion.
67151                 return symbol || getSpellingSuggestionForName(ts.unescapeLeadingUnderscores(name), ts.arrayFrom(symbols.values()), meaning);
67152             });
67153             return result;
67154         }
67155         function getSuggestionForNonexistentSymbol(location, outerName, meaning) {
67156             var symbolResult = getSuggestedSymbolForNonexistentSymbol(location, outerName, meaning);
67157             return symbolResult && ts.symbolName(symbolResult);
67158         }
67159         function getSuggestedSymbolForNonexistentModule(name, targetModule) {
67160             return targetModule.exports && getSpellingSuggestionForName(ts.idText(name), getExportsOfModuleAsArray(targetModule), 2623475 /* ModuleMember */);
67161         }
67162         function getSuggestionForNonexistentExport(name, targetModule) {
67163             var suggestion = getSuggestedSymbolForNonexistentModule(name, targetModule);
67164             return suggestion && ts.symbolName(suggestion);
67165         }
67166         function getSuggestionForNonexistentIndexSignature(objectType, expr, keyedType) {
67167             // check if object type has setter or getter
67168             function hasProp(name) {
67169                 var prop = getPropertyOfObjectType(objectType, name);
67170                 if (prop) {
67171                     var s = getSingleCallSignature(getTypeOfSymbol(prop));
67172                     return !!s && getMinArgumentCount(s) >= 1 && isTypeAssignableTo(keyedType, getTypeAtPosition(s, 0));
67173                 }
67174                 return false;
67175             }
67176             ;
67177             var suggestedMethod = ts.isAssignmentTarget(expr) ? "set" : "get";
67178             if (!hasProp(suggestedMethod)) {
67179                 return undefined;
67180             }
67181             var suggestion = ts.tryGetPropertyAccessOrIdentifierToString(expr.expression);
67182             if (suggestion === undefined) {
67183                 suggestion = suggestedMethod;
67184             }
67185             else {
67186                 suggestion += "." + suggestedMethod;
67187             }
67188             return suggestion;
67189         }
67190         /**
67191          * 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.
67192          * Names less than length 3 only check for case-insensitive equality, not levenshtein distance.
67193          *
67194          * If there is a candidate that's the same except for case, return that.
67195          * If there is a candidate that's within one edit of the name, return that.
67196          * Otherwise, return the candidate with the smallest Levenshtein distance,
67197          *    except for candidates:
67198          *      * With no name
67199          *      * Whose meaning doesn't match the `meaning` parameter.
67200          *      * Whose length differs from the target name by more than 0.34 of the length of the name.
67201          *      * Whose levenshtein distance is more than 0.4 of the length of the name
67202          *        (0.4 allows 1 substitution/transposition for every 5 characters,
67203          *         and 1 insertion/deletion at 3 characters)
67204          */
67205         function getSpellingSuggestionForName(name, symbols, meaning) {
67206             return ts.getSpellingSuggestion(name, symbols, getCandidateName);
67207             function getCandidateName(candidate) {
67208                 var candidateName = ts.symbolName(candidate);
67209                 if (ts.startsWith(candidateName, "\"")) {
67210                     return undefined;
67211                 }
67212                 if (candidate.flags & meaning) {
67213                     return candidateName;
67214                 }
67215                 if (candidate.flags & 2097152 /* Alias */) {
67216                     var alias = tryResolveAlias(candidate);
67217                     if (alias && alias.flags & meaning) {
67218                         return candidateName;
67219                     }
67220                 }
67221                 return undefined;
67222             }
67223         }
67224         function markPropertyAsReferenced(prop, nodeForCheckWriteOnly, isThisAccess) {
67225             var valueDeclaration = prop && (prop.flags & 106500 /* ClassMember */) && prop.valueDeclaration;
67226             if (!valueDeclaration) {
67227                 return;
67228             }
67229             var hasPrivateModifier = ts.hasEffectiveModifier(valueDeclaration, 8 /* Private */);
67230             var hasPrivateIdentifier = ts.isNamedDeclaration(prop.valueDeclaration) && ts.isPrivateIdentifier(prop.valueDeclaration.name);
67231             if (!hasPrivateModifier && !hasPrivateIdentifier) {
67232                 return;
67233             }
67234             if (nodeForCheckWriteOnly && ts.isWriteOnlyAccess(nodeForCheckWriteOnly) && !(prop.flags & 65536 /* SetAccessor */)) {
67235                 return;
67236             }
67237             if (isThisAccess) {
67238                 // Find any FunctionLikeDeclaration because those create a new 'this' binding. But this should only matter for methods (or getters/setters).
67239                 var containingMethod = ts.findAncestor(nodeForCheckWriteOnly, ts.isFunctionLikeDeclaration);
67240                 if (containingMethod && containingMethod.symbol === prop) {
67241                     return;
67242                 }
67243             }
67244             (ts.getCheckFlags(prop) & 1 /* Instantiated */ ? getSymbolLinks(prop).target : prop).isReferenced = 67108863 /* All */;
67245         }
67246         function isValidPropertyAccess(node, propertyName) {
67247             switch (node.kind) {
67248                 case 201 /* PropertyAccessExpression */:
67249                     return isValidPropertyAccessWithType(node, node.expression.kind === 105 /* SuperKeyword */, propertyName, getWidenedType(checkExpression(node.expression)));
67250                 case 157 /* QualifiedName */:
67251                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getWidenedType(checkExpression(node.left)));
67252                 case 195 /* ImportType */:
67253                     return isValidPropertyAccessWithType(node, /*isSuper*/ false, propertyName, getTypeFromTypeNode(node));
67254             }
67255         }
67256         function isValidPropertyAccessForCompletions(node, type, property) {
67257             return isValidPropertyAccessWithType(node, node.kind === 201 /* PropertyAccessExpression */ && node.expression.kind === 105 /* SuperKeyword */, property.escapedName, type);
67258             // Previously we validated the 'this' type of methods but this adversely affected performance. See #31377 for more context.
67259         }
67260         function isValidPropertyAccessWithType(node, isSuper, propertyName, type) {
67261             if (type === errorType || isTypeAny(type)) {
67262                 return true;
67263             }
67264             var prop = getPropertyOfType(type, propertyName);
67265             if (prop) {
67266                 if (ts.isPropertyAccessExpression(node) && prop.valueDeclaration && ts.isPrivateIdentifierPropertyDeclaration(prop.valueDeclaration)) {
67267                     var declClass_1 = ts.getContainingClass(prop.valueDeclaration);
67268                     return !ts.isOptionalChain(node) && !!ts.findAncestor(node, function (parent) { return parent === declClass_1; });
67269                 }
67270                 return checkPropertyAccessibility(node, isSuper, type, prop);
67271             }
67272             // In js files properties of unions are allowed in completion
67273             return ts.isInJSFile(node) && (type.flags & 1048576 /* Union */) !== 0 && type.types.some(function (elementType) { return isValidPropertyAccessWithType(node, isSuper, propertyName, elementType); });
67274         }
67275         /**
67276          * Return the symbol of the for-in variable declared or referenced by the given for-in statement.
67277          */
67278         function getForInVariableSymbol(node) {
67279             var initializer = node.initializer;
67280             if (initializer.kind === 250 /* VariableDeclarationList */) {
67281                 var variable = initializer.declarations[0];
67282                 if (variable && !ts.isBindingPattern(variable.name)) {
67283                     return getSymbolOfNode(variable);
67284                 }
67285             }
67286             else if (initializer.kind === 78 /* Identifier */) {
67287                 return getResolvedSymbol(initializer);
67288             }
67289             return undefined;
67290         }
67291         /**
67292          * Return true if the given type is considered to have numeric property names.
67293          */
67294         function hasNumericPropertyNames(type) {
67295             return getIndexTypeOfType(type, 1 /* Number */) && !getIndexTypeOfType(type, 0 /* String */);
67296         }
67297         /**
67298          * Return true if given node is an expression consisting of an identifier (possibly parenthesized)
67299          * that references a for-in variable for an object with numeric property names.
67300          */
67301         function isForInVariableForNumericPropertyNames(expr) {
67302             var e = ts.skipParentheses(expr);
67303             if (e.kind === 78 /* Identifier */) {
67304                 var symbol = getResolvedSymbol(e);
67305                 if (symbol.flags & 3 /* Variable */) {
67306                     var child = expr;
67307                     var node = expr.parent;
67308                     while (node) {
67309                         if (node.kind === 238 /* ForInStatement */ &&
67310                             child === node.statement &&
67311                             getForInVariableSymbol(node) === symbol &&
67312                             hasNumericPropertyNames(getTypeOfExpression(node.expression))) {
67313                             return true;
67314                         }
67315                         child = node;
67316                         node = node.parent;
67317                     }
67318                 }
67319             }
67320             return false;
67321         }
67322         function checkIndexedAccess(node) {
67323             return node.flags & 32 /* OptionalChain */ ? checkElementAccessChain(node) :
67324                 checkElementAccessExpression(node, checkNonNullExpression(node.expression));
67325         }
67326         function checkElementAccessChain(node) {
67327             var exprType = checkExpression(node.expression);
67328             var nonOptionalType = getOptionalExpressionType(exprType, node.expression);
67329             return propagateOptionalTypeMarker(checkElementAccessExpression(node, checkNonNullType(nonOptionalType, node.expression)), node, nonOptionalType !== exprType);
67330         }
67331         function checkElementAccessExpression(node, exprType) {
67332             var objectType = ts.getAssignmentTargetKind(node) !== 0 /* None */ || isMethodAccessForCall(node) ? getWidenedType(exprType) : exprType;
67333             var indexExpression = node.argumentExpression;
67334             var indexType = checkExpression(indexExpression);
67335             if (objectType === errorType || objectType === silentNeverType) {
67336                 return objectType;
67337             }
67338             if (isConstEnumObjectType(objectType) && !ts.isStringLiteralLike(indexExpression)) {
67339                 error(indexExpression, ts.Diagnostics.A_const_enum_member_can_only_be_accessed_using_a_string_literal);
67340                 return errorType;
67341             }
67342             var effectiveIndexType = isForInVariableForNumericPropertyNames(indexExpression) ? numberType : indexType;
67343             var accessFlags = ts.isAssignmentTarget(node) ?
67344                 2 /* Writing */ | (isGenericObjectType(objectType) && !isThisTypeParameter(objectType) ? 1 /* NoIndexSignatures */ : 0) :
67345                 0 /* None */;
67346             var indexedAccessType = getIndexedAccessTypeOrUndefined(objectType, effectiveIndexType, /*noUncheckedIndexedAccessCandidate*/ undefined, node, accessFlags | 16 /* ExpressionPosition */) || errorType;
67347             return checkIndexedAccessIndexType(getFlowTypeOfAccessExpression(node, indexedAccessType.symbol, indexedAccessType, indexExpression), node);
67348         }
67349         function checkThatExpressionIsProperSymbolReference(expression, expressionType, reportError) {
67350             if (expressionType === errorType) {
67351                 // There is already an error, so no need to report one.
67352                 return false;
67353             }
67354             if (!ts.isWellKnownSymbolSyntactically(expression)) {
67355                 return false;
67356             }
67357             // Make sure the property type is the primitive symbol type
67358             if ((expressionType.flags & 12288 /* ESSymbolLike */) === 0) {
67359                 if (reportError) {
67360                     error(expression, ts.Diagnostics.A_computed_property_name_of_the_form_0_must_be_of_type_symbol, ts.getTextOfNode(expression));
67361                 }
67362                 return false;
67363             }
67364             // The name is Symbol.<someName>, so make sure Symbol actually resolves to the
67365             // global Symbol object
67366             var leftHandSide = expression.expression;
67367             var leftHandSideSymbol = getResolvedSymbol(leftHandSide);
67368             if (!leftHandSideSymbol) {
67369                 return false;
67370             }
67371             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ true);
67372             if (!globalESSymbol) {
67373                 // Already errored when we tried to look up the symbol
67374                 return false;
67375             }
67376             if (leftHandSideSymbol !== globalESSymbol) {
67377                 if (reportError) {
67378                     error(leftHandSide, ts.Diagnostics.Symbol_reference_does_not_refer_to_the_global_Symbol_constructor_object);
67379                 }
67380                 return false;
67381             }
67382             return true;
67383         }
67384         function callLikeExpressionMayHaveTypeArguments(node) {
67385             return ts.isCallOrNewExpression(node) || ts.isTaggedTemplateExpression(node) || ts.isJsxOpeningLikeElement(node);
67386         }
67387         function resolveUntypedCall(node) {
67388             if (callLikeExpressionMayHaveTypeArguments(node)) {
67389                 // Check type arguments even though we will give an error that untyped calls may not accept type arguments.
67390                 // This gets us diagnostics for the type arguments and marks them as referenced.
67391                 ts.forEach(node.typeArguments, checkSourceElement);
67392             }
67393             if (node.kind === 205 /* TaggedTemplateExpression */) {
67394                 checkExpression(node.template);
67395             }
67396             else if (ts.isJsxOpeningLikeElement(node)) {
67397                 checkExpression(node.attributes);
67398             }
67399             else if (node.kind !== 161 /* Decorator */) {
67400                 ts.forEach(node.arguments, function (argument) {
67401                     checkExpression(argument);
67402                 });
67403             }
67404             return anySignature;
67405         }
67406         function resolveErrorCall(node) {
67407             resolveUntypedCall(node);
67408             return unknownSignature;
67409         }
67410         // Re-order candidate signatures into the result array. Assumes the result array to be empty.
67411         // The candidate list orders groups in reverse, but within a group signatures are kept in declaration order
67412         // A nit here is that we reorder only signatures that belong to the same symbol,
67413         // so order how inherited signatures are processed is still preserved.
67414         // interface A { (x: string): void }
67415         // interface B extends A { (x: 'foo'): string }
67416         // const b: B;
67417         // b('foo') // <- here overloads should be processed as [(x:'foo'): string, (x: string): void]
67418         function reorderCandidates(signatures, result, callChainFlags) {
67419             var lastParent;
67420             var lastSymbol;
67421             var cutoffIndex = 0;
67422             var index;
67423             var specializedIndex = -1;
67424             var spliceIndex;
67425             ts.Debug.assert(!result.length);
67426             for (var _i = 0, signatures_7 = signatures; _i < signatures_7.length; _i++) {
67427                 var signature = signatures_7[_i];
67428                 var symbol = signature.declaration && getSymbolOfNode(signature.declaration);
67429                 var parent = signature.declaration && signature.declaration.parent;
67430                 if (!lastSymbol || symbol === lastSymbol) {
67431                     if (lastParent && parent === lastParent) {
67432                         index = index + 1;
67433                     }
67434                     else {
67435                         lastParent = parent;
67436                         index = cutoffIndex;
67437                     }
67438                 }
67439                 else {
67440                     // current declaration belongs to a different symbol
67441                     // set cutoffIndex so re-orderings in the future won't change result set from 0 to cutoffIndex
67442                     index = cutoffIndex = result.length;
67443                     lastParent = parent;
67444                 }
67445                 lastSymbol = symbol;
67446                 // specialized signatures always need to be placed before non-specialized signatures regardless
67447                 // of the cutoff position; see GH#1133
67448                 if (signatureHasLiteralTypes(signature)) {
67449                     specializedIndex++;
67450                     spliceIndex = specializedIndex;
67451                     // The cutoff index always needs to be greater than or equal to the specialized signature index
67452                     // in order to prevent non-specialized signatures from being added before a specialized
67453                     // signature.
67454                     cutoffIndex++;
67455                 }
67456                 else {
67457                     spliceIndex = index;
67458                 }
67459                 result.splice(spliceIndex, 0, callChainFlags ? getOptionalCallSignature(signature, callChainFlags) : signature);
67460             }
67461         }
67462         function isSpreadArgument(arg) {
67463             return !!arg && (arg.kind === 220 /* SpreadElement */ || arg.kind === 227 /* SyntheticExpression */ && arg.isSpread);
67464         }
67465         function getSpreadArgumentIndex(args) {
67466             return ts.findIndex(args, isSpreadArgument);
67467         }
67468         function acceptsVoid(t) {
67469             return !!(t.flags & 16384 /* Void */);
67470         }
67471         function acceptsVoidUndefinedUnknownOrAny(t) {
67472             return !!(t.flags & (16384 /* Void */ | 32768 /* Undefined */ | 2 /* Unknown */ | 1 /* Any */));
67473         }
67474         function hasCorrectArity(node, args, signature, signatureHelpTrailingComma) {
67475             if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
67476             var argCount;
67477             var callIsIncomplete = false; // In incomplete call we want to be lenient when we have too few arguments
67478             var effectiveParameterCount = getParameterCount(signature);
67479             var effectiveMinimumArguments = getMinArgumentCount(signature);
67480             if (node.kind === 205 /* TaggedTemplateExpression */) {
67481                 argCount = args.length;
67482                 if (node.template.kind === 218 /* TemplateExpression */) {
67483                     // If a tagged template expression lacks a tail literal, the call is incomplete.
67484                     // Specifically, a template only can end in a TemplateTail or a Missing literal.
67485                     var lastSpan = ts.last(node.template.templateSpans); // we should always have at least one span.
67486                     callIsIncomplete = ts.nodeIsMissing(lastSpan.literal) || !!lastSpan.literal.isUnterminated;
67487                 }
67488                 else {
67489                     // If the template didn't end in a backtick, or its beginning occurred right prior to EOF,
67490                     // then this might actually turn out to be a TemplateHead in the future;
67491                     // so we consider the call to be incomplete.
67492                     var templateLiteral = node.template;
67493                     ts.Debug.assert(templateLiteral.kind === 14 /* NoSubstitutionTemplateLiteral */);
67494                     callIsIncomplete = !!templateLiteral.isUnterminated;
67495                 }
67496             }
67497             else if (node.kind === 161 /* Decorator */) {
67498                 argCount = getDecoratorArgumentCount(node, signature);
67499             }
67500             else if (ts.isJsxOpeningLikeElement(node)) {
67501                 callIsIncomplete = node.attributes.end === node.end;
67502                 if (callIsIncomplete) {
67503                     return true;
67504                 }
67505                 argCount = effectiveMinimumArguments === 0 ? args.length : 1;
67506                 effectiveParameterCount = args.length === 0 ? effectiveParameterCount : 1; // class may have argumentless ctor functions - still resolve ctor and compare vs props member type
67507                 effectiveMinimumArguments = Math.min(effectiveMinimumArguments, 1); // sfc may specify context argument - handled by framework and not typechecked
67508             }
67509             else if (!node.arguments) {
67510                 // This only happens when we have something of the form: 'new C'
67511                 ts.Debug.assert(node.kind === 204 /* NewExpression */);
67512                 return getMinArgumentCount(signature) === 0;
67513             }
67514             else {
67515                 argCount = signatureHelpTrailingComma ? args.length + 1 : args.length;
67516                 // If we are missing the close parenthesis, the call is incomplete.
67517                 callIsIncomplete = node.arguments.end === node.end;
67518                 // If a spread argument is present, check that it corresponds to a rest parameter or at least that it's in the valid range.
67519                 var spreadArgIndex = getSpreadArgumentIndex(args);
67520                 if (spreadArgIndex >= 0) {
67521                     return spreadArgIndex >= getMinArgumentCount(signature) && (hasEffectiveRestParameter(signature) || spreadArgIndex < getParameterCount(signature));
67522                 }
67523             }
67524             // Too many arguments implies incorrect arity.
67525             if (!hasEffectiveRestParameter(signature) && argCount > effectiveParameterCount) {
67526                 return false;
67527             }
67528             // If the call is incomplete, we should skip the lower bound check.
67529             // JSX signatures can have extra parameters provided by the library which we don't check
67530             if (callIsIncomplete || argCount >= effectiveMinimumArguments) {
67531                 return true;
67532             }
67533             for (var i = argCount; i < effectiveMinimumArguments; i++) {
67534                 var type = getTypeAtPosition(signature, i);
67535                 if (filterType(type, ts.isInJSFile(node) && !strictNullChecks ? acceptsVoidUndefinedUnknownOrAny : acceptsVoid).flags & 131072 /* Never */) {
67536                     return false;
67537                 }
67538             }
67539             return true;
67540         }
67541         function hasCorrectTypeArgumentArity(signature, typeArguments) {
67542             // If the user supplied type arguments, but the number of type arguments does not match
67543             // the declared number of type parameters, the call has an incorrect arity.
67544             var numTypeParameters = ts.length(signature.typeParameters);
67545             var minTypeArgumentCount = getMinTypeArgumentCount(signature.typeParameters);
67546             return !ts.some(typeArguments) ||
67547                 (typeArguments.length >= minTypeArgumentCount && typeArguments.length <= numTypeParameters);
67548         }
67549         // If type has a single call signature and no other members, return that signature. Otherwise, return undefined.
67550         function getSingleCallSignature(type) {
67551             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false);
67552         }
67553         function getSingleCallOrConstructSignature(type) {
67554             return getSingleSignature(type, 0 /* Call */, /*allowMembers*/ false) ||
67555                 getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ false);
67556         }
67557         function getSingleSignature(type, kind, allowMembers) {
67558             if (type.flags & 524288 /* Object */) {
67559                 var resolved = resolveStructuredTypeMembers(type);
67560                 if (allowMembers || resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
67561                     if (kind === 0 /* Call */ && resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0) {
67562                         return resolved.callSignatures[0];
67563                     }
67564                     if (kind === 1 /* Construct */ && resolved.constructSignatures.length === 1 && resolved.callSignatures.length === 0) {
67565                         return resolved.constructSignatures[0];
67566                     }
67567                 }
67568             }
67569             return undefined;
67570         }
67571         // Instantiate a generic signature in the context of a non-generic signature (section 3.8.5 in TypeScript spec)
67572         function instantiateSignatureInContextOf(signature, contextualSignature, inferenceContext, compareTypes) {
67573             var context = createInferenceContext(signature.typeParameters, signature, 0 /* None */, compareTypes);
67574             // We clone the inferenceContext to avoid fixing. For example, when the source signature is <T>(x: T) => T[] and
67575             // the contextual signature is (...args: A) => B, we want to infer the element type of A's constraint (say 'any')
67576             // for T but leave it possible to later infer '[any]' back to A.
67577             var restType = getEffectiveRestType(contextualSignature);
67578             var mapper = inferenceContext && (restType && restType.flags & 262144 /* TypeParameter */ ? inferenceContext.nonFixingMapper : inferenceContext.mapper);
67579             var sourceSignature = mapper ? instantiateSignature(contextualSignature, mapper) : contextualSignature;
67580             applyToParameterTypes(sourceSignature, signature, function (source, target) {
67581                 // Type parameters from outer context referenced by source type are fixed by instantiation of the source type
67582                 inferTypes(context.inferences, source, target);
67583             });
67584             if (!inferenceContext) {
67585                 applyToReturnTypes(contextualSignature, signature, function (source, target) {
67586                     inferTypes(context.inferences, source, target, 64 /* ReturnType */);
67587                 });
67588             }
67589             return getSignatureInstantiation(signature, getInferredTypes(context), ts.isInJSFile(contextualSignature.declaration));
67590         }
67591         function inferJsxTypeArguments(node, signature, checkMode, context) {
67592             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
67593             var checkAttrType = checkExpressionWithContextualType(node.attributes, paramType, context, checkMode);
67594             inferTypes(context.inferences, checkAttrType, paramType);
67595             return getInferredTypes(context);
67596         }
67597         function inferTypeArguments(node, signature, args, checkMode, context) {
67598             if (ts.isJsxOpeningLikeElement(node)) {
67599                 return inferJsxTypeArguments(node, signature, checkMode, context);
67600             }
67601             // If a contextual type is available, infer from that type to the return type of the call expression. For
67602             // example, given a 'function wrap<T, U>(cb: (x: T) => U): (x: T) => U' and a call expression
67603             // 'let f: (x: string) => number = wrap(s => s.length)', we infer from the declared type of 'f' to the
67604             // return type of 'wrap'.
67605             if (node.kind !== 161 /* Decorator */) {
67606                 var contextualType = getContextualType(node, ts.every(signature.typeParameters, function (p) { return !!getDefaultFromTypeParameter(p); }) ? 8 /* SkipBindingPatterns */ : 0 /* None */);
67607                 if (contextualType) {
67608                     // We clone the inference context to avoid disturbing a resolution in progress for an
67609                     // outer call expression. Effectively we just want a snapshot of whatever has been
67610                     // inferred for any outer call expression so far.
67611                     var outerContext = getInferenceContext(node);
67612                     var outerMapper = getMapperFromContext(cloneInferenceContext(outerContext, 1 /* NoDefault */));
67613                     var instantiatedType = instantiateType(contextualType, outerMapper);
67614                     // If the contextual type is a generic function type with a single call signature, we
67615                     // instantiate the type with its own type parameters and type arguments. This ensures that
67616                     // the type parameters are not erased to type any during type inference such that they can
67617                     // be inferred as actual types from the contextual type. For example:
67618                     //   declare function arrayMap<T, U>(f: (x: T) => U): (a: T[]) => U[];
67619                     //   const boxElements: <A>(a: A[]) => { value: A }[] = arrayMap(value => ({ value }));
67620                     // Above, the type of the 'value' parameter is inferred to be 'A'.
67621                     var contextualSignature = getSingleCallSignature(instantiatedType);
67622                     var inferenceSourceType = contextualSignature && contextualSignature.typeParameters ?
67623                         getOrCreateTypeFromSignature(getSignatureInstantiationWithoutFillingInTypeArguments(contextualSignature, contextualSignature.typeParameters)) :
67624                         instantiatedType;
67625                     var inferenceTargetType = getReturnTypeOfSignature(signature);
67626                     // Inferences made from return types have lower priority than all other inferences.
67627                     inferTypes(context.inferences, inferenceSourceType, inferenceTargetType, 64 /* ReturnType */);
67628                     // Create a type mapper for instantiating generic contextual types using the inferences made
67629                     // from the return type. We need a separate inference pass here because (a) instantiation of
67630                     // the source type uses the outer context's return mapper (which excludes inferences made from
67631                     // outer arguments), and (b) we don't want any further inferences going into this context.
67632                     var returnContext = createInferenceContext(signature.typeParameters, signature, context.flags);
67633                     var returnSourceType = instantiateType(contextualType, outerContext && outerContext.returnMapper);
67634                     inferTypes(returnContext.inferences, returnSourceType, inferenceTargetType);
67635                     context.returnMapper = ts.some(returnContext.inferences, hasInferenceCandidates) ? getMapperFromContext(cloneInferredPartOfContext(returnContext)) : undefined;
67636                 }
67637             }
67638             var restType = getNonArrayRestType(signature);
67639             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
67640             if (restType && restType.flags & 262144 /* TypeParameter */) {
67641                 var info = ts.find(context.inferences, function (info) { return info.typeParameter === restType; });
67642                 if (info) {
67643                     info.impliedArity = ts.findIndex(args, isSpreadArgument, argCount) < 0 ? args.length - argCount : undefined;
67644                 }
67645             }
67646             var thisType = getThisTypeOfSignature(signature);
67647             if (thisType) {
67648                 var thisArgumentNode = getThisArgumentOfCall(node);
67649                 var thisArgumentType = thisArgumentNode ? checkExpression(thisArgumentNode) : voidType;
67650                 inferTypes(context.inferences, thisArgumentType, thisType);
67651             }
67652             for (var i = 0; i < argCount; i++) {
67653                 var arg = args[i];
67654                 if (arg.kind !== 222 /* OmittedExpression */) {
67655                     var paramType = getTypeAtPosition(signature, i);
67656                     var argType = checkExpressionWithContextualType(arg, paramType, context, checkMode);
67657                     inferTypes(context.inferences, argType, paramType);
67658                 }
67659             }
67660             if (restType) {
67661                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, context, checkMode);
67662                 inferTypes(context.inferences, spreadType, restType);
67663             }
67664             return getInferredTypes(context);
67665         }
67666         function getMutableArrayOrTupleType(type) {
67667             return type.flags & 1048576 /* Union */ ? mapType(type, getMutableArrayOrTupleType) :
67668                 type.flags & 1 /* Any */ || isMutableArrayOrTuple(getBaseConstraintOfType(type) || type) ? type :
67669                     isTupleType(type) ? createTupleType(getTypeArguments(type), type.target.elementFlags, /*readonly*/ false, type.target.labeledElementDeclarations) :
67670                         createTupleType([type], [8 /* Variadic */]);
67671         }
67672         function getSpreadArgumentType(args, index, argCount, restType, context, checkMode) {
67673             if (index >= argCount - 1) {
67674                 var arg = args[argCount - 1];
67675                 if (isSpreadArgument(arg)) {
67676                     // We are inferring from a spread expression in the last argument position, i.e. both the parameter
67677                     // and the argument are ...x forms.
67678                     return getMutableArrayOrTupleType(arg.kind === 227 /* SyntheticExpression */ ? arg.type :
67679                         checkExpressionWithContextualType(arg.expression, restType, context, checkMode));
67680                 }
67681             }
67682             var types = [];
67683             var flags = [];
67684             var names = [];
67685             for (var i = index; i < argCount; i++) {
67686                 var arg = args[i];
67687                 if (isSpreadArgument(arg)) {
67688                     var spreadType = arg.kind === 227 /* SyntheticExpression */ ? arg.type : checkExpression(arg.expression);
67689                     if (isArrayLikeType(spreadType)) {
67690                         types.push(spreadType);
67691                         flags.push(8 /* Variadic */);
67692                     }
67693                     else {
67694                         types.push(checkIteratedTypeOrElementType(33 /* Spread */, spreadType, undefinedType, arg.kind === 220 /* SpreadElement */ ? arg.expression : arg));
67695                         flags.push(4 /* Rest */);
67696                     }
67697                 }
67698                 else {
67699                     var contextualType = getIndexedAccessType(restType, getLiteralType(i - index));
67700                     var argType = checkExpressionWithContextualType(arg, contextualType, context, checkMode);
67701                     var hasPrimitiveContextualType = maybeTypeOfKind(contextualType, 131068 /* Primitive */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */);
67702                     types.push(hasPrimitiveContextualType ? getRegularTypeOfLiteralType(argType) : getWidenedLiteralType(argType));
67703                     flags.push(1 /* Required */);
67704                 }
67705                 if (arg.kind === 227 /* SyntheticExpression */ && arg.tupleNameSource) {
67706                     names.push(arg.tupleNameSource);
67707                 }
67708             }
67709             return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
67710         }
67711         function checkTypeArguments(signature, typeArgumentNodes, reportErrors, headMessage) {
67712             var isJavascript = ts.isInJSFile(signature.declaration);
67713             var typeParameters = signature.typeParameters;
67714             var typeArgumentTypes = fillMissingTypeArguments(ts.map(typeArgumentNodes, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), isJavascript);
67715             var mapper;
67716             for (var i = 0; i < typeArgumentNodes.length; i++) {
67717                 ts.Debug.assert(typeParameters[i] !== undefined, "Should not call checkTypeArguments with too many type arguments");
67718                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
67719                 if (constraint) {
67720                     var errorInfo = reportErrors && headMessage ? (function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1); }) : undefined;
67721                     var typeArgumentHeadMessage = headMessage || ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1;
67722                     if (!mapper) {
67723                         mapper = createTypeMapper(typeParameters, typeArgumentTypes);
67724                     }
67725                     var typeArgument = typeArgumentTypes[i];
67726                     if (!checkTypeAssignableTo(typeArgument, getTypeWithThisArgument(instantiateType(constraint, mapper), typeArgument), reportErrors ? typeArgumentNodes[i] : undefined, typeArgumentHeadMessage, errorInfo)) {
67727                         return undefined;
67728                     }
67729                 }
67730             }
67731             return typeArgumentTypes;
67732         }
67733         function getJsxReferenceKind(node) {
67734             if (isJsxIntrinsicIdentifier(node.tagName)) {
67735                 return 2 /* Mixed */;
67736             }
67737             var tagType = getApparentType(checkExpression(node.tagName));
67738             if (ts.length(getSignaturesOfType(tagType, 1 /* Construct */))) {
67739                 return 0 /* Component */;
67740             }
67741             if (ts.length(getSignaturesOfType(tagType, 0 /* Call */))) {
67742                 return 1 /* Function */;
67743             }
67744             return 2 /* Mixed */;
67745         }
67746         /**
67747          * Check if the given signature can possibly be a signature called by the JSX opening-like element.
67748          * @param node a JSX opening-like element we are trying to figure its call signature
67749          * @param signature a candidate signature we are trying whether it is a call signature
67750          * @param relation a relationship to check parameter and argument type
67751          */
67752         function checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer) {
67753             // Stateless function components can have maximum of three arguments: "props", "context", and "updater".
67754             // However "context" and "updater" are implicit and can't be specify by users. Only the first parameter, props,
67755             // can be specified by users through attributes property.
67756             var paramType = getEffectiveFirstArgumentForJsxSignature(signature, node);
67757             var attributesType = checkExpressionWithContextualType(node.attributes, paramType, /*inferenceContext*/ undefined, checkMode);
67758             return checkTagNameDoesNotExpectTooManyArguments() && checkTypeRelatedToAndOptionallyElaborate(attributesType, paramType, relation, reportErrors ? node.tagName : undefined, node.attributes, 
67759             /*headMessage*/ undefined, containingMessageChain, errorOutputContainer);
67760             function checkTagNameDoesNotExpectTooManyArguments() {
67761                 var _a;
67762                 var tagType = ts.isJsxOpeningElement(node) || ts.isJsxSelfClosingElement(node) && !isJsxIntrinsicIdentifier(node.tagName) ? checkExpression(node.tagName) : undefined;
67763                 if (!tagType) {
67764                     return true;
67765                 }
67766                 var tagCallSignatures = getSignaturesOfType(tagType, 0 /* Call */);
67767                 if (!ts.length(tagCallSignatures)) {
67768                     return true;
67769                 }
67770                 var factory = getJsxFactoryEntity(node);
67771                 if (!factory) {
67772                     return true;
67773                 }
67774                 var factorySymbol = resolveEntityName(factory, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, node);
67775                 if (!factorySymbol) {
67776                     return true;
67777                 }
67778                 var factoryType = getTypeOfSymbol(factorySymbol);
67779                 var callSignatures = getSignaturesOfType(factoryType, 0 /* Call */);
67780                 if (!ts.length(callSignatures)) {
67781                     return true;
67782                 }
67783                 var hasFirstParamSignatures = false;
67784                 var maxParamCount = 0;
67785                 // Check that _some_ first parameter expects a FC-like thing, and that some overload of the SFC expects an acceptable number of arguments
67786                 for (var _i = 0, callSignatures_1 = callSignatures; _i < callSignatures_1.length; _i++) {
67787                     var sig = callSignatures_1[_i];
67788                     var firstparam = getTypeAtPosition(sig, 0);
67789                     var signaturesOfParam = getSignaturesOfType(firstparam, 0 /* Call */);
67790                     if (!ts.length(signaturesOfParam))
67791                         continue;
67792                     for (var _b = 0, signaturesOfParam_1 = signaturesOfParam; _b < signaturesOfParam_1.length; _b++) {
67793                         var paramSig = signaturesOfParam_1[_b];
67794                         hasFirstParamSignatures = true;
67795                         if (hasEffectiveRestParameter(paramSig)) {
67796                             return true; // some signature has a rest param, so function components can have an arbitrary number of arguments
67797                         }
67798                         var paramCount = getParameterCount(paramSig);
67799                         if (paramCount > maxParamCount) {
67800                             maxParamCount = paramCount;
67801                         }
67802                     }
67803                 }
67804                 if (!hasFirstParamSignatures) {
67805                     // Not a single signature had a first parameter which expected a signature - for back compat, and
67806                     // to guard against generic factories which won't have signatures directly, do not error
67807                     return true;
67808                 }
67809                 var absoluteMinArgCount = Infinity;
67810                 for (var _c = 0, tagCallSignatures_1 = tagCallSignatures; _c < tagCallSignatures_1.length; _c++) {
67811                     var tagSig = tagCallSignatures_1[_c];
67812                     var tagRequiredArgCount = getMinArgumentCount(tagSig);
67813                     if (tagRequiredArgCount < absoluteMinArgCount) {
67814                         absoluteMinArgCount = tagRequiredArgCount;
67815                     }
67816                 }
67817                 if (absoluteMinArgCount <= maxParamCount) {
67818                     return true; // some signature accepts the number of arguments the function component provides
67819                 }
67820                 if (reportErrors) {
67821                     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);
67822                     var tagNameDeclaration = (_a = getSymbolAtLocation(node.tagName)) === null || _a === void 0 ? void 0 : _a.valueDeclaration;
67823                     if (tagNameDeclaration) {
67824                         ts.addRelatedInfo(diag, ts.createDiagnosticForNode(tagNameDeclaration, ts.Diagnostics._0_is_declared_here, ts.entityNameToString(node.tagName)));
67825                     }
67826                     if (errorOutputContainer && errorOutputContainer.skipLogging) {
67827                         (errorOutputContainer.errors || (errorOutputContainer.errors = [])).push(diag);
67828                     }
67829                     if (!errorOutputContainer.skipLogging) {
67830                         diagnostics.add(diag);
67831                     }
67832                 }
67833                 return false;
67834             }
67835         }
67836         function getSignatureApplicabilityError(node, args, signature, relation, checkMode, reportErrors, containingMessageChain) {
67837             var errorOutputContainer = { errors: undefined, skipLogging: true };
67838             if (ts.isJsxOpeningLikeElement(node)) {
67839                 if (!checkApplicableSignatureForJsxOpeningLikeElement(node, signature, relation, checkMode, reportErrors, containingMessageChain, errorOutputContainer)) {
67840                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "jsx should have errors when reporting errors");
67841                     return errorOutputContainer.errors || ts.emptyArray;
67842                 }
67843                 return undefined;
67844             }
67845             var thisType = getThisTypeOfSignature(signature);
67846             if (thisType && thisType !== voidType && node.kind !== 204 /* NewExpression */) {
67847                 // If the called expression is not of the form `x.f` or `x["f"]`, then sourceType = voidType
67848                 // If the signature's 'this' type is voidType, then the check is skipped -- anything is compatible.
67849                 // If the expression is a new expression, then the check is skipped.
67850                 var thisArgumentNode = getThisArgumentOfCall(node);
67851                 var thisArgumentType = void 0;
67852                 if (thisArgumentNode) {
67853                     thisArgumentType = checkExpression(thisArgumentNode);
67854                     if (ts.isOptionalChainRoot(thisArgumentNode.parent)) {
67855                         thisArgumentType = getNonNullableType(thisArgumentType);
67856                     }
67857                     else if (ts.isOptionalChain(thisArgumentNode.parent)) {
67858                         thisArgumentType = removeOptionalTypeMarker(thisArgumentType);
67859                     }
67860                 }
67861                 else {
67862                     thisArgumentType = voidType;
67863                 }
67864                 var errorNode = reportErrors ? (thisArgumentNode || node) : undefined;
67865                 var headMessage_1 = ts.Diagnostics.The_this_context_of_type_0_is_not_assignable_to_method_s_this_of_type_1;
67866                 if (!checkTypeRelatedTo(thisArgumentType, thisType, relation, errorNode, headMessage_1, containingMessageChain, errorOutputContainer)) {
67867                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "this parameter should have errors when reporting errors");
67868                     return errorOutputContainer.errors || ts.emptyArray;
67869                 }
67870             }
67871             var headMessage = ts.Diagnostics.Argument_of_type_0_is_not_assignable_to_parameter_of_type_1;
67872             var restType = getNonArrayRestType(signature);
67873             var argCount = restType ? Math.min(getParameterCount(signature) - 1, args.length) : args.length;
67874             for (var i = 0; i < argCount; i++) {
67875                 var arg = args[i];
67876                 if (arg.kind !== 222 /* OmittedExpression */) {
67877                     var paramType = getTypeAtPosition(signature, i);
67878                     var argType = checkExpressionWithContextualType(arg, paramType, /*inferenceContext*/ undefined, checkMode);
67879                     // If one or more arguments are still excluded (as indicated by CheckMode.SkipContextSensitive),
67880                     // we obtain the regular type of any object literal arguments because we may not have inferred complete
67881                     // parameter types yet and therefore excess property checks may yield false positives (see #17041).
67882                     var checkArgType = checkMode & 4 /* SkipContextSensitive */ ? getRegularTypeOfObjectLiteral(argType) : argType;
67883                     if (!checkTypeRelatedToAndOptionallyElaborate(checkArgType, paramType, relation, reportErrors ? arg : undefined, arg, headMessage, containingMessageChain, errorOutputContainer)) {
67884                         ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "parameter should have errors when reporting errors");
67885                         maybeAddMissingAwaitInfo(arg, checkArgType, paramType);
67886                         return errorOutputContainer.errors || ts.emptyArray;
67887                     }
67888                 }
67889             }
67890             if (restType) {
67891                 var spreadType = getSpreadArgumentType(args, argCount, args.length, restType, /*context*/ undefined, checkMode);
67892                 var errorNode = reportErrors ? argCount < args.length ? args[argCount] : node : undefined;
67893                 if (!checkTypeRelatedTo(spreadType, restType, relation, errorNode, headMessage, /*containingMessageChain*/ undefined, errorOutputContainer)) {
67894                     ts.Debug.assert(!reportErrors || !!errorOutputContainer.errors, "rest parameter should have errors when reporting errors");
67895                     maybeAddMissingAwaitInfo(errorNode, spreadType, restType);
67896                     return errorOutputContainer.errors || ts.emptyArray;
67897                 }
67898             }
67899             return undefined;
67900             function maybeAddMissingAwaitInfo(errorNode, source, target) {
67901                 if (errorNode && reportErrors && errorOutputContainer.errors && errorOutputContainer.errors.length) {
67902                     // Bail if target is Promise-like---something else is wrong
67903                     if (getAwaitedTypeOfPromise(target)) {
67904                         return;
67905                     }
67906                     var awaitedTypeOfSource = getAwaitedTypeOfPromise(source);
67907                     if (awaitedTypeOfSource && isTypeRelatedTo(awaitedTypeOfSource, target, relation)) {
67908                         ts.addRelatedInfo(errorOutputContainer.errors[0], ts.createDiagnosticForNode(errorNode, ts.Diagnostics.Did_you_forget_to_use_await));
67909                     }
67910                 }
67911             }
67912         }
67913         /**
67914          * Returns the this argument in calls like x.f(...) and x[f](...). Undefined otherwise.
67915          */
67916         function getThisArgumentOfCall(node) {
67917             if (node.kind === 203 /* CallExpression */) {
67918                 var callee = ts.skipOuterExpressions(node.expression);
67919                 if (ts.isAccessExpression(callee)) {
67920                     return callee.expression;
67921                 }
67922             }
67923         }
67924         function createSyntheticExpression(parent, type, isSpread, tupleNameSource) {
67925             var result = ts.parseNodeFactory.createSyntheticExpression(type, isSpread, tupleNameSource);
67926             ts.setTextRange(result, parent);
67927             ts.setParent(result, parent);
67928             return result;
67929         }
67930         /**
67931          * Returns the effective arguments for an expression that works like a function invocation.
67932          */
67933         function getEffectiveCallArguments(node) {
67934             if (node.kind === 205 /* TaggedTemplateExpression */) {
67935                 var template = node.template;
67936                 var args_3 = [createSyntheticExpression(template, getGlobalTemplateStringsArrayType())];
67937                 if (template.kind === 218 /* TemplateExpression */) {
67938                     ts.forEach(template.templateSpans, function (span) {
67939                         args_3.push(span.expression);
67940                     });
67941                 }
67942                 return args_3;
67943             }
67944             if (node.kind === 161 /* Decorator */) {
67945                 return getEffectiveDecoratorArguments(node);
67946             }
67947             if (ts.isJsxOpeningLikeElement(node)) {
67948                 return node.attributes.properties.length > 0 || (ts.isJsxOpeningElement(node) && node.parent.children.length > 0) ? [node.attributes] : ts.emptyArray;
67949             }
67950             var args = node.arguments || ts.emptyArray;
67951             var spreadIndex = getSpreadArgumentIndex(args);
67952             if (spreadIndex >= 0) {
67953                 // Create synthetic arguments from spreads of tuple types.
67954                 var effectiveArgs_1 = args.slice(0, spreadIndex);
67955                 var _loop_20 = function (i) {
67956                     var arg = args[i];
67957                     // We can call checkExpressionCached because spread expressions never have a contextual type.
67958                     var spreadType = arg.kind === 220 /* SpreadElement */ && (flowLoopCount ? checkExpression(arg.expression) : checkExpressionCached(arg.expression));
67959                     if (spreadType && isTupleType(spreadType)) {
67960                         ts.forEach(getTypeArguments(spreadType), function (t, i) {
67961                             var _a;
67962                             var flags = spreadType.target.elementFlags[i];
67963                             var syntheticArg = createSyntheticExpression(arg, flags & 4 /* Rest */ ? createArrayType(t) : t, !!(flags & 12 /* Variable */), (_a = spreadType.target.labeledElementDeclarations) === null || _a === void 0 ? void 0 : _a[i]);
67964                             effectiveArgs_1.push(syntheticArg);
67965                         });
67966                     }
67967                     else {
67968                         effectiveArgs_1.push(arg);
67969                     }
67970                 };
67971                 for (var i = spreadIndex; i < args.length; i++) {
67972                     _loop_20(i);
67973                 }
67974                 return effectiveArgs_1;
67975             }
67976             return args;
67977         }
67978         /**
67979          * Returns the synthetic argument list for a decorator invocation.
67980          */
67981         function getEffectiveDecoratorArguments(node) {
67982             var parent = node.parent;
67983             var expr = node.expression;
67984             switch (parent.kind) {
67985                 case 252 /* ClassDeclaration */:
67986                 case 221 /* ClassExpression */:
67987                     // For a class decorator, the `target` is the type of the class (e.g. the
67988                     // "static" or "constructor" side of the class).
67989                     return [
67990                         createSyntheticExpression(expr, getTypeOfSymbol(getSymbolOfNode(parent)))
67991                     ];
67992                 case 160 /* Parameter */:
67993                     // A parameter declaration decorator will have three arguments (see
67994                     // `ParameterDecorator` in core.d.ts).
67995                     var func = parent.parent;
67996                     return [
67997                         createSyntheticExpression(expr, parent.parent.kind === 166 /* Constructor */ ? getTypeOfSymbol(getSymbolOfNode(func)) : errorType),
67998                         createSyntheticExpression(expr, anyType),
67999                         createSyntheticExpression(expr, numberType)
68000                     ];
68001                 case 163 /* PropertyDeclaration */:
68002                 case 165 /* MethodDeclaration */:
68003                 case 167 /* GetAccessor */:
68004                 case 168 /* SetAccessor */:
68005                     // A method or accessor declaration decorator will have two or three arguments (see
68006                     // `PropertyDecorator` and `MethodDecorator` in core.d.ts). If we are emitting decorators
68007                     // for ES3, we will only pass two arguments.
68008                     var hasPropDesc = parent.kind !== 163 /* PropertyDeclaration */ && languageVersion !== 0 /* ES3 */;
68009                     return [
68010                         createSyntheticExpression(expr, getParentTypeOfClassElement(parent)),
68011                         createSyntheticExpression(expr, getClassElementPropertyKeyType(parent)),
68012                         createSyntheticExpression(expr, hasPropDesc ? createTypedPropertyDescriptorType(getTypeOfNode(parent)) : anyType)
68013                     ];
68014             }
68015             return ts.Debug.fail();
68016         }
68017         /**
68018          * Returns the argument count for a decorator node that works like a function invocation.
68019          */
68020         function getDecoratorArgumentCount(node, signature) {
68021             switch (node.parent.kind) {
68022                 case 252 /* ClassDeclaration */:
68023                 case 221 /* ClassExpression */:
68024                     return 1;
68025                 case 163 /* PropertyDeclaration */:
68026                     return 2;
68027                 case 165 /* MethodDeclaration */:
68028                 case 167 /* GetAccessor */:
68029                 case 168 /* SetAccessor */:
68030                     // For ES3 or decorators with only two parameters we supply only two arguments
68031                     return languageVersion === 0 /* ES3 */ || signature.parameters.length <= 2 ? 2 : 3;
68032                 case 160 /* Parameter */:
68033                     return 3;
68034                 default:
68035                     return ts.Debug.fail();
68036             }
68037         }
68038         function getDiagnosticSpanForCallNode(node, doNotIncludeArguments) {
68039             var start;
68040             var length;
68041             var sourceFile = ts.getSourceFileOfNode(node);
68042             if (ts.isPropertyAccessExpression(node.expression)) {
68043                 var nameSpan = ts.getErrorSpanForNode(sourceFile, node.expression.name);
68044                 start = nameSpan.start;
68045                 length = doNotIncludeArguments ? nameSpan.length : node.end - start;
68046             }
68047             else {
68048                 var expressionSpan = ts.getErrorSpanForNode(sourceFile, node.expression);
68049                 start = expressionSpan.start;
68050                 length = doNotIncludeArguments ? expressionSpan.length : node.end - start;
68051             }
68052             return { start: start, length: length, sourceFile: sourceFile };
68053         }
68054         function getDiagnosticForCallNode(node, message, arg0, arg1, arg2, arg3) {
68055             if (ts.isCallExpression(node)) {
68056                 var _a = getDiagnosticSpanForCallNode(node), sourceFile = _a.sourceFile, start = _a.start, length_5 = _a.length;
68057                 return ts.createFileDiagnostic(sourceFile, start, length_5, message, arg0, arg1, arg2, arg3);
68058             }
68059             else {
68060                 return ts.createDiagnosticForNode(node, message, arg0, arg1, arg2, arg3);
68061             }
68062         }
68063         function isPromiseResolveArityError(node) {
68064             if (!ts.isCallExpression(node) || !ts.isIdentifier(node.expression))
68065                 return false;
68066             var symbol = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, undefined, undefined, false);
68067             var decl = symbol === null || symbol === void 0 ? void 0 : symbol.valueDeclaration;
68068             if (!decl || !ts.isParameter(decl) || !isFunctionExpressionOrArrowFunction(decl.parent) || !ts.isNewExpression(decl.parent.parent) || !ts.isIdentifier(decl.parent.parent.expression)) {
68069                 return false;
68070             }
68071             var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
68072             if (!globalPromiseSymbol)
68073                 return false;
68074             var constructorSymbol = getSymbolAtLocation(decl.parent.parent.expression, /*ignoreErrors*/ true);
68075             return constructorSymbol === globalPromiseSymbol;
68076         }
68077         function getArgumentArityError(node, signatures, args) {
68078             var min = Number.POSITIVE_INFINITY;
68079             var max = Number.NEGATIVE_INFINITY;
68080             var belowArgCount = Number.NEGATIVE_INFINITY;
68081             var aboveArgCount = Number.POSITIVE_INFINITY;
68082             var argCount = args.length;
68083             var closestSignature;
68084             for (var _i = 0, signatures_8 = signatures; _i < signatures_8.length; _i++) {
68085                 var sig = signatures_8[_i];
68086                 var minCount = getMinArgumentCount(sig);
68087                 var maxCount = getParameterCount(sig);
68088                 if (minCount < argCount && minCount > belowArgCount)
68089                     belowArgCount = minCount;
68090                 if (argCount < maxCount && maxCount < aboveArgCount)
68091                     aboveArgCount = maxCount;
68092                 if (minCount < min) {
68093                     min = minCount;
68094                     closestSignature = sig;
68095                 }
68096                 max = Math.max(max, maxCount);
68097             }
68098             var hasRestParameter = ts.some(signatures, hasEffectiveRestParameter);
68099             var paramRange = hasRestParameter ? min :
68100                 min < max ? min + "-" + max :
68101                     min;
68102             var hasSpreadArgument = getSpreadArgumentIndex(args) > -1;
68103             if (argCount <= max && hasSpreadArgument) {
68104                 argCount--;
68105             }
68106             var spanArray;
68107             var related;
68108             var error = hasRestParameter || hasSpreadArgument ?
68109                 hasRestParameter && hasSpreadArgument ?
68110                     ts.Diagnostics.Expected_at_least_0_arguments_but_got_1_or_more :
68111                     hasRestParameter ?
68112                         ts.Diagnostics.Expected_at_least_0_arguments_but_got_1 :
68113                         ts.Diagnostics.Expected_0_arguments_but_got_1_or_more :
68114                 paramRange === 1 && argCount === 0 && isPromiseResolveArityError(node) ?
68115                     ts.Diagnostics.Expected_0_arguments_but_got_1_Did_you_forget_to_include_void_in_your_type_argument_to_Promise :
68116                     ts.Diagnostics.Expected_0_arguments_but_got_1;
68117             if (closestSignature && getMinArgumentCount(closestSignature) > argCount && closestSignature.declaration) {
68118                 var paramDecl = closestSignature.declaration.parameters[closestSignature.thisParameter ? argCount + 1 : argCount];
68119                 if (paramDecl) {
68120                     related = ts.createDiagnosticForNode(paramDecl, ts.isBindingPattern(paramDecl.name) ? ts.Diagnostics.An_argument_matching_this_binding_pattern_was_not_provided :
68121                         ts.isRestParameter(paramDecl) ? ts.Diagnostics.Arguments_for_the_rest_parameter_0_were_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);
68122                 }
68123             }
68124             if (min < argCount && argCount < max) {
68125                 return getDiagnosticForCallNode(node, ts.Diagnostics.No_overload_expects_0_arguments_but_overloads_do_exist_that_expect_either_1_or_2_arguments, argCount, belowArgCount, aboveArgCount);
68126             }
68127             if (!hasSpreadArgument && argCount < min) {
68128                 var diagnostic_1 = getDiagnosticForCallNode(node, error, paramRange, argCount);
68129                 return related ? ts.addRelatedInfo(diagnostic_1, related) : diagnostic_1;
68130             }
68131             if (hasRestParameter || hasSpreadArgument) {
68132                 spanArray = ts.factory.createNodeArray(args);
68133                 if (hasSpreadArgument && argCount) {
68134                     var nextArg = ts.elementAt(args, getSpreadArgumentIndex(args) + 1) || undefined;
68135                     spanArray = ts.factory.createNodeArray(args.slice(max > argCount && nextArg ? args.indexOf(nextArg) : Math.min(max, args.length - 1)));
68136                 }
68137             }
68138             else {
68139                 spanArray = ts.factory.createNodeArray(args.slice(max));
68140             }
68141             var pos = ts.first(spanArray).pos;
68142             var end = ts.last(spanArray).end;
68143             if (end === pos) {
68144                 end++;
68145             }
68146             ts.setTextRangePosEnd(spanArray, pos, end);
68147             var diagnostic = ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), spanArray, error, paramRange, argCount);
68148             return related ? ts.addRelatedInfo(diagnostic, related) : diagnostic;
68149         }
68150         function getTypeArgumentArityError(node, signatures, typeArguments) {
68151             var argCount = typeArguments.length;
68152             // No overloads exist
68153             if (signatures.length === 1) {
68154                 var sig = signatures[0];
68155                 var min_1 = getMinTypeArgumentCount(sig.typeParameters);
68156                 var max = ts.length(sig.typeParameters);
68157                 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);
68158             }
68159             // Overloads exist
68160             var belowArgCount = -Infinity;
68161             var aboveArgCount = Infinity;
68162             for (var _i = 0, signatures_9 = signatures; _i < signatures_9.length; _i++) {
68163                 var sig = signatures_9[_i];
68164                 var min_2 = getMinTypeArgumentCount(sig.typeParameters);
68165                 var max = ts.length(sig.typeParameters);
68166                 if (min_2 > argCount) {
68167                     aboveArgCount = Math.min(aboveArgCount, min_2);
68168                 }
68169                 else if (max < argCount) {
68170                     belowArgCount = Math.max(belowArgCount, max);
68171                 }
68172             }
68173             if (belowArgCount !== -Infinity && aboveArgCount !== Infinity) {
68174                 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);
68175             }
68176             return ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, belowArgCount === -Infinity ? aboveArgCount : belowArgCount, argCount);
68177         }
68178         function resolveCall(node, signatures, candidatesOutArray, checkMode, callChainFlags, fallbackError) {
68179             var isTaggedTemplate = node.kind === 205 /* TaggedTemplateExpression */;
68180             var isDecorator = node.kind === 161 /* Decorator */;
68181             var isJsxOpeningOrSelfClosingElement = ts.isJsxOpeningLikeElement(node);
68182             var reportErrors = !candidatesOutArray && produceDiagnostics;
68183             var typeArguments;
68184             if (!isDecorator) {
68185                 typeArguments = node.typeArguments;
68186                 // We already perform checking on the type arguments on the class declaration itself.
68187                 if (isTaggedTemplate || isJsxOpeningOrSelfClosingElement || node.expression.kind !== 105 /* SuperKeyword */) {
68188                     ts.forEach(typeArguments, checkSourceElement);
68189                 }
68190             }
68191             var candidates = candidatesOutArray || [];
68192             // reorderCandidates fills up the candidates array directly
68193             reorderCandidates(signatures, candidates, callChainFlags);
68194             if (!candidates.length) {
68195                 if (reportErrors) {
68196                     diagnostics.add(getDiagnosticForCallNode(node, ts.Diagnostics.Call_target_does_not_contain_any_signatures));
68197                 }
68198                 return resolveErrorCall(node);
68199             }
68200             var args = getEffectiveCallArguments(node);
68201             // The excludeArgument array contains true for each context sensitive argument (an argument
68202             // is context sensitive it is susceptible to a one-time permanent contextual typing).
68203             //
68204             // The idea is that we will perform type argument inference & assignability checking once
68205             // without using the susceptible parameters that are functions, and once more for those
68206             // parameters, contextually typing each as we go along.
68207             //
68208             // For a tagged template, then the first argument be 'undefined' if necessary because it
68209             // represents a TemplateStringsArray.
68210             //
68211             // For a decorator, no arguments are susceptible to contextual typing due to the fact
68212             // decorators are applied to a declaration by the emitter, and not to an expression.
68213             var isSingleNonGenericCandidate = candidates.length === 1 && !candidates[0].typeParameters;
68214             var argCheckMode = !isDecorator && !isSingleNonGenericCandidate && ts.some(args, isContextSensitive) ? 4 /* SkipContextSensitive */ : 0 /* Normal */;
68215             // The following variables are captured and modified by calls to chooseOverload.
68216             // If overload resolution or type argument inference fails, we want to report the
68217             // best error possible. The best error is one which says that an argument was not
68218             // assignable to a parameter. This implies that everything else about the overload
68219             // was fine. So if there is any overload that is only incorrect because of an
68220             // argument, we will report an error on that one.
68221             //
68222             //     function foo(s: string): void;
68223             //     function foo(n: number): void; // Report argument error on this overload
68224             //     function foo(): void;
68225             //     foo(true);
68226             //
68227             // If none of the overloads even made it that far, there are two possibilities.
68228             // There was a problem with type arguments for some overload, in which case
68229             // report an error on that. Or none of the overloads even had correct arity,
68230             // in which case give an arity error.
68231             //
68232             //     function foo<T extends string>(x: T): void; // Report type argument error
68233             //     function foo(): void;
68234             //     foo<number>(0);
68235             //
68236             var candidatesForArgumentError;
68237             var candidateForArgumentArityError;
68238             var candidateForTypeArgumentError;
68239             var result;
68240             // If we are in signature help, a trailing comma indicates that we intend to provide another argument,
68241             // so we will only accept overloads with arity at least 1 higher than the current number of provided arguments.
68242             var signatureHelpTrailingComma = !!(checkMode & 16 /* IsForSignatureHelp */) && node.kind === 203 /* CallExpression */ && node.arguments.hasTrailingComma;
68243             // Section 4.12.1:
68244             // if the candidate list contains one or more signatures for which the type of each argument
68245             // expression is a subtype of each corresponding parameter type, the return type of the first
68246             // of those signatures becomes the return type of the function call.
68247             // Otherwise, the return type of the first signature in the candidate list becomes the return
68248             // type of the function call.
68249             //
68250             // Whether the call is an error is determined by assignability of the arguments. The subtype pass
68251             // is just important for choosing the best signature. So in the case where there is only one
68252             // signature, the subtype pass is useless. So skipping it is an optimization.
68253             if (candidates.length > 1) {
68254                 result = chooseOverload(candidates, subtypeRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
68255             }
68256             if (!result) {
68257                 result = chooseOverload(candidates, assignableRelation, isSingleNonGenericCandidate, signatureHelpTrailingComma);
68258             }
68259             if (result) {
68260                 return result;
68261             }
68262             // No signatures were applicable. Now report errors based on the last applicable signature with
68263             // no arguments excluded from assignability checks.
68264             // If candidate is undefined, it means that no candidates had a suitable arity. In that case,
68265             // skip the checkApplicableSignature check.
68266             if (reportErrors) {
68267                 if (candidatesForArgumentError) {
68268                     if (candidatesForArgumentError.length === 1 || candidatesForArgumentError.length > 3) {
68269                         var last_2 = candidatesForArgumentError[candidatesForArgumentError.length - 1];
68270                         var chain_1;
68271                         if (candidatesForArgumentError.length > 3) {
68272                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.The_last_overload_gave_the_following_error);
68273                             chain_1 = ts.chainDiagnosticMessages(chain_1, ts.Diagnostics.No_overload_matches_this_call);
68274                         }
68275                         var diags = getSignatureApplicabilityError(node, args, last_2, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, function () { return chain_1; });
68276                         if (diags) {
68277                             for (var _i = 0, diags_1 = diags; _i < diags_1.length; _i++) {
68278                                 var d = diags_1[_i];
68279                                 if (last_2.declaration && candidatesForArgumentError.length > 3) {
68280                                     ts.addRelatedInfo(d, ts.createDiagnosticForNode(last_2.declaration, ts.Diagnostics.The_last_overload_is_declared_here));
68281                                 }
68282                                 addImplementationSuccessElaboration(last_2, d);
68283                                 diagnostics.add(d);
68284                             }
68285                         }
68286                         else {
68287                             ts.Debug.fail("No error for last overload signature");
68288                         }
68289                     }
68290                     else {
68291                         var allDiagnostics = [];
68292                         var max = 0;
68293                         var min_3 = Number.MAX_VALUE;
68294                         var minIndex = 0;
68295                         var i_1 = 0;
68296                         var _loop_21 = function (c) {
68297                             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)); };
68298                             var diags_2 = getSignatureApplicabilityError(node, args, c, assignableRelation, 0 /* Normal */, /*reportErrors*/ true, chain_2);
68299                             if (diags_2) {
68300                                 if (diags_2.length <= min_3) {
68301                                     min_3 = diags_2.length;
68302                                     minIndex = i_1;
68303                                 }
68304                                 max = Math.max(max, diags_2.length);
68305                                 allDiagnostics.push(diags_2);
68306                             }
68307                             else {
68308                                 ts.Debug.fail("No error for 3 or fewer overload signatures");
68309                             }
68310                             i_1++;
68311                         };
68312                         for (var _a = 0, candidatesForArgumentError_1 = candidatesForArgumentError; _a < candidatesForArgumentError_1.length; _a++) {
68313                             var c = candidatesForArgumentError_1[_a];
68314                             _loop_21(c);
68315                         }
68316                         var diags_3 = max > 1 ? allDiagnostics[minIndex] : ts.flatten(allDiagnostics);
68317                         ts.Debug.assert(diags_3.length > 0, "No errors reported for 3 or fewer overload signatures");
68318                         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);
68319                         // The below is a spread to guarantee we get a new (mutable) array - our `flatMap` helper tries to do "smart" optimizations where it reuses input
68320                         // arrays and the emptyArray singleton where possible, which is decidedly not what we want while we're still constructing this diagnostic
68321                         var related = __spreadArrays(ts.flatMap(diags_3, function (d) { return d.relatedInformation; }));
68322                         var diag = void 0;
68323                         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; })) {
68324                             var _b = diags_3[0], file = _b.file, start = _b.start, length_6 = _b.length;
68325                             diag = { file: file, start: start, length: length_6, code: chain.code, category: chain.category, messageText: chain, relatedInformation: related };
68326                         }
68327                         else {
68328                             diag = ts.createDiagnosticForNodeFromMessageChain(node, chain, related);
68329                         }
68330                         addImplementationSuccessElaboration(candidatesForArgumentError[0], diag);
68331                         diagnostics.add(diag);
68332                     }
68333                 }
68334                 else if (candidateForArgumentArityError) {
68335                     diagnostics.add(getArgumentArityError(node, [candidateForArgumentArityError], args));
68336                 }
68337                 else if (candidateForTypeArgumentError) {
68338                     checkTypeArguments(candidateForTypeArgumentError, node.typeArguments, /*reportErrors*/ true, fallbackError);
68339                 }
68340                 else {
68341                     var signaturesWithCorrectTypeArgumentArity = ts.filter(signatures, function (s) { return hasCorrectTypeArgumentArity(s, typeArguments); });
68342                     if (signaturesWithCorrectTypeArgumentArity.length === 0) {
68343                         diagnostics.add(getTypeArgumentArityError(node, signatures, typeArguments));
68344                     }
68345                     else if (!isDecorator) {
68346                         diagnostics.add(getArgumentArityError(node, signaturesWithCorrectTypeArgumentArity, args));
68347                     }
68348                     else if (fallbackError) {
68349                         diagnostics.add(getDiagnosticForCallNode(node, fallbackError));
68350                     }
68351                 }
68352             }
68353             return getCandidateForOverloadFailure(node, candidates, args, !!candidatesOutArray);
68354             function addImplementationSuccessElaboration(failed, diagnostic) {
68355                 var _a, _b;
68356                 var oldCandidatesForArgumentError = candidatesForArgumentError;
68357                 var oldCandidateForArgumentArityError = candidateForArgumentArityError;
68358                 var oldCandidateForTypeArgumentError = candidateForTypeArgumentError;
68359                 var declCount = ts.length((_a = failed.declaration) === null || _a === void 0 ? void 0 : _a.symbol.declarations);
68360                 var isOverload = declCount > 1;
68361                 var implDecl = isOverload ? ts.find(((_b = failed.declaration) === null || _b === void 0 ? void 0 : _b.symbol.declarations) || ts.emptyArray, function (d) { return ts.isFunctionLikeDeclaration(d) && ts.nodeIsPresent(d.body); }) : undefined;
68362                 if (implDecl) {
68363                     var candidate = getSignatureFromDeclaration(implDecl);
68364                     var isSingleNonGenericCandidate_1 = !candidate.typeParameters;
68365                     if (chooseOverload([candidate], assignableRelation, isSingleNonGenericCandidate_1)) {
68366                         ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(implDecl, ts.Diagnostics.The_call_would_have_succeeded_against_this_implementation_but_implementation_signatures_of_overloads_are_not_externally_visible));
68367                     }
68368                 }
68369                 candidatesForArgumentError = oldCandidatesForArgumentError;
68370                 candidateForArgumentArityError = oldCandidateForArgumentArityError;
68371                 candidateForTypeArgumentError = oldCandidateForTypeArgumentError;
68372             }
68373             function chooseOverload(candidates, relation, isSingleNonGenericCandidate, signatureHelpTrailingComma) {
68374                 if (signatureHelpTrailingComma === void 0) { signatureHelpTrailingComma = false; }
68375                 candidatesForArgumentError = undefined;
68376                 candidateForArgumentArityError = undefined;
68377                 candidateForTypeArgumentError = undefined;
68378                 if (isSingleNonGenericCandidate) {
68379                     var candidate = candidates[0];
68380                     if (ts.some(typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
68381                         return undefined;
68382                     }
68383                     if (getSignatureApplicabilityError(node, args, candidate, relation, 0 /* Normal */, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
68384                         candidatesForArgumentError = [candidate];
68385                         return undefined;
68386                     }
68387                     return candidate;
68388                 }
68389                 for (var candidateIndex = 0; candidateIndex < candidates.length; candidateIndex++) {
68390                     var candidate = candidates[candidateIndex];
68391                     if (!hasCorrectTypeArgumentArity(candidate, typeArguments) || !hasCorrectArity(node, args, candidate, signatureHelpTrailingComma)) {
68392                         continue;
68393                     }
68394                     var checkCandidate = void 0;
68395                     var inferenceContext = void 0;
68396                     if (candidate.typeParameters) {
68397                         var typeArgumentTypes = void 0;
68398                         if (ts.some(typeArguments)) {
68399                             typeArgumentTypes = checkTypeArguments(candidate, typeArguments, /*reportErrors*/ false);
68400                             if (!typeArgumentTypes) {
68401                                 candidateForTypeArgumentError = candidate;
68402                                 continue;
68403                             }
68404                         }
68405                         else {
68406                             inferenceContext = createInferenceContext(candidate.typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
68407                             typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode | 8 /* SkipGenericFunctions */, inferenceContext);
68408                             argCheckMode |= inferenceContext.flags & 4 /* SkippedGenericFunction */ ? 8 /* SkipGenericFunctions */ : 0 /* Normal */;
68409                         }
68410                         checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
68411                         // If the original signature has a generic rest type, instantiation may produce a
68412                         // signature with different arity and we need to perform another arity check.
68413                         if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
68414                             candidateForArgumentArityError = checkCandidate;
68415                             continue;
68416                         }
68417                     }
68418                     else {
68419                         checkCandidate = candidate;
68420                     }
68421                     if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
68422                         // Give preference to error candidates that have no rest parameters (as they are more specific)
68423                         (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
68424                         continue;
68425                     }
68426                     if (argCheckMode) {
68427                         // If one or more context sensitive arguments were excluded, we start including
68428                         // them now (and keeping do so for any subsequent candidates) and perform a second
68429                         // round of type inference and applicability checking for this particular candidate.
68430                         argCheckMode = 0 /* Normal */;
68431                         if (inferenceContext) {
68432                             var typeArgumentTypes = inferTypeArguments(node, candidate, args, argCheckMode, inferenceContext);
68433                             checkCandidate = getSignatureInstantiation(candidate, typeArgumentTypes, ts.isInJSFile(candidate.declaration), inferenceContext && inferenceContext.inferredTypeParameters);
68434                             // If the original signature has a generic rest type, instantiation may produce a
68435                             // signature with different arity and we need to perform another arity check.
68436                             if (getNonArrayRestType(candidate) && !hasCorrectArity(node, args, checkCandidate, signatureHelpTrailingComma)) {
68437                                 candidateForArgumentArityError = checkCandidate;
68438                                 continue;
68439                             }
68440                         }
68441                         if (getSignatureApplicabilityError(node, args, checkCandidate, relation, argCheckMode, /*reportErrors*/ false, /*containingMessageChain*/ undefined)) {
68442                             // Give preference to error candidates that have no rest parameters (as they are more specific)
68443                             (candidatesForArgumentError || (candidatesForArgumentError = [])).push(checkCandidate);
68444                             continue;
68445                         }
68446                     }
68447                     candidates[candidateIndex] = checkCandidate;
68448                     return checkCandidate;
68449                 }
68450                 return undefined;
68451             }
68452         }
68453         // No signature was applicable. We have already reported the errors for the invalid signature.
68454         function getCandidateForOverloadFailure(node, candidates, args, hasCandidatesOutArray) {
68455             ts.Debug.assert(candidates.length > 0); // Else should not have called this.
68456             checkNodeDeferred(node);
68457             // Normally we will combine overloads. Skip this if they have type parameters since that's hard to combine.
68458             // Don't do this if there is a `candidatesOutArray`,
68459             // because then we want the chosen best candidate to be one of the overloads, not a combination.
68460             return hasCandidatesOutArray || candidates.length === 1 || candidates.some(function (c) { return !!c.typeParameters; })
68461                 ? pickLongestCandidateSignature(node, candidates, args)
68462                 : createUnionOfSignaturesForOverloadFailure(candidates);
68463         }
68464         function createUnionOfSignaturesForOverloadFailure(candidates) {
68465             var thisParameters = ts.mapDefined(candidates, function (c) { return c.thisParameter; });
68466             var thisParameter;
68467             if (thisParameters.length) {
68468                 thisParameter = createCombinedSymbolFromTypes(thisParameters, thisParameters.map(getTypeOfParameter));
68469             }
68470             var _a = ts.minAndMax(candidates, getNumNonRestParameters), minArgumentCount = _a.min, maxNonRestParam = _a.max;
68471             var parameters = [];
68472             var _loop_22 = function (i) {
68473                 var symbols = ts.mapDefined(candidates, function (s) { return signatureHasRestParameter(s) ?
68474                     i < s.parameters.length - 1 ? s.parameters[i] : ts.last(s.parameters) :
68475                     i < s.parameters.length ? s.parameters[i] : undefined; });
68476                 ts.Debug.assert(symbols.length !== 0);
68477                 parameters.push(createCombinedSymbolFromTypes(symbols, ts.mapDefined(candidates, function (candidate) { return tryGetTypeAtPosition(candidate, i); })));
68478             };
68479             for (var i = 0; i < maxNonRestParam; i++) {
68480                 _loop_22(i);
68481             }
68482             var restParameterSymbols = ts.mapDefined(candidates, function (c) { return signatureHasRestParameter(c) ? ts.last(c.parameters) : undefined; });
68483             var flags = 0 /* None */;
68484             if (restParameterSymbols.length !== 0) {
68485                 var type = createArrayType(getUnionType(ts.mapDefined(candidates, tryGetRestTypeOfSignature), 2 /* Subtype */));
68486                 parameters.push(createCombinedSymbolForOverloadFailure(restParameterSymbols, type));
68487                 flags |= 1 /* HasRestParameter */;
68488             }
68489             if (candidates.some(signatureHasLiteralTypes)) {
68490                 flags |= 2 /* HasLiteralTypes */;
68491             }
68492             return createSignature(candidates[0].declaration, 
68493             /*typeParameters*/ undefined, // Before calling this we tested for `!candidates.some(c => !!c.typeParameters)`.
68494             thisParameter, parameters, 
68495             /*resolvedReturnType*/ getIntersectionType(candidates.map(getReturnTypeOfSignature)), 
68496             /*typePredicate*/ undefined, minArgumentCount, flags);
68497         }
68498         function getNumNonRestParameters(signature) {
68499             var numParams = signature.parameters.length;
68500             return signatureHasRestParameter(signature) ? numParams - 1 : numParams;
68501         }
68502         function createCombinedSymbolFromTypes(sources, types) {
68503             return createCombinedSymbolForOverloadFailure(sources, getUnionType(types, 2 /* Subtype */));
68504         }
68505         function createCombinedSymbolForOverloadFailure(sources, type) {
68506             // This function is currently only used for erroneous overloads, so it's good enough to just use the first source.
68507             return createSymbolWithType(ts.first(sources), type);
68508         }
68509         function pickLongestCandidateSignature(node, candidates, args) {
68510             // Pick the longest signature. This way we can get a contextual type for cases like:
68511             //     declare function f(a: { xa: number; xb: number; }, b: number);
68512             //     f({ |
68513             // Also, use explicitly-supplied type arguments if they are provided, so we can get a contextual signature in cases like:
68514             //     declare function f<T>(k: keyof T);
68515             //     f<Foo>("
68516             var bestIndex = getLongestCandidateIndex(candidates, apparentArgumentCount === undefined ? args.length : apparentArgumentCount);
68517             var candidate = candidates[bestIndex];
68518             var typeParameters = candidate.typeParameters;
68519             if (!typeParameters) {
68520                 return candidate;
68521             }
68522             var typeArgumentNodes = callLikeExpressionMayHaveTypeArguments(node) ? node.typeArguments : undefined;
68523             var instantiated = typeArgumentNodes
68524                 ? createSignatureInstantiation(candidate, getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, ts.isInJSFile(node)))
68525                 : inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args);
68526             candidates[bestIndex] = instantiated;
68527             return instantiated;
68528         }
68529         function getTypeArgumentsFromNodes(typeArgumentNodes, typeParameters, isJs) {
68530             var typeArguments = typeArgumentNodes.map(getTypeOfNode);
68531             while (typeArguments.length > typeParameters.length) {
68532                 typeArguments.pop();
68533             }
68534             while (typeArguments.length < typeParameters.length) {
68535                 typeArguments.push(getConstraintOfTypeParameter(typeParameters[typeArguments.length]) || getDefaultTypeArgumentType(isJs));
68536             }
68537             return typeArguments;
68538         }
68539         function inferSignatureInstantiationForOverloadFailure(node, typeParameters, candidate, args) {
68540             var inferenceContext = createInferenceContext(typeParameters, candidate, /*flags*/ ts.isInJSFile(node) ? 2 /* AnyDefault */ : 0 /* None */);
68541             var typeArgumentTypes = inferTypeArguments(node, candidate, args, 4 /* SkipContextSensitive */ | 8 /* SkipGenericFunctions */, inferenceContext);
68542             return createSignatureInstantiation(candidate, typeArgumentTypes);
68543         }
68544         function getLongestCandidateIndex(candidates, argsCount) {
68545             var maxParamsIndex = -1;
68546             var maxParams = -1;
68547             for (var i = 0; i < candidates.length; i++) {
68548                 var candidate = candidates[i];
68549                 var paramCount = getParameterCount(candidate);
68550                 if (hasEffectiveRestParameter(candidate) || paramCount >= argsCount) {
68551                     return i;
68552                 }
68553                 if (paramCount > maxParams) {
68554                     maxParams = paramCount;
68555                     maxParamsIndex = i;
68556                 }
68557             }
68558             return maxParamsIndex;
68559         }
68560         function resolveCallExpression(node, candidatesOutArray, checkMode) {
68561             if (node.expression.kind === 105 /* SuperKeyword */) {
68562                 var superType = checkSuperExpression(node.expression);
68563                 if (isTypeAny(superType)) {
68564                     for (var _i = 0, _a = node.arguments; _i < _a.length; _i++) {
68565                         var arg = _a[_i];
68566                         checkExpression(arg); // Still visit arguments so they get marked for visibility, etc
68567                     }
68568                     return anySignature;
68569                 }
68570                 if (superType !== errorType) {
68571                     // In super call, the candidate signatures are the matching arity signatures of the base constructor function instantiated
68572                     // with the type arguments specified in the extends clause.
68573                     var baseTypeNode = ts.getEffectiveBaseTypeNode(ts.getContainingClass(node));
68574                     if (baseTypeNode) {
68575                         var baseConstructors = getInstantiatedConstructorsForTypeArguments(superType, baseTypeNode.typeArguments, baseTypeNode);
68576                         return resolveCall(node, baseConstructors, candidatesOutArray, checkMode, 0 /* None */);
68577                     }
68578                 }
68579                 return resolveUntypedCall(node);
68580             }
68581             var callChainFlags;
68582             var funcType = checkExpression(node.expression);
68583             if (ts.isCallChain(node)) {
68584                 var nonOptionalType = getOptionalExpressionType(funcType, node.expression);
68585                 callChainFlags = nonOptionalType === funcType ? 0 /* None */ :
68586                     ts.isOutermostOptionalChain(node) ? 8 /* IsOuterCallChain */ :
68587                         4 /* IsInnerCallChain */;
68588                 funcType = nonOptionalType;
68589             }
68590             else {
68591                 callChainFlags = 0 /* None */;
68592             }
68593             funcType = checkNonNullTypeWithReporter(funcType, node.expression, reportCannotInvokePossiblyNullOrUndefinedError);
68594             if (funcType === silentNeverType) {
68595                 return silentNeverSignature;
68596             }
68597             var apparentType = getApparentType(funcType);
68598             if (apparentType === errorType) {
68599                 // Another error has already been reported
68600                 return resolveErrorCall(node);
68601             }
68602             // Technically, this signatures list may be incomplete. We are taking the apparent type,
68603             // but we are not including call signatures that may have been added to the Object or
68604             // Function interface, since they have none by default. This is a bit of a leap of faith
68605             // that the user will not add any.
68606             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
68607             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
68608             // TS 1.0 Spec: 4.12
68609             // In an untyped function call no TypeArgs are permitted, Args can be any argument list, no contextual
68610             // types are provided for the argument expressions, and the result is always of type Any.
68611             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
68612                 // The unknownType indicates that an error already occurred (and was reported).  No
68613                 // need to report another error in this case.
68614                 if (funcType !== errorType && node.typeArguments) {
68615                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
68616                 }
68617                 return resolveUntypedCall(node);
68618             }
68619             // If FuncExpr's apparent type(section 3.8.1) is a function type, the call is a typed function call.
68620             // TypeScript employs overload resolution in typed function calls in order to support functions
68621             // with multiple call signatures.
68622             if (!callSignatures.length) {
68623                 if (numConstructSignatures) {
68624                     error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
68625                 }
68626                 else {
68627                     var relatedInformation = void 0;
68628                     if (node.arguments.length === 1) {
68629                         var text = ts.getSourceFileOfNode(node).text;
68630                         if (ts.isLineBreak(text.charCodeAt(ts.skipTrivia(text, node.expression.end, /* stopAfterLineBreak */ true) - 1))) {
68631                             relatedInformation = ts.createDiagnosticForNode(node.expression, ts.Diagnostics.Are_you_missing_a_semicolon);
68632                         }
68633                     }
68634                     invocationError(node.expression, apparentType, 0 /* Call */, relatedInformation);
68635                 }
68636                 return resolveErrorCall(node);
68637             }
68638             // When a call to a generic function is an argument to an outer call to a generic function for which
68639             // inference is in process, we have a choice to make. If the inner call relies on inferences made from
68640             // its contextual type to its return type, deferring the inner call processing allows the best possible
68641             // contextual type to accumulate. But if the outer call relies on inferences made from the return type of
68642             // the inner call, the inner call should be processed early. There's no sure way to know which choice is
68643             // right (only a full unification algorithm can determine that), so we resort to the following heuristic:
68644             // If no type arguments are specified in the inner call and at least one call signature is generic and
68645             // returns a function type, we choose to defer processing. This narrowly permits function composition
68646             // operators to flow inferences through return types, but otherwise processes calls right away. We
68647             // use the resolvingSignature singleton to indicate that we deferred processing. This result will be
68648             // propagated out and eventually turned into nonInferrableType (a type that is assignable to anything and
68649             // from which we never make inferences).
68650             if (checkMode & 8 /* SkipGenericFunctions */ && !node.typeArguments && callSignatures.some(isGenericFunctionReturningFunction)) {
68651                 skippedGenericFunction(node, checkMode);
68652                 return resolvingSignature;
68653             }
68654             // If the function is explicitly marked with `@class`, then it must be constructed.
68655             if (callSignatures.some(function (sig) { return ts.isInJSFile(sig.declaration) && !!ts.getJSDocClassTag(sig.declaration); })) {
68656                 error(node, ts.Diagnostics.Value_of_type_0_is_not_callable_Did_you_mean_to_include_new, typeToString(funcType));
68657                 return resolveErrorCall(node);
68658             }
68659             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, callChainFlags);
68660         }
68661         function isGenericFunctionReturningFunction(signature) {
68662             return !!(signature.typeParameters && isFunctionType(getReturnTypeOfSignature(signature)));
68663         }
68664         /**
68665          * TS 1.0 spec: 4.12
68666          * If FuncExpr is of type Any, or of an object type that has no call or construct signatures
68667          * but is a subtype of the Function interface, the call is an untyped function call.
68668          */
68669         function isUntypedFunctionCall(funcType, apparentFuncType, numCallSignatures, numConstructSignatures) {
68670             // We exclude union types because we may have a union of function types that happen to have no common signatures.
68671             return isTypeAny(funcType) || isTypeAny(apparentFuncType) && !!(funcType.flags & 262144 /* TypeParameter */) ||
68672                 !numCallSignatures && !numConstructSignatures && !(apparentFuncType.flags & (1048576 /* Union */ | 131072 /* Never */)) && isTypeAssignableTo(funcType, globalFunctionType);
68673         }
68674         function resolveNewExpression(node, candidatesOutArray, checkMode) {
68675             if (node.arguments && languageVersion < 1 /* ES5 */) {
68676                 var spreadIndex = getSpreadArgumentIndex(node.arguments);
68677                 if (spreadIndex >= 0) {
68678                     error(node.arguments[spreadIndex], ts.Diagnostics.Spread_operator_in_new_expressions_is_only_available_when_targeting_ECMAScript_5_and_higher);
68679                 }
68680             }
68681             var expressionType = checkNonNullExpression(node.expression);
68682             if (expressionType === silentNeverType) {
68683                 return silentNeverSignature;
68684             }
68685             // If expressionType's apparent type(section 3.8.1) is an object type with one or
68686             // more construct signatures, the expression is processed in the same manner as a
68687             // function call, but using the construct signatures as the initial set of candidate
68688             // signatures for overload resolution. The result type of the function call becomes
68689             // the result type of the operation.
68690             expressionType = getApparentType(expressionType);
68691             if (expressionType === errorType) {
68692                 // Another error has already been reported
68693                 return resolveErrorCall(node);
68694             }
68695             // TS 1.0 spec: 4.11
68696             // If expressionType is of type Any, Args can be any argument
68697             // list and the result of the operation is of type Any.
68698             if (isTypeAny(expressionType)) {
68699                 if (node.typeArguments) {
68700                     error(node, ts.Diagnostics.Untyped_function_calls_may_not_accept_type_arguments);
68701                 }
68702                 return resolveUntypedCall(node);
68703             }
68704             // Technically, this signatures list may be incomplete. We are taking the apparent type,
68705             // but we are not including construct signatures that may have been added to the Object or
68706             // Function interface, since they have none by default. This is a bit of a leap of faith
68707             // that the user will not add any.
68708             var constructSignatures = getSignaturesOfType(expressionType, 1 /* Construct */);
68709             if (constructSignatures.length) {
68710                 if (!isConstructorAccessible(node, constructSignatures[0])) {
68711                     return resolveErrorCall(node);
68712                 }
68713                 // If the expression is a class of abstract type, then it cannot be instantiated.
68714                 // Note, only class declarations can be declared abstract.
68715                 // In the case of a merged class-module or class-interface declaration,
68716                 // only the class declaration node will have the Abstract flag set.
68717                 var valueDecl = expressionType.symbol && ts.getClassLikeDeclarationOfSymbol(expressionType.symbol);
68718                 if (valueDecl && ts.hasSyntacticModifier(valueDecl, 128 /* Abstract */)) {
68719                     error(node, ts.Diagnostics.Cannot_create_an_instance_of_an_abstract_class);
68720                     return resolveErrorCall(node);
68721                 }
68722                 return resolveCall(node, constructSignatures, candidatesOutArray, checkMode, 0 /* None */);
68723             }
68724             // If expressionType's apparent type is an object type with no construct signatures but
68725             // one or more call signatures, the expression is processed as a function call. A compile-time
68726             // error occurs if the result of the function call is not Void. The type of the result of the
68727             // operation is Any. It is an error to have a Void this type.
68728             var callSignatures = getSignaturesOfType(expressionType, 0 /* Call */);
68729             if (callSignatures.length) {
68730                 var signature = resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
68731                 if (!noImplicitAny) {
68732                     if (signature.declaration && !isJSConstructor(signature.declaration) && getReturnTypeOfSignature(signature) !== voidType) {
68733                         error(node, ts.Diagnostics.Only_a_void_function_can_be_called_with_the_new_keyword);
68734                     }
68735                     if (getThisTypeOfSignature(signature) === voidType) {
68736                         error(node, ts.Diagnostics.A_function_that_is_called_with_the_new_keyword_cannot_have_a_this_type_that_is_void);
68737                     }
68738                 }
68739                 return signature;
68740             }
68741             invocationError(node.expression, expressionType, 1 /* Construct */);
68742             return resolveErrorCall(node);
68743         }
68744         function typeHasProtectedAccessibleBase(target, type) {
68745             var baseTypes = getBaseTypes(type);
68746             if (!ts.length(baseTypes)) {
68747                 return false;
68748             }
68749             var firstBase = baseTypes[0];
68750             if (firstBase.flags & 2097152 /* Intersection */) {
68751                 var types = firstBase.types;
68752                 var mixinFlags = findMixins(types);
68753                 var i = 0;
68754                 for (var _i = 0, _a = firstBase.types; _i < _a.length; _i++) {
68755                     var intersectionMember = _a[_i];
68756                     // We want to ignore mixin ctors
68757                     if (!mixinFlags[i]) {
68758                         if (ts.getObjectFlags(intersectionMember) & (1 /* Class */ | 2 /* Interface */)) {
68759                             if (intersectionMember.symbol === target) {
68760                                 return true;
68761                             }
68762                             if (typeHasProtectedAccessibleBase(target, intersectionMember)) {
68763                                 return true;
68764                             }
68765                         }
68766                     }
68767                     i++;
68768                 }
68769                 return false;
68770             }
68771             if (firstBase.symbol === target) {
68772                 return true;
68773             }
68774             return typeHasProtectedAccessibleBase(target, firstBase);
68775         }
68776         function isConstructorAccessible(node, signature) {
68777             if (!signature || !signature.declaration) {
68778                 return true;
68779             }
68780             var declaration = signature.declaration;
68781             var modifiers = ts.getSelectedEffectiveModifierFlags(declaration, 24 /* NonPublicAccessibilityModifier */);
68782             // (1) Public constructors and (2) constructor functions are always accessible.
68783             if (!modifiers || declaration.kind !== 166 /* Constructor */) {
68784                 return true;
68785             }
68786             var declaringClassDeclaration = ts.getClassLikeDeclarationOfSymbol(declaration.parent.symbol);
68787             var declaringClass = getDeclaredTypeOfSymbol(declaration.parent.symbol);
68788             // A private or protected constructor can only be instantiated within its own class (or a subclass, for protected)
68789             if (!isNodeWithinClass(node, declaringClassDeclaration)) {
68790                 var containingClass = ts.getContainingClass(node);
68791                 if (containingClass && modifiers & 16 /* Protected */) {
68792                     var containingType = getTypeOfNode(containingClass);
68793                     if (typeHasProtectedAccessibleBase(declaration.parent.symbol, containingType)) {
68794                         return true;
68795                     }
68796                 }
68797                 if (modifiers & 8 /* Private */) {
68798                     error(node, ts.Diagnostics.Constructor_of_class_0_is_private_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
68799                 }
68800                 if (modifiers & 16 /* Protected */) {
68801                     error(node, ts.Diagnostics.Constructor_of_class_0_is_protected_and_only_accessible_within_the_class_declaration, typeToString(declaringClass));
68802                 }
68803                 return false;
68804             }
68805             return true;
68806         }
68807         function invocationErrorDetails(errorTarget, apparentType, kind) {
68808             var errorInfo;
68809             var isCall = kind === 0 /* Call */;
68810             var awaitedType = getAwaitedType(apparentType);
68811             var maybeMissingAwait = awaitedType && getSignaturesOfType(awaitedType, kind).length > 0;
68812             if (apparentType.flags & 1048576 /* Union */) {
68813                 var types = apparentType.types;
68814                 var hasSignatures = false;
68815                 for (var _i = 0, types_19 = types; _i < types_19.length; _i++) {
68816                     var constituent = types_19[_i];
68817                     var signatures = getSignaturesOfType(constituent, kind);
68818                     if (signatures.length !== 0) {
68819                         hasSignatures = true;
68820                         if (errorInfo) {
68821                             // Bail early if we already have an error, no chance of "No constituent of type is callable"
68822                             break;
68823                         }
68824                     }
68825                     else {
68826                         // Error on the first non callable constituent only
68827                         if (!errorInfo) {
68828                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
68829                                 ts.Diagnostics.Type_0_has_no_call_signatures :
68830                                 ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(constituent));
68831                             errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
68832                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_callable :
68833                                 ts.Diagnostics.Not_all_constituents_of_type_0_are_constructable, typeToString(apparentType));
68834                         }
68835                         if (hasSignatures) {
68836                             // Bail early if we already found a siganture, no chance of "No constituent of type is callable"
68837                             break;
68838                         }
68839                     }
68840                 }
68841                 if (!hasSignatures) {
68842                     errorInfo = ts.chainDiagnosticMessages(
68843                     /* detials */ undefined, isCall ?
68844                         ts.Diagnostics.No_constituent_of_type_0_is_callable :
68845                         ts.Diagnostics.No_constituent_of_type_0_is_constructable, typeToString(apparentType));
68846                 }
68847                 if (!errorInfo) {
68848                     errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
68849                         ts.Diagnostics.Each_member_of_the_union_type_0_has_signatures_but_none_of_those_signatures_are_compatible_with_each_other :
68850                         ts.Diagnostics.Each_member_of_the_union_type_0_has_construct_signatures_but_none_of_those_signatures_are_compatible_with_each_other, typeToString(apparentType));
68851                 }
68852             }
68853             else {
68854                 errorInfo = ts.chainDiagnosticMessages(errorInfo, isCall ?
68855                     ts.Diagnostics.Type_0_has_no_call_signatures :
68856                     ts.Diagnostics.Type_0_has_no_construct_signatures, typeToString(apparentType));
68857             }
68858             var headMessage = isCall ? ts.Diagnostics.This_expression_is_not_callable : ts.Diagnostics.This_expression_is_not_constructable;
68859             // Diagnose get accessors incorrectly called as functions
68860             if (ts.isCallExpression(errorTarget.parent) && errorTarget.parent.arguments.length === 0) {
68861                 var resolvedSymbol = getNodeLinks(errorTarget).resolvedSymbol;
68862                 if (resolvedSymbol && resolvedSymbol.flags & 32768 /* GetAccessor */) {
68863                     headMessage = ts.Diagnostics.This_expression_is_not_callable_because_it_is_a_get_accessor_Did_you_mean_to_use_it_without;
68864                 }
68865             }
68866             return {
68867                 messageChain: ts.chainDiagnosticMessages(errorInfo, headMessage),
68868                 relatedMessage: maybeMissingAwait ? ts.Diagnostics.Did_you_forget_to_use_await : undefined,
68869             };
68870         }
68871         function invocationError(errorTarget, apparentType, kind, relatedInformation) {
68872             var _a = invocationErrorDetails(errorTarget, apparentType, kind), messageChain = _a.messageChain, relatedInfo = _a.relatedMessage;
68873             var diagnostic = ts.createDiagnosticForNodeFromMessageChain(errorTarget, messageChain);
68874             if (relatedInfo) {
68875                 ts.addRelatedInfo(diagnostic, ts.createDiagnosticForNode(errorTarget, relatedInfo));
68876             }
68877             if (ts.isCallExpression(errorTarget.parent)) {
68878                 var _b = getDiagnosticSpanForCallNode(errorTarget.parent, /* doNotIncludeArguments */ true), start = _b.start, length_7 = _b.length;
68879                 diagnostic.start = start;
68880                 diagnostic.length = length_7;
68881             }
68882             diagnostics.add(diagnostic);
68883             invocationErrorRecovery(apparentType, kind, relatedInformation ? ts.addRelatedInfo(diagnostic, relatedInformation) : diagnostic);
68884         }
68885         function invocationErrorRecovery(apparentType, kind, diagnostic) {
68886             if (!apparentType.symbol) {
68887                 return;
68888             }
68889             var importNode = getSymbolLinks(apparentType.symbol).originatingImport;
68890             // Create a diagnostic on the originating import if possible onto which we can attach a quickfix
68891             //  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
68892             if (importNode && !ts.isImportCall(importNode)) {
68893                 var sigs = getSignaturesOfType(getTypeOfSymbol(getSymbolLinks(apparentType.symbol).target), kind);
68894                 if (!sigs || !sigs.length)
68895                     return;
68896                 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));
68897             }
68898         }
68899         function resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode) {
68900             var tagType = checkExpression(node.tag);
68901             var apparentType = getApparentType(tagType);
68902             if (apparentType === errorType) {
68903                 // Another error has already been reported
68904                 return resolveErrorCall(node);
68905             }
68906             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
68907             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
68908             if (isUntypedFunctionCall(tagType, apparentType, callSignatures.length, numConstructSignatures)) {
68909                 return resolveUntypedCall(node);
68910             }
68911             if (!callSignatures.length) {
68912                 if (ts.isArrayLiteralExpression(node.parent)) {
68913                     var diagnostic = ts.createDiagnosticForNode(node.tag, ts.Diagnostics.It_is_likely_that_you_are_missing_a_comma_to_separate_these_two_template_expressions_They_form_a_tagged_template_expression_which_cannot_be_invoked);
68914                     diagnostics.add(diagnostic);
68915                     return resolveErrorCall(node);
68916                 }
68917                 invocationError(node.tag, apparentType, 0 /* Call */);
68918                 return resolveErrorCall(node);
68919             }
68920             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */);
68921         }
68922         /**
68923          * Gets the localized diagnostic head message to use for errors when resolving a decorator as a call expression.
68924          */
68925         function getDiagnosticHeadMessageForDecoratorResolution(node) {
68926             switch (node.parent.kind) {
68927                 case 252 /* ClassDeclaration */:
68928                 case 221 /* ClassExpression */:
68929                     return ts.Diagnostics.Unable_to_resolve_signature_of_class_decorator_when_called_as_an_expression;
68930                 case 160 /* Parameter */:
68931                     return ts.Diagnostics.Unable_to_resolve_signature_of_parameter_decorator_when_called_as_an_expression;
68932                 case 163 /* PropertyDeclaration */:
68933                     return ts.Diagnostics.Unable_to_resolve_signature_of_property_decorator_when_called_as_an_expression;
68934                 case 165 /* MethodDeclaration */:
68935                 case 167 /* GetAccessor */:
68936                 case 168 /* SetAccessor */:
68937                     return ts.Diagnostics.Unable_to_resolve_signature_of_method_decorator_when_called_as_an_expression;
68938                 default:
68939                     return ts.Debug.fail();
68940             }
68941         }
68942         /**
68943          * Resolves a decorator as if it were a call expression.
68944          */
68945         function resolveDecorator(node, candidatesOutArray, checkMode) {
68946             var funcType = checkExpression(node.expression);
68947             var apparentType = getApparentType(funcType);
68948             if (apparentType === errorType) {
68949                 return resolveErrorCall(node);
68950             }
68951             var callSignatures = getSignaturesOfType(apparentType, 0 /* Call */);
68952             var numConstructSignatures = getSignaturesOfType(apparentType, 1 /* Construct */).length;
68953             if (isUntypedFunctionCall(funcType, apparentType, callSignatures.length, numConstructSignatures)) {
68954                 return resolveUntypedCall(node);
68955             }
68956             if (isPotentiallyUncalledDecorator(node, callSignatures)) {
68957                 var nodeStr = ts.getTextOfNode(node.expression, /*includeTrivia*/ false);
68958                 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);
68959                 return resolveErrorCall(node);
68960             }
68961             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
68962             if (!callSignatures.length) {
68963                 var errorDetails = invocationErrorDetails(node.expression, apparentType, 0 /* Call */);
68964                 var messageChain = ts.chainDiagnosticMessages(errorDetails.messageChain, headMessage);
68965                 var diag = ts.createDiagnosticForNodeFromMessageChain(node.expression, messageChain);
68966                 if (errorDetails.relatedMessage) {
68967                     ts.addRelatedInfo(diag, ts.createDiagnosticForNode(node.expression, errorDetails.relatedMessage));
68968                 }
68969                 diagnostics.add(diag);
68970                 invocationErrorRecovery(apparentType, 0 /* Call */, diag);
68971                 return resolveErrorCall(node);
68972             }
68973             return resolveCall(node, callSignatures, candidatesOutArray, checkMode, 0 /* None */, headMessage);
68974         }
68975         function createSignatureForJSXIntrinsic(node, result) {
68976             var namespace = getJsxNamespaceAt(node);
68977             var exports = namespace && getExportsOfSymbol(namespace);
68978             // We fake up a SFC signature for each intrinsic, however a more specific per-element signature drawn from the JSX declaration
68979             // file would probably be preferable.
68980             var typeSymbol = exports && getSymbol(exports, JsxNames.Element, 788968 /* Type */);
68981             var returnNode = typeSymbol && nodeBuilder.symbolToEntityName(typeSymbol, 788968 /* Type */, node);
68982             var declaration = ts.factory.createFunctionTypeNode(/*typeParameters*/ undefined, [ts.factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotdotdot*/ undefined, "props", /*questionMark*/ undefined, nodeBuilder.typeToTypeNode(result, node))], returnNode ? ts.factory.createTypeReferenceNode(returnNode, /*typeArguments*/ undefined) : ts.factory.createKeywordTypeNode(128 /* AnyKeyword */));
68983             var parameterSymbol = createSymbol(1 /* FunctionScopedVariable */, "props");
68984             parameterSymbol.type = result;
68985             return createSignature(declaration, 
68986             /*typeParameters*/ undefined, 
68987             /*thisParameter*/ undefined, [parameterSymbol], typeSymbol ? getDeclaredTypeOfSymbol(typeSymbol) : errorType, 
68988             /*returnTypePredicate*/ undefined, 1, 0 /* None */);
68989         }
68990         function resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode) {
68991             if (isJsxIntrinsicIdentifier(node.tagName)) {
68992                 var result = getIntrinsicAttributesTypeFromJsxOpeningLikeElement(node);
68993                 var fakeSignature = createSignatureForJSXIntrinsic(node, result);
68994                 checkTypeAssignableToAndOptionallyElaborate(checkExpressionWithContextualType(node.attributes, getEffectiveFirstArgumentForJsxSignature(fakeSignature, node), /*mapper*/ undefined, 0 /* Normal */), result, node.tagName, node.attributes);
68995                 if (ts.length(node.typeArguments)) {
68996                     ts.forEach(node.typeArguments, checkSourceElement);
68997                     diagnostics.add(ts.createDiagnosticForNodeArray(ts.getSourceFileOfNode(node), node.typeArguments, ts.Diagnostics.Expected_0_type_arguments_but_got_1, 0, ts.length(node.typeArguments)));
68998                 }
68999                 return fakeSignature;
69000             }
69001             var exprTypes = checkExpression(node.tagName);
69002             var apparentType = getApparentType(exprTypes);
69003             if (apparentType === errorType) {
69004                 return resolveErrorCall(node);
69005             }
69006             var signatures = getUninstantiatedJsxSignaturesOfType(exprTypes, node);
69007             if (isUntypedFunctionCall(exprTypes, apparentType, signatures.length, /*constructSignatures*/ 0)) {
69008                 return resolveUntypedCall(node);
69009             }
69010             if (signatures.length === 0) {
69011                 // We found no signatures at all, which is an error
69012                 error(node.tagName, ts.Diagnostics.JSX_element_type_0_does_not_have_any_construct_or_call_signatures, ts.getTextOfNode(node.tagName));
69013                 return resolveErrorCall(node);
69014             }
69015             return resolveCall(node, signatures, candidatesOutArray, checkMode, 0 /* None */);
69016         }
69017         /**
69018          * Sometimes, we have a decorator that could accept zero arguments,
69019          * but is receiving too many arguments as part of the decorator invocation.
69020          * In those cases, a user may have meant to *call* the expression before using it as a decorator.
69021          */
69022         function isPotentiallyUncalledDecorator(decorator, signatures) {
69023             return signatures.length && ts.every(signatures, function (signature) {
69024                 return signature.minArgumentCount === 0 &&
69025                     !signatureHasRestParameter(signature) &&
69026                     signature.parameters.length < getDecoratorArgumentCount(decorator, signature);
69027             });
69028         }
69029         function resolveSignature(node, candidatesOutArray, checkMode) {
69030             switch (node.kind) {
69031                 case 203 /* CallExpression */:
69032                     return resolveCallExpression(node, candidatesOutArray, checkMode);
69033                 case 204 /* NewExpression */:
69034                     return resolveNewExpression(node, candidatesOutArray, checkMode);
69035                 case 205 /* TaggedTemplateExpression */:
69036                     return resolveTaggedTemplateExpression(node, candidatesOutArray, checkMode);
69037                 case 161 /* Decorator */:
69038                     return resolveDecorator(node, candidatesOutArray, checkMode);
69039                 case 275 /* JsxOpeningElement */:
69040                 case 274 /* JsxSelfClosingElement */:
69041                     return resolveJsxOpeningLikeElement(node, candidatesOutArray, checkMode);
69042             }
69043             throw ts.Debug.assertNever(node, "Branch in 'resolveSignature' should be unreachable.");
69044         }
69045         /**
69046          * Resolve a signature of a given call-like expression.
69047          * @param node a call-like expression to try resolve a signature for
69048          * @param candidatesOutArray an array of signature to be filled in by the function. It is passed by signature help in the language service;
69049          *                           the function will fill it up with appropriate candidate signatures
69050          * @return a signature of the call-like expression or undefined if one can't be found
69051          */
69052         function getResolvedSignature(node, candidatesOutArray, checkMode) {
69053             var links = getNodeLinks(node);
69054             // If getResolvedSignature has already been called, we will have cached the resolvedSignature.
69055             // However, it is possible that either candidatesOutArray was not passed in the first time,
69056             // or that a different candidatesOutArray was passed in. Therefore, we need to redo the work
69057             // to correctly fill the candidatesOutArray.
69058             var cached = links.resolvedSignature;
69059             if (cached && cached !== resolvingSignature && !candidatesOutArray) {
69060                 return cached;
69061             }
69062             links.resolvedSignature = resolvingSignature;
69063             var result = resolveSignature(node, candidatesOutArray, checkMode || 0 /* Normal */);
69064             // When CheckMode.SkipGenericFunctions is set we use resolvingSignature to indicate that call
69065             // resolution should be deferred.
69066             if (result !== resolvingSignature) {
69067                 // If signature resolution originated in control flow type analysis (for example to compute the
69068                 // assigned type in a flow assignment) we don't cache the result as it may be based on temporary
69069                 // types from the control flow analysis.
69070                 links.resolvedSignature = flowLoopStart === flowLoopCount ? result : cached;
69071             }
69072             return result;
69073         }
69074         /**
69075          * Indicates whether a declaration can be treated as a constructor in a JavaScript
69076          * file.
69077          */
69078         function isJSConstructor(node) {
69079             var _a;
69080             if (!node || !ts.isInJSFile(node)) {
69081                 return false;
69082             }
69083             var func = ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) ? node :
69084                 ts.isVariableDeclaration(node) && node.initializer && ts.isFunctionExpression(node.initializer) ? node.initializer :
69085                     undefined;
69086             if (func) {
69087                 // If the node has a @class tag, treat it like a constructor.
69088                 if (ts.getJSDocClassTag(node))
69089                     return true;
69090                 // If the symbol of the node has members, treat it like a constructor.
69091                 var symbol = getSymbolOfNode(func);
69092                 return !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.members) === null || _a === void 0 ? void 0 : _a.size);
69093             }
69094             return false;
69095         }
69096         function mergeJSSymbols(target, source) {
69097             var _a, _b;
69098             if (source) {
69099                 var links = getSymbolLinks(source);
69100                 if (!links.inferredClassSymbol || !links.inferredClassSymbol.has(getSymbolId(target))) {
69101                     var inferred = ts.isTransientSymbol(target) ? target : cloneSymbol(target);
69102                     inferred.exports = inferred.exports || ts.createSymbolTable();
69103                     inferred.members = inferred.members || ts.createSymbolTable();
69104                     inferred.flags |= source.flags & 32 /* Class */;
69105                     if ((_a = source.exports) === null || _a === void 0 ? void 0 : _a.size) {
69106                         mergeSymbolTable(inferred.exports, source.exports);
69107                     }
69108                     if ((_b = source.members) === null || _b === void 0 ? void 0 : _b.size) {
69109                         mergeSymbolTable(inferred.members, source.members);
69110                     }
69111                     (links.inferredClassSymbol || (links.inferredClassSymbol = new ts.Map())).set(getSymbolId(inferred), inferred);
69112                     return inferred;
69113                 }
69114                 return links.inferredClassSymbol.get(getSymbolId(target));
69115             }
69116         }
69117         function getAssignedClassSymbol(decl) {
69118             var _a;
69119             var assignmentSymbol = decl && getSymbolOfExpando(decl, /*allowDeclaration*/ true);
69120             var prototype = (_a = assignmentSymbol === null || assignmentSymbol === void 0 ? void 0 : assignmentSymbol.exports) === null || _a === void 0 ? void 0 : _a.get("prototype");
69121             var init = (prototype === null || prototype === void 0 ? void 0 : prototype.valueDeclaration) && getAssignedJSPrototype(prototype.valueDeclaration);
69122             return init ? getSymbolOfNode(init) : undefined;
69123         }
69124         function getSymbolOfExpando(node, allowDeclaration) {
69125             if (!node.parent) {
69126                 return undefined;
69127             }
69128             var name;
69129             var decl;
69130             if (ts.isVariableDeclaration(node.parent) && node.parent.initializer === node) {
69131                 if (!ts.isInJSFile(node) && !(ts.isVarConst(node.parent) && ts.isFunctionLikeDeclaration(node))) {
69132                     return undefined;
69133                 }
69134                 name = node.parent.name;
69135                 decl = node.parent;
69136             }
69137             else if (ts.isBinaryExpression(node.parent)) {
69138                 var parentNode = node.parent;
69139                 var parentNodeOperator = node.parent.operatorToken.kind;
69140                 if (parentNodeOperator === 62 /* EqualsToken */ && (allowDeclaration || parentNode.right === node)) {
69141                     name = parentNode.left;
69142                     decl = name;
69143                 }
69144                 else if (parentNodeOperator === 56 /* BarBarToken */ || parentNodeOperator === 60 /* QuestionQuestionToken */) {
69145                     if (ts.isVariableDeclaration(parentNode.parent) && parentNode.parent.initializer === parentNode) {
69146                         name = parentNode.parent.name;
69147                         decl = parentNode.parent;
69148                     }
69149                     else if (ts.isBinaryExpression(parentNode.parent) && parentNode.parent.operatorToken.kind === 62 /* EqualsToken */ && (allowDeclaration || parentNode.parent.right === parentNode)) {
69150                         name = parentNode.parent.left;
69151                         decl = name;
69152                     }
69153                     if (!name || !ts.isBindableStaticNameExpression(name) || !ts.isSameEntityName(name, parentNode.left)) {
69154                         return undefined;
69155                     }
69156                 }
69157             }
69158             else if (allowDeclaration && ts.isFunctionDeclaration(node)) {
69159                 name = node.name;
69160                 decl = node;
69161             }
69162             if (!decl || !name || (!allowDeclaration && !ts.getExpandoInitializer(node, ts.isPrototypeAccess(name)))) {
69163                 return undefined;
69164             }
69165             return getSymbolOfNode(decl);
69166         }
69167         function getAssignedJSPrototype(node) {
69168             if (!node.parent) {
69169                 return false;
69170             }
69171             var parent = node.parent;
69172             while (parent && parent.kind === 201 /* PropertyAccessExpression */) {
69173                 parent = parent.parent;
69174             }
69175             if (parent && ts.isBinaryExpression(parent) && ts.isPrototypeAccess(parent.left) && parent.operatorToken.kind === 62 /* EqualsToken */) {
69176                 var right = ts.getInitializerOfBinaryExpression(parent);
69177                 return ts.isObjectLiteralExpression(right) && right;
69178             }
69179         }
69180         /**
69181          * Syntactically and semantically checks a call or new expression.
69182          * @param node The call/new expression to be checked.
69183          * @returns On success, the expression's signature's return type. On failure, anyType.
69184          */
69185         function checkCallExpression(node, checkMode) {
69186             var _a;
69187             if (!checkGrammarTypeArguments(node, node.typeArguments))
69188                 checkGrammarArguments(node.arguments);
69189             var signature = getResolvedSignature(node, /*candidatesOutArray*/ undefined, checkMode);
69190             if (signature === resolvingSignature) {
69191                 // CheckMode.SkipGenericFunctions is enabled and this is a call to a generic function that
69192                 // returns a function type. We defer checking and return nonInferrableType.
69193                 return nonInferrableType;
69194             }
69195             checkDeprecatedSignature(signature, node);
69196             if (node.expression.kind === 105 /* SuperKeyword */) {
69197                 return voidType;
69198             }
69199             if (node.kind === 204 /* NewExpression */) {
69200                 var declaration = signature.declaration;
69201                 if (declaration &&
69202                     declaration.kind !== 166 /* Constructor */ &&
69203                     declaration.kind !== 170 /* ConstructSignature */ &&
69204                     declaration.kind !== 175 /* ConstructorType */ &&
69205                     !ts.isJSDocConstructSignature(declaration) &&
69206                     !isJSConstructor(declaration)) {
69207                     // When resolved signature is a call signature (and not a construct signature) the result type is any
69208                     if (noImplicitAny) {
69209                         error(node, ts.Diagnostics.new_expression_whose_target_lacks_a_construct_signature_implicitly_has_an_any_type);
69210                     }
69211                     return anyType;
69212                 }
69213             }
69214             // In JavaScript files, calls to any identifier 'require' are treated as external module imports
69215             if (ts.isInJSFile(node) && isCommonJsRequire(node)) {
69216                 return resolveExternalModuleTypeByLiteral(node.arguments[0]);
69217             }
69218             var returnType = getReturnTypeOfSignature(signature);
69219             // Treat any call to the global 'Symbol' function that is part of a const variable or readonly property
69220             // as a fresh unique symbol literal type.
69221             if (returnType.flags & 12288 /* ESSymbolLike */ && isSymbolOrSymbolForCall(node)) {
69222                 return getESSymbolLikeTypeForNode(ts.walkUpParenthesizedExpressions(node.parent));
69223             }
69224             if (node.kind === 203 /* CallExpression */ && node.parent.kind === 233 /* ExpressionStatement */ &&
69225                 returnType.flags & 16384 /* Void */ && getTypePredicateOfSignature(signature)) {
69226                 if (!ts.isDottedName(node.expression)) {
69227                     error(node.expression, ts.Diagnostics.Assertions_require_the_call_target_to_be_an_identifier_or_qualified_name);
69228                 }
69229                 else if (!getEffectsSignature(node)) {
69230                     var diagnostic = error(node.expression, ts.Diagnostics.Assertions_require_every_name_in_the_call_target_to_be_declared_with_an_explicit_type_annotation);
69231                     getTypeOfDottedName(node.expression, diagnostic);
69232                 }
69233             }
69234             if (ts.isInJSFile(node)) {
69235                 var jsSymbol = getSymbolOfExpando(node, /*allowDeclaration*/ false);
69236                 if ((_a = jsSymbol === null || jsSymbol === void 0 ? void 0 : jsSymbol.exports) === null || _a === void 0 ? void 0 : _a.size) {
69237                     var jsAssignmentType = createAnonymousType(jsSymbol, jsSymbol.exports, ts.emptyArray, ts.emptyArray, undefined, undefined);
69238                     jsAssignmentType.objectFlags |= 16384 /* JSLiteral */;
69239                     return getIntersectionType([returnType, jsAssignmentType]);
69240                 }
69241             }
69242             return returnType;
69243         }
69244         function checkDeprecatedSignature(signature, node) {
69245             if (signature.declaration && signature.declaration.flags & 134217728 /* Deprecated */) {
69246                 var suggestionNode = getDeprecatedSuggestionNode(node);
69247                 errorOrSuggestion(/*isError*/ false, suggestionNode, ts.Diagnostics._0_is_deprecated, signatureToString(signature));
69248             }
69249         }
69250         function getDeprecatedSuggestionNode(node) {
69251             node = ts.skipParentheses(node);
69252             switch (node.kind) {
69253                 case 203 /* CallExpression */:
69254                 case 161 /* Decorator */:
69255                 case 204 /* NewExpression */:
69256                     return getDeprecatedSuggestionNode(node.expression);
69257                 case 205 /* TaggedTemplateExpression */:
69258                     return getDeprecatedSuggestionNode(node.tag);
69259                 case 275 /* JsxOpeningElement */:
69260                 case 274 /* JsxSelfClosingElement */:
69261                     return getDeprecatedSuggestionNode(node.tagName);
69262                 case 202 /* ElementAccessExpression */:
69263                     return node.argumentExpression;
69264                 case 201 /* PropertyAccessExpression */:
69265                     return node.name;
69266                 case 173 /* TypeReference */:
69267                     var typeReference = node;
69268                     return ts.isQualifiedName(typeReference.typeName) ? typeReference.typeName.right : typeReference;
69269                 default:
69270                     return node;
69271             }
69272         }
69273         function isSymbolOrSymbolForCall(node) {
69274             if (!ts.isCallExpression(node))
69275                 return false;
69276             var left = node.expression;
69277             if (ts.isPropertyAccessExpression(left) && left.name.escapedText === "for") {
69278                 left = left.expression;
69279             }
69280             if (!ts.isIdentifier(left) || left.escapedText !== "Symbol") {
69281                 return false;
69282             }
69283             // make sure `Symbol` is the global symbol
69284             var globalESSymbol = getGlobalESSymbolConstructorSymbol(/*reportErrors*/ false);
69285             if (!globalESSymbol) {
69286                 return false;
69287             }
69288             return globalESSymbol === resolveName(left, "Symbol", 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
69289         }
69290         function checkImportCallExpression(node) {
69291             // Check grammar of dynamic import
69292             if (!checkGrammarArguments(node.arguments))
69293                 checkGrammarImportCallExpression(node);
69294             if (node.arguments.length === 0) {
69295                 return createPromiseReturnType(node, anyType);
69296             }
69297             var specifier = node.arguments[0];
69298             var specifierType = checkExpressionCached(specifier);
69299             // Even though multiple arguments is grammatically incorrect, type-check extra arguments for completion
69300             for (var i = 1; i < node.arguments.length; ++i) {
69301                 checkExpressionCached(node.arguments[i]);
69302             }
69303             if (specifierType.flags & 32768 /* Undefined */ || specifierType.flags & 65536 /* Null */ || !isTypeAssignableTo(specifierType, stringType)) {
69304                 error(specifier, ts.Diagnostics.Dynamic_import_s_specifier_must_be_of_type_string_but_here_has_type_0, typeToString(specifierType));
69305             }
69306             // resolveExternalModuleName will return undefined if the moduleReferenceExpression is not a string literal
69307             var moduleSymbol = resolveExternalModuleName(node, specifier);
69308             if (moduleSymbol) {
69309                 var esModuleSymbol = resolveESModuleSymbol(moduleSymbol, specifier, /*dontRecursivelyResolve*/ true, /*suppressUsageError*/ false);
69310                 if (esModuleSymbol) {
69311                     return createPromiseReturnType(node, getTypeWithSyntheticDefaultImportType(getTypeOfSymbol(esModuleSymbol), esModuleSymbol, moduleSymbol));
69312                 }
69313             }
69314             return createPromiseReturnType(node, anyType);
69315         }
69316         function getTypeWithSyntheticDefaultImportType(type, symbol, originalSymbol) {
69317             if (allowSyntheticDefaultImports && type && type !== errorType) {
69318                 var synthType = type;
69319                 if (!synthType.syntheticType) {
69320                     var file = ts.find(originalSymbol.declarations, ts.isSourceFile);
69321                     var hasSyntheticDefault = canHaveSyntheticDefault(file, originalSymbol, /*dontResolveAlias*/ false);
69322                     if (hasSyntheticDefault) {
69323                         var memberTable = ts.createSymbolTable();
69324                         var newSymbol = createSymbol(2097152 /* Alias */, "default" /* Default */);
69325                         newSymbol.parent = originalSymbol;
69326                         newSymbol.nameType = getLiteralType("default");
69327                         newSymbol.target = resolveSymbol(symbol);
69328                         memberTable.set("default" /* Default */, newSymbol);
69329                         var anonymousSymbol = createSymbol(2048 /* TypeLiteral */, "__type" /* Type */);
69330                         var defaultContainingObject = createAnonymousType(anonymousSymbol, memberTable, ts.emptyArray, ts.emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
69331                         anonymousSymbol.type = defaultContainingObject;
69332                         synthType.syntheticType = isValidSpreadType(type) ? getSpreadType(type, defaultContainingObject, anonymousSymbol, /*objectFlags*/ 0, /*readonly*/ false) : defaultContainingObject;
69333                     }
69334                     else {
69335                         synthType.syntheticType = type;
69336                     }
69337                 }
69338                 return synthType.syntheticType;
69339             }
69340             return type;
69341         }
69342         function isCommonJsRequire(node) {
69343             if (!ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
69344                 return false;
69345             }
69346             // Make sure require is not a local function
69347             if (!ts.isIdentifier(node.expression))
69348                 return ts.Debug.fail();
69349             var resolvedRequire = resolveName(node.expression, node.expression.escapedText, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true); // TODO: GH#18217
69350             if (resolvedRequire === requireSymbol) {
69351                 return true;
69352             }
69353             // project includes symbol named 'require' - make sure that it is ambient and local non-alias
69354             if (resolvedRequire.flags & 2097152 /* Alias */) {
69355                 return false;
69356             }
69357             var targetDeclarationKind = resolvedRequire.flags & 16 /* Function */
69358                 ? 251 /* FunctionDeclaration */
69359                 : resolvedRequire.flags & 3 /* Variable */
69360                     ? 249 /* VariableDeclaration */
69361                     : 0 /* Unknown */;
69362             if (targetDeclarationKind !== 0 /* Unknown */) {
69363                 var decl = ts.getDeclarationOfKind(resolvedRequire, targetDeclarationKind);
69364                 // function/variable declaration should be ambient
69365                 return !!decl && !!(decl.flags & 8388608 /* Ambient */);
69366             }
69367             return false;
69368         }
69369         function checkTaggedTemplateExpression(node) {
69370             if (!checkGrammarTaggedTemplateChain(node))
69371                 checkGrammarTypeArguments(node, node.typeArguments);
69372             if (languageVersion < 2 /* ES2015 */) {
69373                 checkExternalEmitHelpers(node, 524288 /* MakeTemplateObject */);
69374             }
69375             var signature = getResolvedSignature(node);
69376             checkDeprecatedSignature(signature, node);
69377             return getReturnTypeOfSignature(signature);
69378         }
69379         function checkAssertion(node) {
69380             return checkAssertionWorker(node, node.type, node.expression);
69381         }
69382         function isValidConstAssertionArgument(node) {
69383             switch (node.kind) {
69384                 case 10 /* StringLiteral */:
69385                 case 14 /* NoSubstitutionTemplateLiteral */:
69386                 case 8 /* NumericLiteral */:
69387                 case 9 /* BigIntLiteral */:
69388                 case 109 /* TrueKeyword */:
69389                 case 94 /* FalseKeyword */:
69390                 case 199 /* ArrayLiteralExpression */:
69391                 case 200 /* ObjectLiteralExpression */:
69392                 case 218 /* TemplateExpression */:
69393                     return true;
69394                 case 207 /* ParenthesizedExpression */:
69395                     return isValidConstAssertionArgument(node.expression);
69396                 case 214 /* PrefixUnaryExpression */:
69397                     var op = node.operator;
69398                     var arg = node.operand;
69399                     return op === 40 /* MinusToken */ && (arg.kind === 8 /* NumericLiteral */ || arg.kind === 9 /* BigIntLiteral */) ||
69400                         op === 39 /* PlusToken */ && arg.kind === 8 /* NumericLiteral */;
69401                 case 201 /* PropertyAccessExpression */:
69402                 case 202 /* ElementAccessExpression */:
69403                     var expr = node.expression;
69404                     if (ts.isIdentifier(expr)) {
69405                         var symbol = getSymbolAtLocation(expr);
69406                         if (symbol && symbol.flags & 2097152 /* Alias */) {
69407                             symbol = resolveAlias(symbol);
69408                         }
69409                         return !!(symbol && (symbol.flags & 384 /* Enum */) && getEnumKind(symbol) === 1 /* Literal */);
69410                     }
69411             }
69412             return false;
69413         }
69414         function checkAssertionWorker(errNode, type, expression, checkMode) {
69415             var exprType = checkExpression(expression, checkMode);
69416             if (ts.isConstTypeReference(type)) {
69417                 if (!isValidConstAssertionArgument(expression)) {
69418                     error(expression, ts.Diagnostics.A_const_assertions_can_only_be_applied_to_references_to_enum_members_or_string_number_boolean_array_or_object_literals);
69419                 }
69420                 return getRegularTypeOfLiteralType(exprType);
69421             }
69422             checkSourceElement(type);
69423             exprType = getRegularTypeOfObjectLiteral(getBaseTypeOfLiteralType(exprType));
69424             var targetType = getTypeFromTypeNode(type);
69425             if (produceDiagnostics && targetType !== errorType) {
69426                 var widenedType = getWidenedType(exprType);
69427                 if (!isTypeComparableTo(targetType, widenedType)) {
69428                     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);
69429                 }
69430             }
69431             return targetType;
69432         }
69433         function checkNonNullChain(node) {
69434             var leftType = checkExpression(node.expression);
69435             var nonOptionalType = getOptionalExpressionType(leftType, node.expression);
69436             return propagateOptionalTypeMarker(getNonNullableType(nonOptionalType), node, nonOptionalType !== leftType);
69437         }
69438         function checkNonNullAssertion(node) {
69439             return node.flags & 32 /* OptionalChain */ ? checkNonNullChain(node) :
69440                 getNonNullableType(checkExpression(node.expression));
69441         }
69442         function checkMetaProperty(node) {
69443             checkGrammarMetaProperty(node);
69444             if (node.keywordToken === 102 /* NewKeyword */) {
69445                 return checkNewTargetMetaProperty(node);
69446             }
69447             if (node.keywordToken === 99 /* ImportKeyword */) {
69448                 return checkImportMetaProperty(node);
69449             }
69450             return ts.Debug.assertNever(node.keywordToken);
69451         }
69452         function checkNewTargetMetaProperty(node) {
69453             var container = ts.getNewTargetContainer(node);
69454             if (!container) {
69455                 error(node, ts.Diagnostics.Meta_property_0_is_only_allowed_in_the_body_of_a_function_declaration_function_expression_or_constructor, "new.target");
69456                 return errorType;
69457             }
69458             else if (container.kind === 166 /* Constructor */) {
69459                 var symbol = getSymbolOfNode(container.parent);
69460                 return getTypeOfSymbol(symbol);
69461             }
69462             else {
69463                 var symbol = getSymbolOfNode(container);
69464                 return getTypeOfSymbol(symbol);
69465             }
69466         }
69467         function checkImportMetaProperty(node) {
69468             if (moduleKind !== ts.ModuleKind.ES2020 && moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) {
69469                 error(node, ts.Diagnostics.The_import_meta_meta_property_is_only_allowed_when_the_module_option_is_es2020_esnext_or_system);
69470             }
69471             var file = ts.getSourceFileOfNode(node);
69472             ts.Debug.assert(!!(file.flags & 2097152 /* PossiblyContainsImportMeta */), "Containing file is missing import meta node flag.");
69473             ts.Debug.assert(!!file.externalModuleIndicator, "Containing file should be a module.");
69474             return node.name.escapedText === "meta" ? getGlobalImportMetaType() : errorType;
69475         }
69476         function getTypeOfParameter(symbol) {
69477             var type = getTypeOfSymbol(symbol);
69478             if (strictNullChecks) {
69479                 var declaration = symbol.valueDeclaration;
69480                 if (declaration && ts.hasInitializer(declaration)) {
69481                     return getOptionalType(type);
69482                 }
69483             }
69484             return type;
69485         }
69486         function getTupleElementLabel(d) {
69487             ts.Debug.assert(ts.isIdentifier(d.name)); // Parameter declarations could be binding patterns, but we only allow identifier names
69488             return d.name.escapedText;
69489         }
69490         function getParameterNameAtPosition(signature, pos, overrideRestType) {
69491             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69492             if (pos < paramCount) {
69493                 return signature.parameters[pos].escapedName;
69494             }
69495             var restParameter = signature.parameters[paramCount] || unknownSymbol;
69496             var restType = overrideRestType || getTypeOfSymbol(restParameter);
69497             if (isTupleType(restType)) {
69498                 var associatedNames = restType.target.labeledElementDeclarations;
69499                 var index = pos - paramCount;
69500                 return associatedNames && getTupleElementLabel(associatedNames[index]) || restParameter.escapedName + "_" + index;
69501             }
69502             return restParameter.escapedName;
69503         }
69504         function isValidDeclarationForTupleLabel(d) {
69505             return d.kind === 192 /* NamedTupleMember */ || (ts.isParameter(d) && d.name && ts.isIdentifier(d.name));
69506         }
69507         function getNameableDeclarationAtPosition(signature, pos) {
69508             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69509             if (pos < paramCount) {
69510                 var decl = signature.parameters[pos].valueDeclaration;
69511                 return decl && isValidDeclarationForTupleLabel(decl) ? decl : undefined;
69512             }
69513             var restParameter = signature.parameters[paramCount] || unknownSymbol;
69514             var restType = getTypeOfSymbol(restParameter);
69515             if (isTupleType(restType)) {
69516                 var associatedNames = restType.target.labeledElementDeclarations;
69517                 var index = pos - paramCount;
69518                 return associatedNames && associatedNames[index];
69519             }
69520             return restParameter.valueDeclaration && isValidDeclarationForTupleLabel(restParameter.valueDeclaration) ? restParameter.valueDeclaration : undefined;
69521         }
69522         function getTypeAtPosition(signature, pos) {
69523             return tryGetTypeAtPosition(signature, pos) || anyType;
69524         }
69525         function tryGetTypeAtPosition(signature, pos) {
69526             var paramCount = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69527             if (pos < paramCount) {
69528                 return getTypeOfParameter(signature.parameters[pos]);
69529             }
69530             if (signatureHasRestParameter(signature)) {
69531                 // We want to return the value undefined for an out of bounds parameter position,
69532                 // so we need to check bounds here before calling getIndexedAccessType (which
69533                 // otherwise would return the type 'undefined').
69534                 var restType = getTypeOfSymbol(signature.parameters[paramCount]);
69535                 var index = pos - paramCount;
69536                 if (!isTupleType(restType) || restType.target.hasRestElement || index < restType.target.fixedLength) {
69537                     return getIndexedAccessType(restType, getLiteralType(index));
69538                 }
69539             }
69540             return undefined;
69541         }
69542         function getRestTypeAtPosition(source, pos) {
69543             var parameterCount = getParameterCount(source);
69544             var minArgumentCount = getMinArgumentCount(source);
69545             var restType = getEffectiveRestType(source);
69546             if (restType && pos >= parameterCount - 1) {
69547                 return pos === parameterCount - 1 ? restType : createArrayType(getIndexedAccessType(restType, numberType));
69548             }
69549             var types = [];
69550             var flags = [];
69551             var names = [];
69552             for (var i = pos; i < parameterCount; i++) {
69553                 if (!restType || i < parameterCount - 1) {
69554                     types.push(getTypeAtPosition(source, i));
69555                     flags.push(i < minArgumentCount ? 1 /* Required */ : 2 /* Optional */);
69556                 }
69557                 else {
69558                     types.push(restType);
69559                     flags.push(8 /* Variadic */);
69560                 }
69561                 var name = getNameableDeclarationAtPosition(source, i);
69562                 if (name) {
69563                     names.push(name);
69564                 }
69565             }
69566             return createTupleType(types, flags, /*readonly*/ false, ts.length(names) === ts.length(types) ? names : undefined);
69567         }
69568         function getParameterCount(signature) {
69569             var length = signature.parameters.length;
69570             if (signatureHasRestParameter(signature)) {
69571                 var restType = getTypeOfSymbol(signature.parameters[length - 1]);
69572                 if (isTupleType(restType)) {
69573                     return length + restType.target.fixedLength - (restType.target.hasRestElement ? 0 : 1);
69574                 }
69575             }
69576             return length;
69577         }
69578         function getMinArgumentCount(signature, flags) {
69579             var strongArityForUntypedJS = flags & 1 /* StrongArityForUntypedJS */;
69580             var voidIsNonOptional = flags & 2 /* VoidIsNonOptional */;
69581             if (voidIsNonOptional || signature.resolvedMinArgumentCount === undefined) {
69582                 var minArgumentCount = void 0;
69583                 if (signatureHasRestParameter(signature)) {
69584                     var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
69585                     if (isTupleType(restType)) {
69586                         var firstOptionalIndex = ts.findIndex(restType.target.elementFlags, function (f) { return !(f & 1 /* Required */); });
69587                         var requiredCount = firstOptionalIndex < 0 ? restType.target.fixedLength : firstOptionalIndex;
69588                         if (requiredCount > 0) {
69589                             minArgumentCount = signature.parameters.length - 1 + requiredCount;
69590                         }
69591                     }
69592                 }
69593                 if (minArgumentCount === undefined) {
69594                     if (!strongArityForUntypedJS && signature.flags & 16 /* IsUntypedSignatureInJSFile */) {
69595                         return 0;
69596                     }
69597                     minArgumentCount = signature.minArgumentCount;
69598                 }
69599                 if (voidIsNonOptional) {
69600                     return minArgumentCount;
69601                 }
69602                 for (var i = minArgumentCount - 1; i >= 0; i--) {
69603                     var type = getTypeAtPosition(signature, i);
69604                     if (filterType(type, acceptsVoid).flags & 131072 /* Never */) {
69605                         break;
69606                     }
69607                     minArgumentCount = i;
69608                 }
69609                 signature.resolvedMinArgumentCount = minArgumentCount;
69610             }
69611             return signature.resolvedMinArgumentCount;
69612         }
69613         function hasEffectiveRestParameter(signature) {
69614             if (signatureHasRestParameter(signature)) {
69615                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
69616                 return !isTupleType(restType) || restType.target.hasRestElement;
69617             }
69618             return false;
69619         }
69620         function getEffectiveRestType(signature) {
69621             if (signatureHasRestParameter(signature)) {
69622                 var restType = getTypeOfSymbol(signature.parameters[signature.parameters.length - 1]);
69623                 if (!isTupleType(restType)) {
69624                     return restType;
69625                 }
69626                 if (restType.target.hasRestElement) {
69627                     return sliceTupleType(restType, restType.target.fixedLength);
69628                 }
69629             }
69630             return undefined;
69631         }
69632         function getNonArrayRestType(signature) {
69633             var restType = getEffectiveRestType(signature);
69634             return restType && !isArrayType(restType) && !isTypeAny(restType) && (getReducedType(restType).flags & 131072 /* Never */) === 0 ? restType : undefined;
69635         }
69636         function getTypeOfFirstParameterOfSignature(signature) {
69637             return getTypeOfFirstParameterOfSignatureWithFallback(signature, neverType);
69638         }
69639         function getTypeOfFirstParameterOfSignatureWithFallback(signature, fallbackType) {
69640             return signature.parameters.length > 0 ? getTypeAtPosition(signature, 0) : fallbackType;
69641         }
69642         function inferFromAnnotatedParameters(signature, context, inferenceContext) {
69643             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69644             for (var i = 0; i < len; i++) {
69645                 var declaration = signature.parameters[i].valueDeclaration;
69646                 if (declaration.type) {
69647                     var typeNode = ts.getEffectiveTypeAnnotationNode(declaration);
69648                     if (typeNode) {
69649                         inferTypes(inferenceContext.inferences, getTypeFromTypeNode(typeNode), getTypeAtPosition(context, i));
69650                     }
69651                 }
69652             }
69653             var restType = getEffectiveRestType(context);
69654             if (restType && restType.flags & 262144 /* TypeParameter */) {
69655                 // The contextual signature has a generic rest parameter. We first instantiate the contextual
69656                 // signature (without fixing type parameters) and assign types to contextually typed parameters.
69657                 var instantiatedContext = instantiateSignature(context, inferenceContext.nonFixingMapper);
69658                 assignContextualParameterTypes(signature, instantiatedContext);
69659                 // We then infer from a tuple type representing the parameters that correspond to the contextual
69660                 // rest parameter.
69661                 var restPos = getParameterCount(context) - 1;
69662                 inferTypes(inferenceContext.inferences, getRestTypeAtPosition(signature, restPos), restType);
69663             }
69664         }
69665         function assignContextualParameterTypes(signature, context) {
69666             signature.typeParameters = context.typeParameters;
69667             if (context.thisParameter) {
69668                 var parameter = signature.thisParameter;
69669                 if (!parameter || parameter.valueDeclaration && !parameter.valueDeclaration.type) {
69670                     if (!parameter) {
69671                         signature.thisParameter = createSymbolWithType(context.thisParameter, /*type*/ undefined);
69672                     }
69673                     assignParameterType(signature.thisParameter, getTypeOfSymbol(context.thisParameter));
69674                 }
69675             }
69676             var len = signature.parameters.length - (signatureHasRestParameter(signature) ? 1 : 0);
69677             for (var i = 0; i < len; i++) {
69678                 var parameter = signature.parameters[i];
69679                 if (!ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
69680                     var contextualParameterType = tryGetTypeAtPosition(context, i);
69681                     assignParameterType(parameter, contextualParameterType);
69682                 }
69683             }
69684             if (signatureHasRestParameter(signature)) {
69685                 // parameter might be a transient symbol generated by use of `arguments` in the function body.
69686                 var parameter = ts.last(signature.parameters);
69687                 if (ts.isTransientSymbol(parameter) || !ts.getEffectiveTypeAnnotationNode(parameter.valueDeclaration)) {
69688                     var contextualParameterType = getRestTypeAtPosition(context, len);
69689                     assignParameterType(parameter, contextualParameterType);
69690                 }
69691             }
69692         }
69693         function assignNonContextualParameterTypes(signature) {
69694             if (signature.thisParameter) {
69695                 assignParameterType(signature.thisParameter);
69696             }
69697             for (var _i = 0, _a = signature.parameters; _i < _a.length; _i++) {
69698                 var parameter = _a[_i];
69699                 assignParameterType(parameter);
69700             }
69701         }
69702         function assignParameterType(parameter, type) {
69703             var links = getSymbolLinks(parameter);
69704             if (!links.type) {
69705                 var declaration = parameter.valueDeclaration;
69706                 links.type = type || getWidenedTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ true);
69707                 if (declaration.name.kind !== 78 /* Identifier */) {
69708                     // if inference didn't come up with anything but unknown, fall back to the binding pattern if present.
69709                     if (links.type === unknownType) {
69710                         links.type = getTypeFromBindingPattern(declaration.name);
69711                     }
69712                     assignBindingElementTypes(declaration.name);
69713                 }
69714             }
69715         }
69716         // When contextual typing assigns a type to a parameter that contains a binding pattern, we also need to push
69717         // the destructured type into the contained binding elements.
69718         function assignBindingElementTypes(pattern) {
69719             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
69720                 var element = _a[_i];
69721                 if (!ts.isOmittedExpression(element)) {
69722                     if (element.name.kind === 78 /* Identifier */) {
69723                         getSymbolLinks(getSymbolOfNode(element)).type = getTypeForBindingElement(element);
69724                     }
69725                     else {
69726                         assignBindingElementTypes(element.name);
69727                     }
69728                 }
69729             }
69730         }
69731         function createPromiseType(promisedType) {
69732             // creates a `Promise<T>` type where `T` is the promisedType argument
69733             var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
69734             if (globalPromiseType !== emptyGenericType) {
69735                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
69736                 promisedType = getAwaitedType(promisedType) || unknownType;
69737                 return createTypeReference(globalPromiseType, [promisedType]);
69738             }
69739             return unknownType;
69740         }
69741         function createPromiseLikeType(promisedType) {
69742             // creates a `PromiseLike<T>` type where `T` is the promisedType argument
69743             var globalPromiseLikeType = getGlobalPromiseLikeType(/*reportErrors*/ true);
69744             if (globalPromiseLikeType !== emptyGenericType) {
69745                 // if the promised type is itself a promise, get the underlying type; otherwise, fallback to the promised type
69746                 promisedType = getAwaitedType(promisedType) || unknownType;
69747                 return createTypeReference(globalPromiseLikeType, [promisedType]);
69748             }
69749             return unknownType;
69750         }
69751         function createPromiseReturnType(func, promisedType) {
69752             var promiseType = createPromiseType(promisedType);
69753             if (promiseType === unknownType) {
69754                 error(func, ts.isImportCall(func) ?
69755                     ts.Diagnostics.A_dynamic_import_call_returns_a_Promise_Make_sure_you_have_a_declaration_for_Promise_or_include_ES2015_in_your_lib_option :
69756                     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);
69757                 return errorType;
69758             }
69759             else if (!getGlobalPromiseConstructorSymbol(/*reportErrors*/ true)) {
69760                 error(func, ts.isImportCall(func) ?
69761                     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 :
69762                     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);
69763             }
69764             return promiseType;
69765         }
69766         function getReturnTypeFromBody(func, checkMode) {
69767             if (!func.body) {
69768                 return errorType;
69769             }
69770             var functionFlags = ts.getFunctionFlags(func);
69771             var isAsync = (functionFlags & 2 /* Async */) !== 0;
69772             var isGenerator = (functionFlags & 1 /* Generator */) !== 0;
69773             var returnType;
69774             var yieldType;
69775             var nextType;
69776             var fallbackReturnType = voidType;
69777             if (func.body.kind !== 230 /* Block */) { // Async or normal arrow function
69778                 returnType = checkExpressionCached(func.body, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
69779                 if (isAsync) {
69780                     // From within an async function you can return either a non-promise value or a promise. Any
69781                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
69782                     // return type of the body should be unwrapped to its awaited type, which we will wrap in
69783                     // the native Promise<T> type later in this function.
69784                     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);
69785                 }
69786             }
69787             else if (isGenerator) { // Generator or AsyncGenerator function
69788                 var returnTypes = checkAndAggregateReturnExpressionTypes(func, checkMode);
69789                 if (!returnTypes) {
69790                     fallbackReturnType = neverType;
69791                 }
69792                 else if (returnTypes.length > 0) {
69793                     returnType = getUnionType(returnTypes, 2 /* Subtype */);
69794                 }
69795                 var _a = checkAndAggregateYieldOperandTypes(func, checkMode), yieldTypes = _a.yieldTypes, nextTypes = _a.nextTypes;
69796                 yieldType = ts.some(yieldTypes) ? getUnionType(yieldTypes, 2 /* Subtype */) : undefined;
69797                 nextType = ts.some(nextTypes) ? getIntersectionType(nextTypes) : undefined;
69798             }
69799             else { // Async or normal function
69800                 var types = checkAndAggregateReturnExpressionTypes(func, checkMode);
69801                 if (!types) {
69802                     // For an async function, the return type will not be never, but rather a Promise for never.
69803                     return functionFlags & 2 /* Async */
69804                         ? createPromiseReturnType(func, neverType) // Async function
69805                         : neverType; // Normal function
69806                 }
69807                 if (types.length === 0) {
69808                     // For an async function, the return type will not be void, but rather a Promise for void.
69809                     return functionFlags & 2 /* Async */
69810                         ? createPromiseReturnType(func, voidType) // Async function
69811                         : voidType; // Normal function
69812                 }
69813                 // Return a union of the return expression types.
69814                 returnType = getUnionType(types, 2 /* Subtype */);
69815             }
69816             if (returnType || yieldType || nextType) {
69817                 if (yieldType)
69818                     reportErrorsFromWidening(func, yieldType, 3 /* GeneratorYield */);
69819                 if (returnType)
69820                     reportErrorsFromWidening(func, returnType, 1 /* FunctionReturn */);
69821                 if (nextType)
69822                     reportErrorsFromWidening(func, nextType, 2 /* GeneratorNext */);
69823                 if (returnType && isUnitType(returnType) ||
69824                     yieldType && isUnitType(yieldType) ||
69825                     nextType && isUnitType(nextType)) {
69826                     var contextualSignature = getContextualSignatureForFunctionLikeDeclaration(func);
69827                     var contextualType = !contextualSignature ? undefined :
69828                         contextualSignature === getSignatureFromDeclaration(func) ? isGenerator ? undefined : returnType :
69829                             instantiateContextualType(getReturnTypeOfSignature(contextualSignature), func);
69830                     if (isGenerator) {
69831                         yieldType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(yieldType, contextualType, 0 /* Yield */, isAsync);
69832                         returnType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(returnType, contextualType, 1 /* Return */, isAsync);
69833                         nextType = getWidenedLiteralLikeTypeForContextualIterationTypeIfNeeded(nextType, contextualType, 2 /* Next */, isAsync);
69834                     }
69835                     else {
69836                         returnType = getWidenedLiteralLikeTypeForContextualReturnTypeIfNeeded(returnType, contextualType, isAsync);
69837                     }
69838                 }
69839                 if (yieldType)
69840                     yieldType = getWidenedType(yieldType);
69841                 if (returnType)
69842                     returnType = getWidenedType(returnType);
69843                 if (nextType)
69844                     nextType = getWidenedType(nextType);
69845             }
69846             if (isGenerator) {
69847                 return createGeneratorReturnType(yieldType || neverType, returnType || fallbackReturnType, nextType || getContextualIterationType(2 /* Next */, func) || unknownType, isAsync);
69848             }
69849             else {
69850                 // From within an async function you can return either a non-promise value or a promise. Any
69851                 // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
69852                 // return type of the body is awaited type of the body, wrapped in a native Promise<T> type.
69853                 return isAsync
69854                     ? createPromiseType(returnType || fallbackReturnType)
69855                     : returnType || fallbackReturnType;
69856             }
69857         }
69858         function createGeneratorReturnType(yieldType, returnType, nextType, isAsyncGenerator) {
69859             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
69860             var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
69861             yieldType = resolver.resolveIterationType(yieldType, /*errorNode*/ undefined) || unknownType;
69862             returnType = resolver.resolveIterationType(returnType, /*errorNode*/ undefined) || unknownType;
69863             nextType = resolver.resolveIterationType(nextType, /*errorNode*/ undefined) || unknownType;
69864             if (globalGeneratorType === emptyGenericType) {
69865                 // Fall back to the global IterableIterator if returnType is assignable to the expected return iteration
69866                 // type of IterableIterator, and the expected next iteration type of IterableIterator is assignable to
69867                 // nextType.
69868                 var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
69869                 var iterationTypes = globalType !== emptyGenericType ? getIterationTypesOfGlobalIterableType(globalType, resolver) : undefined;
69870                 var iterableIteratorReturnType = iterationTypes ? iterationTypes.returnType : anyType;
69871                 var iterableIteratorNextType = iterationTypes ? iterationTypes.nextType : undefinedType;
69872                 if (isTypeAssignableTo(returnType, iterableIteratorReturnType) &&
69873                     isTypeAssignableTo(iterableIteratorNextType, nextType)) {
69874                     if (globalType !== emptyGenericType) {
69875                         return createTypeFromGenericGlobalType(globalType, [yieldType]);
69876                     }
69877                     // The global IterableIterator type doesn't exist, so report an error
69878                     resolver.getGlobalIterableIteratorType(/*reportErrors*/ true);
69879                     return emptyObjectType;
69880                 }
69881                 // The global Generator type doesn't exist, so report an error
69882                 resolver.getGlobalGeneratorType(/*reportErrors*/ true);
69883                 return emptyObjectType;
69884             }
69885             return createTypeFromGenericGlobalType(globalGeneratorType, [yieldType, returnType, nextType]);
69886         }
69887         function checkAndAggregateYieldOperandTypes(func, checkMode) {
69888             var yieldTypes = [];
69889             var nextTypes = [];
69890             var isAsync = (ts.getFunctionFlags(func) & 2 /* Async */) !== 0;
69891             ts.forEachYieldExpression(func.body, function (yieldExpression) {
69892                 var yieldExpressionType = yieldExpression.expression ? checkExpression(yieldExpression.expression, checkMode) : undefinedWideningType;
69893                 ts.pushIfUnique(yieldTypes, getYieldedTypeOfYieldExpression(yieldExpression, yieldExpressionType, anyType, isAsync));
69894                 var nextType;
69895                 if (yieldExpression.asteriskToken) {
69896                     var iterationTypes = getIterationTypesOfIterable(yieldExpressionType, isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, yieldExpression.expression);
69897                     nextType = iterationTypes && iterationTypes.nextType;
69898                 }
69899                 else {
69900                     nextType = getContextualType(yieldExpression);
69901                 }
69902                 if (nextType)
69903                     ts.pushIfUnique(nextTypes, nextType);
69904             });
69905             return { yieldTypes: yieldTypes, nextTypes: nextTypes };
69906         }
69907         function getYieldedTypeOfYieldExpression(node, expressionType, sentType, isAsync) {
69908             var errorNode = node.expression || node;
69909             // A `yield*` expression effectively yields everything that its operand yields
69910             var yieldedType = node.asteriskToken ? checkIteratedTypeOrElementType(isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */, expressionType, sentType, errorNode) : expressionType;
69911             return !isAsync ? yieldedType : getAwaitedType(yieldedType, errorNode, node.asteriskToken
69912                 ? 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
69913                 : ts.Diagnostics.Type_of_yield_operand_in_an_async_generator_must_either_be_a_valid_promise_or_must_not_contain_a_callable_then_member);
69914         }
69915         /**
69916          * Collect the TypeFacts learned from a typeof switch with
69917          * total clauses `witnesses`, and the active clause ranging
69918          * from `start` to `end`. Parameter `hasDefault` denotes
69919          * whether the active clause contains a default clause.
69920          */
69921         function getFactsFromTypeofSwitch(start, end, witnesses, hasDefault) {
69922             var facts = 0 /* None */;
69923             // When in the default we only collect inequality facts
69924             // because default is 'in theory' a set of infinite
69925             // equalities.
69926             if (hasDefault) {
69927                 // Value is not equal to any types after the active clause.
69928                 for (var i = end; i < witnesses.length; i++) {
69929                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
69930                 }
69931                 // Remove inequalities for types that appear in the
69932                 // active clause because they appear before other
69933                 // types collected so far.
69934                 for (var i = start; i < end; i++) {
69935                     facts &= ~(typeofNEFacts.get(witnesses[i]) || 0);
69936                 }
69937                 // Add inequalities for types before the active clause unconditionally.
69938                 for (var i = 0; i < start; i++) {
69939                     facts |= typeofNEFacts.get(witnesses[i]) || 32768 /* TypeofNEHostObject */;
69940                 }
69941             }
69942             // When in an active clause without default the set of
69943             // equalities is finite.
69944             else {
69945                 // Add equalities for all types in the active clause.
69946                 for (var i = start; i < end; i++) {
69947                     facts |= typeofEQFacts.get(witnesses[i]) || 128 /* TypeofEQHostObject */;
69948                 }
69949                 // Remove equalities for types that appear before the
69950                 // active clause.
69951                 for (var i = 0; i < start; i++) {
69952                     facts &= ~(typeofEQFacts.get(witnesses[i]) || 0);
69953                 }
69954             }
69955             return facts;
69956         }
69957         function isExhaustiveSwitchStatement(node) {
69958             var links = getNodeLinks(node);
69959             return links.isExhaustive !== undefined ? links.isExhaustive : (links.isExhaustive = computeExhaustiveSwitchStatement(node));
69960         }
69961         function computeExhaustiveSwitchStatement(node) {
69962             if (node.expression.kind === 211 /* TypeOfExpression */) {
69963                 var operandType = getTypeOfExpression(node.expression.expression);
69964                 var witnesses = getSwitchClauseTypeOfWitnesses(node, /*retainDefault*/ false);
69965                 // notEqualFacts states that the type of the switched value is not equal to every type in the switch.
69966                 var notEqualFacts_1 = getFactsFromTypeofSwitch(0, 0, witnesses, /*hasDefault*/ true);
69967                 var type_4 = getBaseConstraintOfType(operandType) || operandType;
69968                 // Take any/unknown as a special condition. Or maybe we could change `type` to a union containing all primitive types.
69969                 if (type_4.flags & 3 /* AnyOrUnknown */) {
69970                     return (556800 /* AllTypeofNE */ & notEqualFacts_1) === 556800 /* AllTypeofNE */;
69971                 }
69972                 return !!(filterType(type_4, function (t) { return (getTypeFacts(t) & notEqualFacts_1) === notEqualFacts_1; }).flags & 131072 /* Never */);
69973             }
69974             var type = getTypeOfExpression(node.expression);
69975             if (!isLiteralType(type)) {
69976                 return false;
69977             }
69978             var switchTypes = getSwitchClauseTypes(node);
69979             if (!switchTypes.length || ts.some(switchTypes, isNeitherUnitTypeNorNever)) {
69980                 return false;
69981             }
69982             return eachTypeContainedIn(mapType(type, getRegularTypeOfLiteralType), switchTypes);
69983         }
69984         function functionHasImplicitReturn(func) {
69985             return func.endFlowNode && isReachableFlowNode(func.endFlowNode);
69986         }
69987         /** NOTE: Return value of `[]` means a different thing than `undefined`. `[]` means func returns `void`, `undefined` means it returns `never`. */
69988         function checkAndAggregateReturnExpressionTypes(func, checkMode) {
69989             var functionFlags = ts.getFunctionFlags(func);
69990             var aggregatedTypes = [];
69991             var hasReturnWithNoExpression = functionHasImplicitReturn(func);
69992             var hasReturnOfTypeNever = false;
69993             ts.forEachReturnStatement(func.body, function (returnStatement) {
69994                 var expr = returnStatement.expression;
69995                 if (expr) {
69996                     var type = checkExpressionCached(expr, checkMode && checkMode & ~8 /* SkipGenericFunctions */);
69997                     if (functionFlags & 2 /* Async */) {
69998                         // From within an async function you can return either a non-promise value or a promise. Any
69999                         // Promise/A+ compatible implementation will always assimilate any foreign promise, so the
70000                         // return type of the body should be unwrapped to its awaited type, which should be wrapped in
70001                         // the native Promise<T> type by the caller.
70002                         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);
70003                     }
70004                     if (type.flags & 131072 /* Never */) {
70005                         hasReturnOfTypeNever = true;
70006                     }
70007                     ts.pushIfUnique(aggregatedTypes, type);
70008                 }
70009                 else {
70010                     hasReturnWithNoExpression = true;
70011                 }
70012             });
70013             if (aggregatedTypes.length === 0 && !hasReturnWithNoExpression && (hasReturnOfTypeNever || mayReturnNever(func))) {
70014                 return undefined;
70015             }
70016             if (strictNullChecks && aggregatedTypes.length && hasReturnWithNoExpression &&
70017                 !(isJSConstructor(func) && aggregatedTypes.some(function (t) { return t.symbol === func.symbol; }))) {
70018                 // Javascript "callable constructors", containing eg `if (!(this instanceof A)) return new A()` should not add undefined
70019                 ts.pushIfUnique(aggregatedTypes, undefinedType);
70020             }
70021             return aggregatedTypes;
70022         }
70023         function mayReturnNever(func) {
70024             switch (func.kind) {
70025                 case 208 /* FunctionExpression */:
70026                 case 209 /* ArrowFunction */:
70027                     return true;
70028                 case 165 /* MethodDeclaration */:
70029                     return func.parent.kind === 200 /* ObjectLiteralExpression */;
70030                 default:
70031                     return false;
70032             }
70033         }
70034         /**
70035          * TypeScript Specification 1.0 (6.3) - July 2014
70036          *   An explicitly typed function whose return type isn't the Void type,
70037          *   the Any type, or a union type containing the Void or Any type as a constituent
70038          *   must have at least one return statement somewhere in its body.
70039          *   An exception to this rule is if the function implementation consists of a single 'throw' statement.
70040          *
70041          * @param returnType - return type of the function, can be undefined if return type is not explicitly specified
70042          */
70043         function checkAllCodePathsInNonVoidFunctionReturnOrThrow(func, returnType) {
70044             if (!produceDiagnostics) {
70045                 return;
70046             }
70047             var functionFlags = ts.getFunctionFlags(func);
70048             var type = returnType && unwrapReturnType(returnType, functionFlags);
70049             // Functions with with an explicitly specified 'void' or 'any' return type don't need any return expressions.
70050             if (type && maybeTypeOfKind(type, 1 /* Any */ | 16384 /* Void */)) {
70051                 return;
70052             }
70053             // If all we have is a function signature, or an arrow function with an expression body, then there is nothing to check.
70054             // also if HasImplicitReturn flag is not set this means that all codepaths in function body end with return or throw
70055             if (func.kind === 164 /* MethodSignature */ || ts.nodeIsMissing(func.body) || func.body.kind !== 230 /* Block */ || !functionHasImplicitReturn(func)) {
70056                 return;
70057             }
70058             var hasExplicitReturn = func.flags & 512 /* HasExplicitReturn */;
70059             if (type && type.flags & 131072 /* Never */) {
70060                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_returning_never_cannot_have_a_reachable_end_point);
70061             }
70062             else if (type && !hasExplicitReturn) {
70063                 // minimal check: function has syntactic return type annotation and no explicit return statements in the body
70064                 // this function does not conform to the specification.
70065                 // NOTE: having returnType !== undefined is a precondition for entering this branch so func.type will always be present
70066                 error(ts.getEffectiveReturnTypeNode(func), ts.Diagnostics.A_function_whose_declared_type_is_neither_void_nor_any_must_return_a_value);
70067             }
70068             else if (type && strictNullChecks && !isTypeAssignableTo(undefinedType, type)) {
70069                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Function_lacks_ending_return_statement_and_return_type_does_not_include_undefined);
70070             }
70071             else if (compilerOptions.noImplicitReturns) {
70072                 if (!type) {
70073                     // If return type annotation is omitted check if function has any explicit return statements.
70074                     // If it does not have any - its inferred return type is void - don't do any checks.
70075                     // Otherwise get inferred return type from function body and report error only if it is not void / anytype
70076                     if (!hasExplicitReturn) {
70077                         return;
70078                     }
70079                     var inferredReturnType = getReturnTypeOfSignature(getSignatureFromDeclaration(func));
70080                     if (isUnwrappedReturnTypeVoidOrAny(func, inferredReturnType)) {
70081                         return;
70082                     }
70083                 }
70084                 error(ts.getEffectiveReturnTypeNode(func) || func, ts.Diagnostics.Not_all_code_paths_return_a_value);
70085             }
70086         }
70087         function checkFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
70088             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
70089             checkNodeDeferred(node);
70090             // The identityMapper object is used to indicate that function expressions are wildcards
70091             if (checkMode && checkMode & 4 /* SkipContextSensitive */ && isContextSensitive(node)) {
70092                 // Skip parameters, return signature with return type that retains noncontextual parts so inferences can still be drawn in an early stage
70093                 if (!ts.getEffectiveReturnTypeNode(node) && !hasContextSensitiveParameters(node)) {
70094                     // Return plain anyFunctionType if there is no possibility we'll make inferences from the return type
70095                     var contextualSignature = getContextualSignature(node);
70096                     if (contextualSignature && couldContainTypeVariables(getReturnTypeOfSignature(contextualSignature))) {
70097                         var links = getNodeLinks(node);
70098                         if (links.contextFreeType) {
70099                             return links.contextFreeType;
70100                         }
70101                         var returnType = getReturnTypeFromBody(node, checkMode);
70102                         var returnOnlySignature = createSignature(undefined, undefined, undefined, ts.emptyArray, returnType, /*resolvedTypePredicate*/ undefined, 0, 0 /* None */);
70103                         var returnOnlyType = createAnonymousType(node.symbol, emptySymbols, [returnOnlySignature], ts.emptyArray, undefined, undefined);
70104                         returnOnlyType.objectFlags |= 2097152 /* NonInferrableType */;
70105                         return links.contextFreeType = returnOnlyType;
70106                     }
70107                 }
70108                 return anyFunctionType;
70109             }
70110             // Grammar checking
70111             var hasGrammarError = checkGrammarFunctionLikeDeclaration(node);
70112             if (!hasGrammarError && node.kind === 208 /* FunctionExpression */) {
70113                 checkGrammarForGenerator(node);
70114             }
70115             contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode);
70116             return getTypeOfSymbol(getSymbolOfNode(node));
70117         }
70118         function contextuallyCheckFunctionExpressionOrObjectLiteralMethod(node, checkMode) {
70119             var links = getNodeLinks(node);
70120             // Check if function expression is contextually typed and assign parameter types if so.
70121             if (!(links.flags & 1024 /* ContextChecked */)) {
70122                 var contextualSignature = getContextualSignature(node);
70123                 // If a type check is started at a function expression that is an argument of a function call, obtaining the
70124                 // contextual type may recursively get back to here during overload resolution of the call. If so, we will have
70125                 // already assigned contextual types.
70126                 if (!(links.flags & 1024 /* ContextChecked */)) {
70127                     links.flags |= 1024 /* ContextChecked */;
70128                     var signature = ts.firstOrUndefined(getSignaturesOfType(getTypeOfSymbol(getSymbolOfNode(node)), 0 /* Call */));
70129                     if (!signature) {
70130                         return;
70131                     }
70132                     if (isContextSensitive(node)) {
70133                         if (contextualSignature) {
70134                             var inferenceContext = getInferenceContext(node);
70135                             if (checkMode && checkMode & 2 /* Inferential */) {
70136                                 inferFromAnnotatedParameters(signature, contextualSignature, inferenceContext);
70137                             }
70138                             var instantiatedContextualSignature = inferenceContext ?
70139                                 instantiateSignature(contextualSignature, inferenceContext.mapper) : contextualSignature;
70140                             assignContextualParameterTypes(signature, instantiatedContextualSignature);
70141                         }
70142                         else {
70143                             // Force resolution of all parameter types such that the absence of a contextual type is consistently reflected.
70144                             assignNonContextualParameterTypes(signature);
70145                         }
70146                     }
70147                     if (contextualSignature && !getReturnTypeFromAnnotation(node) && !signature.resolvedReturnType) {
70148                         var returnType = getReturnTypeFromBody(node, checkMode);
70149                         if (!signature.resolvedReturnType) {
70150                             signature.resolvedReturnType = returnType;
70151                         }
70152                     }
70153                     checkSignatureDeclaration(node);
70154                 }
70155             }
70156         }
70157         function checkFunctionExpressionOrObjectLiteralMethodDeferred(node) {
70158             ts.Debug.assert(node.kind !== 165 /* MethodDeclaration */ || ts.isObjectLiteralMethod(node));
70159             var functionFlags = ts.getFunctionFlags(node);
70160             var returnType = getReturnTypeFromAnnotation(node);
70161             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
70162             if (node.body) {
70163                 if (!ts.getEffectiveReturnTypeNode(node)) {
70164                     // There are some checks that are only performed in getReturnTypeFromBody, that may produce errors
70165                     // we need. An example is the noImplicitAny errors resulting from widening the return expression
70166                     // of a function. Because checking of function expression bodies is deferred, there was never an
70167                     // appropriate time to do this during the main walk of the file (see the comment at the top of
70168                     // checkFunctionExpressionBodies). So it must be done now.
70169                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
70170                 }
70171                 if (node.body.kind === 230 /* Block */) {
70172                     checkSourceElement(node.body);
70173                 }
70174                 else {
70175                     // From within an async function you can return either a non-promise value or a promise. Any
70176                     // Promise/A+ compatible implementation will always assimilate any foreign promise, so we
70177                     // should not be checking assignability of a promise to the return type. Instead, we need to
70178                     // check assignability of the awaited type of the expression body against the promised type of
70179                     // its return type annotation.
70180                     var exprType = checkExpression(node.body);
70181                     var returnOrPromisedType = returnType && unwrapReturnType(returnType, functionFlags);
70182                     if (returnOrPromisedType) {
70183                         if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */) { // Async function
70184                             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);
70185                             checkTypeAssignableToAndOptionallyElaborate(awaitedType, returnOrPromisedType, node.body, node.body);
70186                         }
70187                         else { // Normal function
70188                             checkTypeAssignableToAndOptionallyElaborate(exprType, returnOrPromisedType, node.body, node.body);
70189                         }
70190                     }
70191                 }
70192             }
70193         }
70194         function checkArithmeticOperandType(operand, type, diagnostic, isAwaitValid) {
70195             if (isAwaitValid === void 0) { isAwaitValid = false; }
70196             if (!isTypeAssignableTo(type, numberOrBigIntType)) {
70197                 var awaitedType = isAwaitValid && getAwaitedTypeOfPromise(type);
70198                 errorAndMaybeSuggestAwait(operand, !!awaitedType && isTypeAssignableTo(awaitedType, numberOrBigIntType), diagnostic);
70199                 return false;
70200             }
70201             return true;
70202         }
70203         function isReadonlyAssignmentDeclaration(d) {
70204             if (!ts.isCallExpression(d)) {
70205                 return false;
70206             }
70207             if (!ts.isBindableObjectDefinePropertyCall(d)) {
70208                 return false;
70209             }
70210             var objectLitType = checkExpressionCached(d.arguments[2]);
70211             var valueType = getTypeOfPropertyOfType(objectLitType, "value");
70212             if (valueType) {
70213                 var writableProp = getPropertyOfType(objectLitType, "writable");
70214                 var writableType = writableProp && getTypeOfSymbol(writableProp);
70215                 if (!writableType || writableType === falseType || writableType === regularFalseType) {
70216                     return true;
70217                 }
70218                 // We include this definition whereupon we walk back and check the type at the declaration because
70219                 // The usual definition of `Object.defineProperty` will _not_ cause literal types to be preserved in the
70220                 // argument types, should the type be contextualized by the call itself.
70221                 if (writableProp && writableProp.valueDeclaration && ts.isPropertyAssignment(writableProp.valueDeclaration)) {
70222                     var initializer = writableProp.valueDeclaration.initializer;
70223                     var rawOriginalType = checkExpression(initializer);
70224                     if (rawOriginalType === falseType || rawOriginalType === regularFalseType) {
70225                         return true;
70226                     }
70227                 }
70228                 return false;
70229             }
70230             var setProp = getPropertyOfType(objectLitType, "set");
70231             return !setProp;
70232         }
70233         function isReadonlySymbol(symbol) {
70234             // The following symbols are considered read-only:
70235             // Properties with a 'readonly' modifier
70236             // Variables declared with 'const'
70237             // Get accessors without matching set accessors
70238             // Enum members
70239             // Object.defineProperty assignments with writable false or no setter
70240             // Unions and intersections of the above (unions and intersections eagerly set isReadonly on creation)
70241             return !!(ts.getCheckFlags(symbol) & 8 /* Readonly */ ||
70242                 symbol.flags & 4 /* Property */ && ts.getDeclarationModifierFlagsFromSymbol(symbol) & 64 /* Readonly */ ||
70243                 symbol.flags & 3 /* Variable */ && getDeclarationNodeFlagsFromSymbol(symbol) & 2 /* Const */ ||
70244                 symbol.flags & 98304 /* Accessor */ && !(symbol.flags & 65536 /* SetAccessor */) ||
70245                 symbol.flags & 8 /* EnumMember */ ||
70246                 ts.some(symbol.declarations, isReadonlyAssignmentDeclaration));
70247         }
70248         function isAssignmentToReadonlyEntity(expr, symbol, assignmentKind) {
70249             var _a, _b;
70250             if (assignmentKind === 0 /* None */) {
70251                 // no assigment means it doesn't matter whether the entity is readonly
70252                 return false;
70253             }
70254             if (isReadonlySymbol(symbol)) {
70255                 // Allow assignments to readonly properties within constructors of the same class declaration.
70256                 if (symbol.flags & 4 /* Property */ &&
70257                     ts.isAccessExpression(expr) &&
70258                     expr.expression.kind === 107 /* ThisKeyword */) {
70259                     // Look for if this is the constructor for the class that `symbol` is a property of.
70260                     var ctor = ts.getContainingFunction(expr);
70261                     if (!(ctor && (ctor.kind === 166 /* Constructor */ || isJSConstructor(ctor)))) {
70262                         return true;
70263                     }
70264                     if (symbol.valueDeclaration) {
70265                         var isAssignmentDeclaration_1 = ts.isBinaryExpression(symbol.valueDeclaration);
70266                         var isLocalPropertyDeclaration = ctor.parent === symbol.valueDeclaration.parent;
70267                         var isLocalParameterProperty = ctor === symbol.valueDeclaration.parent;
70268                         var isLocalThisPropertyAssignment = isAssignmentDeclaration_1 && ((_a = symbol.parent) === null || _a === void 0 ? void 0 : _a.valueDeclaration) === ctor.parent;
70269                         var isLocalThisPropertyAssignmentConstructorFunction = isAssignmentDeclaration_1 && ((_b = symbol.parent) === null || _b === void 0 ? void 0 : _b.valueDeclaration) === ctor;
70270                         var isWriteableSymbol = isLocalPropertyDeclaration
70271                             || isLocalParameterProperty
70272                             || isLocalThisPropertyAssignment
70273                             || isLocalThisPropertyAssignmentConstructorFunction;
70274                         return !isWriteableSymbol;
70275                     }
70276                 }
70277                 return true;
70278             }
70279             if (ts.isAccessExpression(expr)) {
70280                 // references through namespace import should be readonly
70281                 var node = ts.skipParentheses(expr.expression);
70282                 if (node.kind === 78 /* Identifier */) {
70283                     var symbol_2 = getNodeLinks(node).resolvedSymbol;
70284                     if (symbol_2.flags & 2097152 /* Alias */) {
70285                         var declaration = getDeclarationOfAliasSymbol(symbol_2);
70286                         return !!declaration && declaration.kind === 263 /* NamespaceImport */;
70287                     }
70288                 }
70289             }
70290             return false;
70291         }
70292         function checkReferenceExpression(expr, invalidReferenceMessage, invalidOptionalChainMessage) {
70293             // References are combinations of identifiers, parentheses, and property accesses.
70294             var node = ts.skipOuterExpressions(expr, 6 /* Assertions */ | 1 /* Parentheses */);
70295             if (node.kind !== 78 /* Identifier */ && !ts.isAccessExpression(node)) {
70296                 error(expr, invalidReferenceMessage);
70297                 return false;
70298             }
70299             if (node.flags & 32 /* OptionalChain */) {
70300                 error(expr, invalidOptionalChainMessage);
70301                 return false;
70302             }
70303             return true;
70304         }
70305         function checkDeleteExpression(node) {
70306             checkExpression(node.expression);
70307             var expr = ts.skipParentheses(node.expression);
70308             if (!ts.isAccessExpression(expr)) {
70309                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_a_property_reference);
70310                 return booleanType;
70311             }
70312             if (ts.isPropertyAccessExpression(expr) && ts.isPrivateIdentifier(expr.name)) {
70313                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_private_identifier);
70314             }
70315             var links = getNodeLinks(expr);
70316             var symbol = getExportSymbolOfValueSymbolIfExported(links.resolvedSymbol);
70317             if (symbol) {
70318                 if (isReadonlySymbol(symbol)) {
70319                     error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_cannot_be_a_read_only_property);
70320                 }
70321                 checkDeleteExpressionMustBeOptional(expr, getTypeOfSymbol(symbol));
70322             }
70323             return booleanType;
70324         }
70325         function checkDeleteExpressionMustBeOptional(expr, type) {
70326             var AnyOrUnknownOrNeverFlags = 3 /* AnyOrUnknown */ | 131072 /* Never */;
70327             if (strictNullChecks && !(type.flags & AnyOrUnknownOrNeverFlags) && !(getFalsyFlags(type) & 32768 /* Undefined */)) {
70328                 error(expr, ts.Diagnostics.The_operand_of_a_delete_operator_must_be_optional);
70329             }
70330         }
70331         function checkTypeOfExpression(node) {
70332             checkExpression(node.expression);
70333             return typeofType;
70334         }
70335         function checkVoidExpression(node) {
70336             checkExpression(node.expression);
70337             return undefinedWideningType;
70338         }
70339         function checkAwaitExpression(node) {
70340             // Grammar checking
70341             if (produceDiagnostics) {
70342                 if (!(node.flags & 32768 /* AwaitContext */)) {
70343                     if (ts.isInTopLevelContext(node)) {
70344                         var sourceFile = ts.getSourceFileOfNode(node);
70345                         if (!hasParseDiagnostics(sourceFile)) {
70346                             var span = void 0;
70347                             if (!ts.isEffectiveExternalModule(sourceFile, compilerOptions)) {
70348                                 if (!span)
70349                                     span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
70350                                 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);
70351                                 diagnostics.add(diagnostic);
70352                             }
70353                             if ((moduleKind !== ts.ModuleKind.ESNext && moduleKind !== ts.ModuleKind.System) || languageVersion < 4 /* ES2017 */) {
70354                                 span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
70355                                 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);
70356                                 diagnostics.add(diagnostic);
70357                             }
70358                         }
70359                     }
70360                     else {
70361                         // use of 'await' in non-async function
70362                         var sourceFile = ts.getSourceFileOfNode(node);
70363                         if (!hasParseDiagnostics(sourceFile)) {
70364                             var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
70365                             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);
70366                             var func = ts.getContainingFunction(node);
70367                             if (func && func.kind !== 166 /* Constructor */ && (ts.getFunctionFlags(func) & 2 /* Async */) === 0) {
70368                                 var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
70369                                 ts.addRelatedInfo(diagnostic, relatedInfo);
70370                             }
70371                             diagnostics.add(diagnostic);
70372                         }
70373                     }
70374                 }
70375                 if (isInParameterInitializerBeforeContainingFunction(node)) {
70376                     error(node, ts.Diagnostics.await_expressions_cannot_be_used_in_a_parameter_initializer);
70377                 }
70378             }
70379             var operandType = checkExpression(node.expression);
70380             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);
70381             if (awaitedType === operandType && awaitedType !== errorType && !(operandType.flags & 3 /* AnyOrUnknown */)) {
70382                 addErrorOrSuggestion(/*isError*/ false, ts.createDiagnosticForNode(node, ts.Diagnostics.await_has_no_effect_on_the_type_of_this_expression));
70383             }
70384             return awaitedType;
70385         }
70386         function checkPrefixUnaryExpression(node) {
70387             var operandType = checkExpression(node.operand);
70388             if (operandType === silentNeverType) {
70389                 return silentNeverType;
70390             }
70391             switch (node.operand.kind) {
70392                 case 8 /* NumericLiteral */:
70393                     switch (node.operator) {
70394                         case 40 /* MinusToken */:
70395                             return getFreshTypeOfLiteralType(getLiteralType(-node.operand.text));
70396                         case 39 /* PlusToken */:
70397                             return getFreshTypeOfLiteralType(getLiteralType(+node.operand.text));
70398                     }
70399                     break;
70400                 case 9 /* BigIntLiteral */:
70401                     if (node.operator === 40 /* MinusToken */) {
70402                         return getFreshTypeOfLiteralType(getLiteralType({
70403                             negative: true,
70404                             base10Value: ts.parsePseudoBigInt(node.operand.text)
70405                         }));
70406                     }
70407             }
70408             switch (node.operator) {
70409                 case 39 /* PlusToken */:
70410                 case 40 /* MinusToken */:
70411                 case 54 /* TildeToken */:
70412                     checkNonNullType(operandType, node.operand);
70413                     if (maybeTypeOfKind(operandType, 12288 /* ESSymbolLike */)) {
70414                         error(node.operand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(node.operator));
70415                     }
70416                     if (node.operator === 39 /* PlusToken */) {
70417                         if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
70418                             error(node.operand, ts.Diagnostics.Operator_0_cannot_be_applied_to_type_1, ts.tokenToString(node.operator), typeToString(getBaseTypeOfLiteralType(operandType)));
70419                         }
70420                         return numberType;
70421                     }
70422                     return getUnaryResultType(operandType);
70423                 case 53 /* ExclamationToken */:
70424                     checkTruthinessExpression(node.operand);
70425                     var facts = getTypeFacts(operandType) & (4194304 /* Truthy */ | 8388608 /* Falsy */);
70426                     return facts === 4194304 /* Truthy */ ? falseType :
70427                         facts === 8388608 /* Falsy */ ? trueType :
70428                             booleanType;
70429                 case 45 /* PlusPlusToken */:
70430                 case 46 /* MinusMinusToken */:
70431                     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);
70432                     if (ok) {
70433                         // run check only if former checks succeeded to avoid reporting cascading errors
70434                         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);
70435                     }
70436                     return getUnaryResultType(operandType);
70437             }
70438             return errorType;
70439         }
70440         function checkPostfixUnaryExpression(node) {
70441             var operandType = checkExpression(node.operand);
70442             if (operandType === silentNeverType) {
70443                 return silentNeverType;
70444             }
70445             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);
70446             if (ok) {
70447                 // run check only if former checks succeeded to avoid reporting cascading errors
70448                 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);
70449             }
70450             return getUnaryResultType(operandType);
70451         }
70452         function getUnaryResultType(operandType) {
70453             if (maybeTypeOfKind(operandType, 2112 /* BigIntLike */)) {
70454                 return isTypeAssignableToKind(operandType, 3 /* AnyOrUnknown */) || maybeTypeOfKind(operandType, 296 /* NumberLike */)
70455                     ? numberOrBigIntType
70456                     : bigintType;
70457             }
70458             // If it's not a bigint type, implicit coercion will result in a number
70459             return numberType;
70460         }
70461         // Return true if type might be of the given kind. A union or intersection type might be of a given
70462         // kind if at least one constituent type is of the given kind.
70463         function maybeTypeOfKind(type, kind) {
70464             if (type.flags & kind) {
70465                 return true;
70466             }
70467             if (type.flags & 3145728 /* UnionOrIntersection */) {
70468                 var types = type.types;
70469                 for (var _i = 0, types_20 = types; _i < types_20.length; _i++) {
70470                     var t = types_20[_i];
70471                     if (maybeTypeOfKind(t, kind)) {
70472                         return true;
70473                     }
70474                 }
70475             }
70476             return false;
70477         }
70478         function isTypeAssignableToKind(source, kind, strict) {
70479             if (source.flags & kind) {
70480                 return true;
70481             }
70482             if (strict && source.flags & (3 /* AnyOrUnknown */ | 16384 /* Void */ | 32768 /* Undefined */ | 65536 /* Null */)) {
70483                 return false;
70484             }
70485             return !!(kind & 296 /* NumberLike */) && isTypeAssignableTo(source, numberType) ||
70486                 !!(kind & 2112 /* BigIntLike */) && isTypeAssignableTo(source, bigintType) ||
70487                 !!(kind & 402653316 /* StringLike */) && isTypeAssignableTo(source, stringType) ||
70488                 !!(kind & 528 /* BooleanLike */) && isTypeAssignableTo(source, booleanType) ||
70489                 !!(kind & 16384 /* Void */) && isTypeAssignableTo(source, voidType) ||
70490                 !!(kind & 131072 /* Never */) && isTypeAssignableTo(source, neverType) ||
70491                 !!(kind & 65536 /* Null */) && isTypeAssignableTo(source, nullType) ||
70492                 !!(kind & 32768 /* Undefined */) && isTypeAssignableTo(source, undefinedType) ||
70493                 !!(kind & 4096 /* ESSymbol */) && isTypeAssignableTo(source, esSymbolType) ||
70494                 !!(kind & 67108864 /* NonPrimitive */) && isTypeAssignableTo(source, nonPrimitiveType);
70495         }
70496         function allTypesAssignableToKind(source, kind, strict) {
70497             return source.flags & 1048576 /* Union */ ?
70498                 ts.every(source.types, function (subType) { return allTypesAssignableToKind(subType, kind, strict); }) :
70499                 isTypeAssignableToKind(source, kind, strict);
70500         }
70501         function isConstEnumObjectType(type) {
70502             return !!(ts.getObjectFlags(type) & 16 /* Anonymous */) && !!type.symbol && isConstEnumSymbol(type.symbol);
70503         }
70504         function isConstEnumSymbol(symbol) {
70505             return (symbol.flags & 128 /* ConstEnum */) !== 0;
70506         }
70507         function checkInstanceOfExpression(left, right, leftType, rightType) {
70508             if (leftType === silentNeverType || rightType === silentNeverType) {
70509                 return silentNeverType;
70510             }
70511             // TypeScript 1.0 spec (April 2014): 4.15.4
70512             // The instanceof operator requires the left operand to be of type Any, an object type, or a type parameter type,
70513             // and the right operand to be of type Any, a subtype of the 'Function' interface type, or have a call or construct signature.
70514             // The result is always of the Boolean primitive type.
70515             // NOTE: do not raise error if leftType is unknown as related error was already reported
70516             if (!isTypeAny(leftType) &&
70517                 allTypesAssignableToKind(leftType, 131068 /* Primitive */)) {
70518                 error(left, ts.Diagnostics.The_left_hand_side_of_an_instanceof_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
70519             }
70520             // NOTE: do not raise error if right is unknown as related error was already reported
70521             if (!(isTypeAny(rightType) || typeHasCallOrConstructSignatures(rightType) || isTypeSubtypeOf(rightType, globalFunctionType))) {
70522                 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);
70523             }
70524             return booleanType;
70525         }
70526         function checkInExpression(left, right, leftType, rightType) {
70527             if (leftType === silentNeverType || rightType === silentNeverType) {
70528                 return silentNeverType;
70529             }
70530             leftType = checkNonNullType(leftType, left);
70531             rightType = checkNonNullType(rightType, right);
70532             // TypeScript 1.0 spec (April 2014): 4.15.5
70533             // The in operator requires the left operand to be of type Any, the String primitive type, or the Number primitive type,
70534             // and the right operand to be of type Any, an object type, or a type parameter type.
70535             // The result is always of the Boolean primitive type.
70536             if (!(allTypesAssignableToKind(leftType, 402653316 /* StringLike */ | 296 /* NumberLike */ | 12288 /* ESSymbolLike */) ||
70537                 isTypeAssignableToKind(leftType, 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */ | 262144 /* TypeParameter */))) {
70538                 error(left, ts.Diagnostics.The_left_hand_side_of_an_in_expression_must_be_of_type_any_string_number_or_symbol);
70539             }
70540             if (!allTypesAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
70541                 error(right, ts.Diagnostics.The_right_hand_side_of_an_in_expression_must_be_of_type_any_an_object_type_or_a_type_parameter);
70542             }
70543             return booleanType;
70544         }
70545         function checkObjectLiteralAssignment(node, sourceType, rightIsThis) {
70546             var properties = node.properties;
70547             if (strictNullChecks && properties.length === 0) {
70548                 return checkNonNullType(sourceType, node);
70549             }
70550             for (var i = 0; i < properties.length; i++) {
70551                 checkObjectLiteralDestructuringPropertyAssignment(node, sourceType, i, properties, rightIsThis);
70552             }
70553             return sourceType;
70554         }
70555         /** Note: If property cannot be a SpreadAssignment, then allProperties does not need to be provided */
70556         function checkObjectLiteralDestructuringPropertyAssignment(node, objectLiteralType, propertyIndex, allProperties, rightIsThis) {
70557             if (rightIsThis === void 0) { rightIsThis = false; }
70558             var properties = node.properties;
70559             var property = properties[propertyIndex];
70560             if (property.kind === 288 /* PropertyAssignment */ || property.kind === 289 /* ShorthandPropertyAssignment */) {
70561                 var name = property.name;
70562                 var exprType = getLiteralTypeFromPropertyName(name);
70563                 if (isTypeUsableAsPropertyName(exprType)) {
70564                     var text = getPropertyNameFromType(exprType);
70565                     var prop = getPropertyOfType(objectLiteralType, text);
70566                     if (prop) {
70567                         markPropertyAsReferenced(prop, property, rightIsThis);
70568                         checkPropertyAccessibility(property, /*isSuper*/ false, objectLiteralType, prop);
70569                     }
70570                 }
70571                 var elementType = getIndexedAccessType(objectLiteralType, exprType, /*noUncheckedIndexedAccessCandidate*/ undefined, name, /*aliasSymbol*/ undefined, /*aliasTypeArguments*/ undefined, 16 /* ExpressionPosition */);
70572                 var type = getFlowTypeOfDestructuring(property, elementType);
70573                 return checkDestructuringAssignment(property.kind === 289 /* ShorthandPropertyAssignment */ ? property : property.initializer, type);
70574             }
70575             else if (property.kind === 290 /* SpreadAssignment */) {
70576                 if (propertyIndex < properties.length - 1) {
70577                     error(property, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
70578                 }
70579                 else {
70580                     if (languageVersion < 99 /* ESNext */) {
70581                         checkExternalEmitHelpers(property, 4 /* Rest */);
70582                     }
70583                     var nonRestNames = [];
70584                     if (allProperties) {
70585                         for (var _i = 0, allProperties_1 = allProperties; _i < allProperties_1.length; _i++) {
70586                             var otherProperty = allProperties_1[_i];
70587                             if (!ts.isSpreadAssignment(otherProperty)) {
70588                                 nonRestNames.push(otherProperty.name);
70589                             }
70590                         }
70591                     }
70592                     var type = getRestType(objectLiteralType, nonRestNames, objectLiteralType.symbol);
70593                     checkGrammarForDisallowedTrailingComma(allProperties, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
70594                     return checkDestructuringAssignment(property.expression, type);
70595                 }
70596             }
70597             else {
70598                 error(property, ts.Diagnostics.Property_assignment_expected);
70599             }
70600         }
70601         function checkArrayLiteralAssignment(node, sourceType, checkMode) {
70602             var elements = node.elements;
70603             if (languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
70604                 checkExternalEmitHelpers(node, 512 /* Read */);
70605             }
70606             // This elementType will be used if the specific property corresponding to this index is not
70607             // present (aka the tuple element property). This call also checks that the parentType is in
70608             // fact an iterable or array (depending on target language).
70609             var possiblyOutOfBoundsType = checkIteratedTypeOrElementType(65 /* Destructuring */ | 128 /* PossiblyOutOfBounds */, sourceType, undefinedType, node) || errorType;
70610             var inBoundsType = compilerOptions.noUncheckedIndexedAccess ? undefined : possiblyOutOfBoundsType;
70611             for (var i = 0; i < elements.length; i++) {
70612                 var type = possiblyOutOfBoundsType;
70613                 if (node.elements[i].kind === 220 /* SpreadElement */) {
70614                     type = inBoundsType = inBoundsType !== null && inBoundsType !== void 0 ? inBoundsType : (checkIteratedTypeOrElementType(65 /* Destructuring */, sourceType, undefinedType, node) || errorType);
70615                 }
70616                 checkArrayLiteralDestructuringElementAssignment(node, sourceType, i, type, checkMode);
70617             }
70618             return sourceType;
70619         }
70620         function checkArrayLiteralDestructuringElementAssignment(node, sourceType, elementIndex, elementType, checkMode) {
70621             var elements = node.elements;
70622             var element = elements[elementIndex];
70623             if (element.kind !== 222 /* OmittedExpression */) {
70624                 if (element.kind !== 220 /* SpreadElement */) {
70625                     var indexType = getLiteralType(elementIndex);
70626                     if (isArrayLikeType(sourceType)) {
70627                         // We create a synthetic expression so that getIndexedAccessType doesn't get confused
70628                         // when the element is a SyntaxKind.ElementAccessExpression.
70629                         var accessFlags = 16 /* ExpressionPosition */ | (hasDefaultValue(element) ? 8 /* NoTupleBoundsCheck */ : 0);
70630                         var elementType_2 = getIndexedAccessTypeOrUndefined(sourceType, indexType, /*noUncheckedIndexedAccessCandidate*/ undefined, createSyntheticExpression(element, indexType), accessFlags) || errorType;
70631                         var assignedType = hasDefaultValue(element) ? getTypeWithFacts(elementType_2, 524288 /* NEUndefined */) : elementType_2;
70632                         var type = getFlowTypeOfDestructuring(element, assignedType);
70633                         return checkDestructuringAssignment(element, type, checkMode);
70634                     }
70635                     return checkDestructuringAssignment(element, elementType, checkMode);
70636                 }
70637                 if (elementIndex < elements.length - 1) {
70638                     error(element, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
70639                 }
70640                 else {
70641                     var restExpression = element.expression;
70642                     if (restExpression.kind === 216 /* BinaryExpression */ && restExpression.operatorToken.kind === 62 /* EqualsToken */) {
70643                         error(restExpression.operatorToken, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
70644                     }
70645                     else {
70646                         checkGrammarForDisallowedTrailingComma(node.elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
70647                         var type = everyType(sourceType, isTupleType) ?
70648                             mapType(sourceType, function (t) { return sliceTupleType(t, elementIndex); }) :
70649                             createArrayType(elementType);
70650                         return checkDestructuringAssignment(restExpression, type, checkMode);
70651                     }
70652                 }
70653             }
70654             return undefined;
70655         }
70656         function checkDestructuringAssignment(exprOrAssignment, sourceType, checkMode, rightIsThis) {
70657             var target;
70658             if (exprOrAssignment.kind === 289 /* ShorthandPropertyAssignment */) {
70659                 var prop = exprOrAssignment;
70660                 if (prop.objectAssignmentInitializer) {
70661                     // In strict null checking mode, if a default value of a non-undefined type is specified, remove
70662                     // undefined from the final type.
70663                     if (strictNullChecks &&
70664                         !(getFalsyFlags(checkExpression(prop.objectAssignmentInitializer)) & 32768 /* Undefined */)) {
70665                         sourceType = getTypeWithFacts(sourceType, 524288 /* NEUndefined */);
70666                     }
70667                     checkBinaryLikeExpression(prop.name, prop.equalsToken, prop.objectAssignmentInitializer, checkMode);
70668                 }
70669                 target = exprOrAssignment.name;
70670             }
70671             else {
70672                 target = exprOrAssignment;
70673             }
70674             if (target.kind === 216 /* BinaryExpression */ && target.operatorToken.kind === 62 /* EqualsToken */) {
70675                 checkBinaryExpression(target, checkMode);
70676                 target = target.left;
70677             }
70678             if (target.kind === 200 /* ObjectLiteralExpression */) {
70679                 return checkObjectLiteralAssignment(target, sourceType, rightIsThis);
70680             }
70681             if (target.kind === 199 /* ArrayLiteralExpression */) {
70682                 return checkArrayLiteralAssignment(target, sourceType, checkMode);
70683             }
70684             return checkReferenceAssignment(target, sourceType, checkMode);
70685         }
70686         function checkReferenceAssignment(target, sourceType, checkMode) {
70687             var targetType = checkExpression(target, checkMode);
70688             var error = target.parent.kind === 290 /* SpreadAssignment */ ?
70689                 ts.Diagnostics.The_target_of_an_object_rest_assignment_must_be_a_variable_or_a_property_access :
70690                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_must_be_a_variable_or_a_property_access;
70691             var optionalError = target.parent.kind === 290 /* SpreadAssignment */ ?
70692                 ts.Diagnostics.The_target_of_an_object_rest_assignment_may_not_be_an_optional_property_access :
70693                 ts.Diagnostics.The_left_hand_side_of_an_assignment_expression_may_not_be_an_optional_property_access;
70694             if (checkReferenceExpression(target, error, optionalError)) {
70695                 checkTypeAssignableToAndOptionallyElaborate(sourceType, targetType, target, target);
70696             }
70697             if (ts.isPrivateIdentifierPropertyAccessExpression(target)) {
70698                 checkExternalEmitHelpers(target.parent, 2097152 /* ClassPrivateFieldSet */);
70699             }
70700             return sourceType;
70701         }
70702         /**
70703          * This is a *shallow* check: An expression is side-effect-free if the
70704          * evaluation of the expression *itself* cannot produce side effects.
70705          * For example, x++ / 3 is side-effect free because the / operator
70706          * does not have side effects.
70707          * The intent is to "smell test" an expression for correctness in positions where
70708          * its value is discarded (e.g. the left side of the comma operator).
70709          */
70710         function isSideEffectFree(node) {
70711             node = ts.skipParentheses(node);
70712             switch (node.kind) {
70713                 case 78 /* Identifier */:
70714                 case 10 /* StringLiteral */:
70715                 case 13 /* RegularExpressionLiteral */:
70716                 case 205 /* TaggedTemplateExpression */:
70717                 case 218 /* TemplateExpression */:
70718                 case 14 /* NoSubstitutionTemplateLiteral */:
70719                 case 8 /* NumericLiteral */:
70720                 case 9 /* BigIntLiteral */:
70721                 case 109 /* TrueKeyword */:
70722                 case 94 /* FalseKeyword */:
70723                 case 103 /* NullKeyword */:
70724                 case 150 /* UndefinedKeyword */:
70725                 case 208 /* FunctionExpression */:
70726                 case 221 /* ClassExpression */:
70727                 case 209 /* ArrowFunction */:
70728                 case 199 /* ArrayLiteralExpression */:
70729                 case 200 /* ObjectLiteralExpression */:
70730                 case 211 /* TypeOfExpression */:
70731                 case 225 /* NonNullExpression */:
70732                 case 274 /* JsxSelfClosingElement */:
70733                 case 273 /* JsxElement */:
70734                     return true;
70735                 case 217 /* ConditionalExpression */:
70736                     return isSideEffectFree(node.whenTrue) &&
70737                         isSideEffectFree(node.whenFalse);
70738                 case 216 /* BinaryExpression */:
70739                     if (ts.isAssignmentOperator(node.operatorToken.kind)) {
70740                         return false;
70741                     }
70742                     return isSideEffectFree(node.left) &&
70743                         isSideEffectFree(node.right);
70744                 case 214 /* PrefixUnaryExpression */:
70745                 case 215 /* PostfixUnaryExpression */:
70746                     // Unary operators ~, !, +, and - have no side effects.
70747                     // The rest do.
70748                     switch (node.operator) {
70749                         case 53 /* ExclamationToken */:
70750                         case 39 /* PlusToken */:
70751                         case 40 /* MinusToken */:
70752                         case 54 /* TildeToken */:
70753                             return true;
70754                     }
70755                     return false;
70756                 // Some forms listed here for clarity
70757                 case 212 /* VoidExpression */: // Explicit opt-out
70758                 case 206 /* TypeAssertionExpression */: // Not SEF, but can produce useful type warnings
70759                 case 224 /* AsExpression */: // Not SEF, but can produce useful type warnings
70760                 default:
70761                     return false;
70762             }
70763         }
70764         function isTypeEqualityComparableTo(source, target) {
70765             return (target.flags & 98304 /* Nullable */) !== 0 || isTypeComparableTo(source, target);
70766         }
70767         var CheckBinaryExpressionState;
70768         (function (CheckBinaryExpressionState) {
70769             CheckBinaryExpressionState[CheckBinaryExpressionState["MaybeCheckLeft"] = 0] = "MaybeCheckLeft";
70770             CheckBinaryExpressionState[CheckBinaryExpressionState["CheckRight"] = 1] = "CheckRight";
70771             CheckBinaryExpressionState[CheckBinaryExpressionState["FinishCheck"] = 2] = "FinishCheck";
70772         })(CheckBinaryExpressionState || (CheckBinaryExpressionState = {}));
70773         function checkBinaryExpression(node, checkMode) {
70774             var workStacks = {
70775                 expr: [node],
70776                 state: [0 /* MaybeCheckLeft */],
70777                 leftType: [undefined]
70778             };
70779             var stackIndex = 0;
70780             var lastResult;
70781             while (stackIndex >= 0) {
70782                 node = workStacks.expr[stackIndex];
70783                 switch (workStacks.state[stackIndex]) {
70784                     case 0 /* MaybeCheckLeft */: {
70785                         if (ts.isInJSFile(node) && ts.getAssignedExpandoInitializer(node)) {
70786                             finishInvocation(checkExpression(node.right, checkMode));
70787                             break;
70788                         }
70789                         checkGrammarNullishCoalesceWithLogicalExpression(node);
70790                         var operator = node.operatorToken.kind;
70791                         if (operator === 62 /* EqualsToken */ && (node.left.kind === 200 /* ObjectLiteralExpression */ || node.left.kind === 199 /* ArrayLiteralExpression */)) {
70792                             finishInvocation(checkDestructuringAssignment(node.left, checkExpression(node.right, checkMode), checkMode, node.right.kind === 107 /* ThisKeyword */));
70793                             break;
70794                         }
70795                         advanceState(1 /* CheckRight */);
70796                         maybeCheckExpression(node.left);
70797                         break;
70798                     }
70799                     case 1 /* CheckRight */: {
70800                         var leftType = lastResult;
70801                         workStacks.leftType[stackIndex] = leftType;
70802                         var operator = node.operatorToken.kind;
70803                         if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
70804                             checkTruthinessOfType(leftType, node.left);
70805                         }
70806                         advanceState(2 /* FinishCheck */);
70807                         maybeCheckExpression(node.right);
70808                         break;
70809                     }
70810                     case 2 /* FinishCheck */: {
70811                         var leftType = workStacks.leftType[stackIndex];
70812                         var rightType = lastResult;
70813                         finishInvocation(checkBinaryLikeExpressionWorker(node.left, node.operatorToken, node.right, leftType, rightType, node));
70814                         break;
70815                     }
70816                     default: return ts.Debug.fail("Invalid state " + workStacks.state[stackIndex] + " for checkBinaryExpression");
70817                 }
70818             }
70819             return lastResult;
70820             function finishInvocation(result) {
70821                 lastResult = result;
70822                 stackIndex--;
70823             }
70824             /**
70825              * Note that `advanceState` sets the _current_ head state, and that `maybeCheckExpression` potentially pushes on a new
70826              * head state; so `advanceState` must be called before any `maybeCheckExpression` during a state's execution.
70827              */
70828             function advanceState(nextState) {
70829                 workStacks.state[stackIndex] = nextState;
70830             }
70831             function maybeCheckExpression(node) {
70832                 if (ts.isBinaryExpression(node)) {
70833                     stackIndex++;
70834                     workStacks.expr[stackIndex] = node;
70835                     workStacks.state[stackIndex] = 0 /* MaybeCheckLeft */;
70836                     workStacks.leftType[stackIndex] = undefined;
70837                 }
70838                 else {
70839                     lastResult = checkExpression(node, checkMode);
70840                 }
70841             }
70842         }
70843         function checkGrammarNullishCoalesceWithLogicalExpression(node) {
70844             var left = node.left, operatorToken = node.operatorToken, right = node.right;
70845             if (operatorToken.kind === 60 /* QuestionQuestionToken */) {
70846                 if (ts.isBinaryExpression(left) && (left.operatorToken.kind === 56 /* BarBarToken */ || left.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
70847                     grammarErrorOnNode(left, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(left.operatorToken.kind), ts.tokenToString(operatorToken.kind));
70848                 }
70849                 if (ts.isBinaryExpression(right) && (right.operatorToken.kind === 56 /* BarBarToken */ || right.operatorToken.kind === 55 /* AmpersandAmpersandToken */)) {
70850                     grammarErrorOnNode(right, ts.Diagnostics._0_and_1_operations_cannot_be_mixed_without_parentheses, ts.tokenToString(right.operatorToken.kind), ts.tokenToString(operatorToken.kind));
70851                 }
70852             }
70853         }
70854         // Note that this and `checkBinaryExpression` above should behave mostly the same, except this elides some
70855         // expression-wide checks and does not use a work stack to fold nested binary expressions into the same callstack frame
70856         function checkBinaryLikeExpression(left, operatorToken, right, checkMode, errorNode) {
70857             var operator = operatorToken.kind;
70858             if (operator === 62 /* EqualsToken */ && (left.kind === 200 /* ObjectLiteralExpression */ || left.kind === 199 /* ArrayLiteralExpression */)) {
70859                 return checkDestructuringAssignment(left, checkExpression(right, checkMode), checkMode, right.kind === 107 /* ThisKeyword */);
70860             }
70861             var leftType;
70862             if (operator === 55 /* AmpersandAmpersandToken */ || operator === 56 /* BarBarToken */ || operator === 60 /* QuestionQuestionToken */) {
70863                 leftType = checkTruthinessExpression(left, checkMode);
70864             }
70865             else {
70866                 leftType = checkExpression(left, checkMode);
70867             }
70868             var rightType = checkExpression(right, checkMode);
70869             return checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode);
70870         }
70871         function checkBinaryLikeExpressionWorker(left, operatorToken, right, leftType, rightType, errorNode) {
70872             var operator = operatorToken.kind;
70873             switch (operator) {
70874                 case 41 /* AsteriskToken */:
70875                 case 42 /* AsteriskAsteriskToken */:
70876                 case 65 /* AsteriskEqualsToken */:
70877                 case 66 /* AsteriskAsteriskEqualsToken */:
70878                 case 43 /* SlashToken */:
70879                 case 67 /* SlashEqualsToken */:
70880                 case 44 /* PercentToken */:
70881                 case 68 /* PercentEqualsToken */:
70882                 case 40 /* MinusToken */:
70883                 case 64 /* MinusEqualsToken */:
70884                 case 47 /* LessThanLessThanToken */:
70885                 case 69 /* LessThanLessThanEqualsToken */:
70886                 case 48 /* GreaterThanGreaterThanToken */:
70887                 case 70 /* GreaterThanGreaterThanEqualsToken */:
70888                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
70889                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
70890                 case 51 /* BarToken */:
70891                 case 73 /* BarEqualsToken */:
70892                 case 52 /* CaretToken */:
70893                 case 77 /* CaretEqualsToken */:
70894                 case 50 /* AmpersandToken */:
70895                 case 72 /* AmpersandEqualsToken */:
70896                     if (leftType === silentNeverType || rightType === silentNeverType) {
70897                         return silentNeverType;
70898                     }
70899                     leftType = checkNonNullType(leftType, left);
70900                     rightType = checkNonNullType(rightType, right);
70901                     var suggestedOperator = void 0;
70902                     // if a user tries to apply a bitwise operator to 2 boolean operands
70903                     // try and return them a helpful suggestion
70904                     if ((leftType.flags & 528 /* BooleanLike */) &&
70905                         (rightType.flags & 528 /* BooleanLike */) &&
70906                         (suggestedOperator = getSuggestedBooleanOperator(operatorToken.kind)) !== undefined) {
70907                         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));
70908                         return numberType;
70909                     }
70910                     else {
70911                         // otherwise just check each operand separately and report errors as normal
70912                         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);
70913                         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);
70914                         var resultType_1;
70915                         // If both are any or unknown, allow operation; assume it will resolve to number
70916                         if ((isTypeAssignableToKind(leftType, 3 /* AnyOrUnknown */) && isTypeAssignableToKind(rightType, 3 /* AnyOrUnknown */)) ||
70917                             // Or, if neither could be bigint, implicit coercion results in a number result
70918                             !(maybeTypeOfKind(leftType, 2112 /* BigIntLike */) || maybeTypeOfKind(rightType, 2112 /* BigIntLike */))) {
70919                             resultType_1 = numberType;
70920                         }
70921                         // At least one is assignable to bigint, so check that both are
70922                         else if (bothAreBigIntLike(leftType, rightType)) {
70923                             switch (operator) {
70924                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */:
70925                                 case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */:
70926                                     reportOperatorError();
70927                                     break;
70928                                 case 42 /* AsteriskAsteriskToken */:
70929                                 case 66 /* AsteriskAsteriskEqualsToken */:
70930                                     if (languageVersion < 3 /* ES2016 */) {
70931                                         error(errorNode, ts.Diagnostics.Exponentiation_cannot_be_performed_on_bigint_values_unless_the_target_option_is_set_to_es2016_or_later);
70932                                     }
70933                             }
70934                             resultType_1 = bigintType;
70935                         }
70936                         // Exactly one of leftType/rightType is assignable to bigint
70937                         else {
70938                             reportOperatorError(bothAreBigIntLike);
70939                             resultType_1 = errorType;
70940                         }
70941                         if (leftOk && rightOk) {
70942                             checkAssignmentOperator(resultType_1);
70943                         }
70944                         return resultType_1;
70945                     }
70946                 case 39 /* PlusToken */:
70947                 case 63 /* PlusEqualsToken */:
70948                     if (leftType === silentNeverType || rightType === silentNeverType) {
70949                         return silentNeverType;
70950                     }
70951                     if (!isTypeAssignableToKind(leftType, 402653316 /* StringLike */) && !isTypeAssignableToKind(rightType, 402653316 /* StringLike */)) {
70952                         leftType = checkNonNullType(leftType, left);
70953                         rightType = checkNonNullType(rightType, right);
70954                     }
70955                     var resultType = void 0;
70956                     if (isTypeAssignableToKind(leftType, 296 /* NumberLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 296 /* NumberLike */, /*strict*/ true)) {
70957                         // Operands of an enum type are treated as having the primitive type Number.
70958                         // If both operands are of the Number primitive type, the result is of the Number primitive type.
70959                         resultType = numberType;
70960                     }
70961                     else if (isTypeAssignableToKind(leftType, 2112 /* BigIntLike */, /*strict*/ true) && isTypeAssignableToKind(rightType, 2112 /* BigIntLike */, /*strict*/ true)) {
70962                         // If both operands are of the BigInt primitive type, the result is of the BigInt primitive type.
70963                         resultType = bigintType;
70964                     }
70965                     else if (isTypeAssignableToKind(leftType, 402653316 /* StringLike */, /*strict*/ true) || isTypeAssignableToKind(rightType, 402653316 /* StringLike */, /*strict*/ true)) {
70966                         // If one or both operands are of the String primitive type, the result is of the String primitive type.
70967                         resultType = stringType;
70968                     }
70969                     else if (isTypeAny(leftType) || isTypeAny(rightType)) {
70970                         // Otherwise, the result is of type Any.
70971                         // NOTE: unknown type here denotes error type. Old compiler treated this case as any type so do we.
70972                         resultType = leftType === errorType || rightType === errorType ? errorType : anyType;
70973                     }
70974                     // Symbols are not allowed at all in arithmetic expressions
70975                     if (resultType && !checkForDisallowedESSymbolOperand(operator)) {
70976                         return resultType;
70977                     }
70978                     if (!resultType) {
70979                         // Types that have a reasonably good chance of being a valid operand type.
70980                         // If both types have an awaited type of one of these, we'll assume the user
70981                         // might be missing an await without doing an exhaustive check that inserting
70982                         // await(s) will actually be a completely valid binary expression.
70983                         var closeEnoughKind_1 = 296 /* NumberLike */ | 2112 /* BigIntLike */ | 402653316 /* StringLike */ | 3 /* AnyOrUnknown */;
70984                         reportOperatorError(function (left, right) {
70985                             return isTypeAssignableToKind(left, closeEnoughKind_1) &&
70986                                 isTypeAssignableToKind(right, closeEnoughKind_1);
70987                         });
70988                         return anyType;
70989                     }
70990                     if (operator === 63 /* PlusEqualsToken */) {
70991                         checkAssignmentOperator(resultType);
70992                     }
70993                     return resultType;
70994                 case 29 /* LessThanToken */:
70995                 case 31 /* GreaterThanToken */:
70996                 case 32 /* LessThanEqualsToken */:
70997                 case 33 /* GreaterThanEqualsToken */:
70998                     if (checkForDisallowedESSymbolOperand(operator)) {
70999                         leftType = getBaseTypeOfLiteralType(checkNonNullType(leftType, left));
71000                         rightType = getBaseTypeOfLiteralType(checkNonNullType(rightType, right));
71001                         reportOperatorErrorUnless(function (left, right) {
71002                             return isTypeComparableTo(left, right) || isTypeComparableTo(right, left) || (isTypeAssignableTo(left, numberOrBigIntType) && isTypeAssignableTo(right, numberOrBigIntType));
71003                         });
71004                     }
71005                     return booleanType;
71006                 case 34 /* EqualsEqualsToken */:
71007                 case 35 /* ExclamationEqualsToken */:
71008                 case 36 /* EqualsEqualsEqualsToken */:
71009                 case 37 /* ExclamationEqualsEqualsToken */:
71010                     reportOperatorErrorUnless(function (left, right) { return isTypeEqualityComparableTo(left, right) || isTypeEqualityComparableTo(right, left); });
71011                     return booleanType;
71012                 case 101 /* InstanceOfKeyword */:
71013                     return checkInstanceOfExpression(left, right, leftType, rightType);
71014                 case 100 /* InKeyword */:
71015                     return checkInExpression(left, right, leftType, rightType);
71016                 case 55 /* AmpersandAmpersandToken */:
71017                 case 75 /* AmpersandAmpersandEqualsToken */: {
71018                     var resultType_2 = getTypeFacts(leftType) & 4194304 /* Truthy */ ?
71019                         getUnionType([extractDefinitelyFalsyTypes(strictNullChecks ? leftType : getBaseTypeOfLiteralType(rightType)), rightType]) :
71020                         leftType;
71021                     if (operator === 75 /* AmpersandAmpersandEqualsToken */) {
71022                         checkAssignmentOperator(rightType);
71023                     }
71024                     return resultType_2;
71025                 }
71026                 case 56 /* BarBarToken */:
71027                 case 74 /* BarBarEqualsToken */: {
71028                     var resultType_3 = getTypeFacts(leftType) & 8388608 /* Falsy */ ?
71029                         getUnionType([removeDefinitelyFalsyTypes(leftType), rightType], 2 /* Subtype */) :
71030                         leftType;
71031                     if (operator === 74 /* BarBarEqualsToken */) {
71032                         checkAssignmentOperator(rightType);
71033                     }
71034                     return resultType_3;
71035                 }
71036                 case 60 /* QuestionQuestionToken */:
71037                 case 76 /* QuestionQuestionEqualsToken */: {
71038                     var resultType_4 = getTypeFacts(leftType) & 262144 /* EQUndefinedOrNull */ ?
71039                         getUnionType([getNonNullableType(leftType), rightType], 2 /* Subtype */) :
71040                         leftType;
71041                     if (operator === 76 /* QuestionQuestionEqualsToken */) {
71042                         checkAssignmentOperator(rightType);
71043                     }
71044                     return resultType_4;
71045                 }
71046                 case 62 /* EqualsToken */:
71047                     var declKind = ts.isBinaryExpression(left.parent) ? ts.getAssignmentDeclarationKind(left.parent) : 0 /* None */;
71048                     checkAssignmentDeclaration(declKind, rightType);
71049                     if (isAssignmentDeclaration(declKind)) {
71050                         if (!(rightType.flags & 524288 /* Object */) ||
71051                             declKind !== 2 /* ModuleExports */ &&
71052                                 declKind !== 6 /* Prototype */ &&
71053                                 !isEmptyObjectType(rightType) &&
71054                                 !isFunctionObjectType(rightType) &&
71055                                 !(ts.getObjectFlags(rightType) & 1 /* Class */)) {
71056                             // don't check assignability of module.exports=, C.prototype=, or expando types because they will necessarily be incomplete
71057                             checkAssignmentOperator(rightType);
71058                         }
71059                         return leftType;
71060                     }
71061                     else {
71062                         checkAssignmentOperator(rightType);
71063                         return getRegularTypeOfObjectLiteral(rightType);
71064                     }
71065                 case 27 /* CommaToken */:
71066                     if (!compilerOptions.allowUnreachableCode && isSideEffectFree(left) && !isEvalNode(right)) {
71067                         var sf = ts.getSourceFileOfNode(left);
71068                         var sourceText = sf.text;
71069                         var start_3 = ts.skipTrivia(sourceText, left.pos);
71070                         var isInDiag2657 = sf.parseDiagnostics.some(function (diag) {
71071                             if (diag.code !== ts.Diagnostics.JSX_expressions_must_have_one_parent_element.code)
71072                                 return false;
71073                             return ts.textSpanContainsPosition(diag, start_3);
71074                         });
71075                         if (!isInDiag2657)
71076                             error(left, ts.Diagnostics.Left_side_of_comma_operator_is_unused_and_has_no_side_effects);
71077                     }
71078                     return rightType;
71079                 default:
71080                     return ts.Debug.fail();
71081             }
71082             function bothAreBigIntLike(left, right) {
71083                 return isTypeAssignableToKind(left, 2112 /* BigIntLike */) && isTypeAssignableToKind(right, 2112 /* BigIntLike */);
71084             }
71085             function checkAssignmentDeclaration(kind, rightType) {
71086                 if (kind === 2 /* ModuleExports */) {
71087                     for (var _i = 0, _a = getPropertiesOfObjectType(rightType); _i < _a.length; _i++) {
71088                         var prop = _a[_i];
71089                         var propType = getTypeOfSymbol(prop);
71090                         if (propType.symbol && propType.symbol.flags & 32 /* Class */) {
71091                             var name = prop.escapedName;
71092                             var symbol = resolveName(prop.valueDeclaration, name, 788968 /* Type */, undefined, name, /*isUse*/ false);
71093                             if (symbol && symbol.declarations.some(ts.isJSDocTypedefTag)) {
71094                                 addDuplicateDeclarationErrorsForSymbols(symbol, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), prop);
71095                                 addDuplicateDeclarationErrorsForSymbols(prop, ts.Diagnostics.Duplicate_identifier_0, ts.unescapeLeadingUnderscores(name), symbol);
71096                             }
71097                         }
71098                     }
71099                 }
71100             }
71101             function isEvalNode(node) {
71102                 return node.kind === 78 /* Identifier */ && node.escapedText === "eval";
71103             }
71104             // Return true if there was no error, false if there was an error.
71105             function checkForDisallowedESSymbolOperand(operator) {
71106                 var offendingSymbolOperand = maybeTypeOfKind(leftType, 12288 /* ESSymbolLike */) ? left :
71107                     maybeTypeOfKind(rightType, 12288 /* ESSymbolLike */) ? right :
71108                         undefined;
71109                 if (offendingSymbolOperand) {
71110                     error(offendingSymbolOperand, ts.Diagnostics.The_0_operator_cannot_be_applied_to_type_symbol, ts.tokenToString(operator));
71111                     return false;
71112                 }
71113                 return true;
71114             }
71115             function getSuggestedBooleanOperator(operator) {
71116                 switch (operator) {
71117                     case 51 /* BarToken */:
71118                     case 73 /* BarEqualsToken */:
71119                         return 56 /* BarBarToken */;
71120                     case 52 /* CaretToken */:
71121                     case 77 /* CaretEqualsToken */:
71122                         return 37 /* ExclamationEqualsEqualsToken */;
71123                     case 50 /* AmpersandToken */:
71124                     case 72 /* AmpersandEqualsToken */:
71125                         return 55 /* AmpersandAmpersandToken */;
71126                     default:
71127                         return undefined;
71128                 }
71129             }
71130             function checkAssignmentOperator(valueType) {
71131                 if (produceDiagnostics && ts.isAssignmentOperator(operator)) {
71132                     // TypeScript 1.0 spec (April 2014): 4.17
71133                     // An assignment of the form
71134                     //    VarExpr = ValueExpr
71135                     // requires VarExpr to be classified as a reference
71136                     // A compound assignment furthermore requires VarExpr to be classified as a reference (section 4.1)
71137                     // and the type of the non-compound operation to be assignable to the type of VarExpr.
71138                     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)
71139                         && (!ts.isIdentifier(left) || ts.unescapeLeadingUnderscores(left.escapedText) !== "exports")) {
71140                         // to avoid cascading errors check assignability only if 'isReference' check succeeded and no errors were reported
71141                         checkTypeAssignableToAndOptionallyElaborate(valueType, leftType, left, right);
71142                     }
71143                 }
71144             }
71145             function isAssignmentDeclaration(kind) {
71146                 var _a;
71147                 switch (kind) {
71148                     case 2 /* ModuleExports */:
71149                         return true;
71150                     case 1 /* ExportsProperty */:
71151                     case 5 /* Property */:
71152                     case 6 /* Prototype */:
71153                     case 3 /* PrototypeProperty */:
71154                     case 4 /* ThisProperty */:
71155                         var symbol = getSymbolOfNode(left);
71156                         var init = ts.getAssignedExpandoInitializer(right);
71157                         return !!init && ts.isObjectLiteralExpression(init) &&
71158                             !!((_a = symbol === null || symbol === void 0 ? void 0 : symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
71159                     default:
71160                         return false;
71161                 }
71162             }
71163             /**
71164              * Returns true if an error is reported
71165              */
71166             function reportOperatorErrorUnless(typesAreCompatible) {
71167                 if (!typesAreCompatible(leftType, rightType)) {
71168                     reportOperatorError(typesAreCompatible);
71169                     return true;
71170                 }
71171                 return false;
71172             }
71173             function reportOperatorError(isRelated) {
71174                 var _a;
71175                 var wouldWorkWithAwait = false;
71176                 var errNode = errorNode || operatorToken;
71177                 if (isRelated) {
71178                     var awaitedLeftType = getAwaitedType(leftType);
71179                     var awaitedRightType = getAwaitedType(rightType);
71180                     wouldWorkWithAwait = !(awaitedLeftType === leftType && awaitedRightType === rightType)
71181                         && !!(awaitedLeftType && awaitedRightType)
71182                         && isRelated(awaitedLeftType, awaitedRightType);
71183                 }
71184                 var effectiveLeft = leftType;
71185                 var effectiveRight = rightType;
71186                 if (!wouldWorkWithAwait && isRelated) {
71187                     _a = getBaseTypesIfUnrelated(leftType, rightType, isRelated), effectiveLeft = _a[0], effectiveRight = _a[1];
71188                 }
71189                 var _b = getTypeNamesForErrorDisplay(effectiveLeft, effectiveRight), leftStr = _b[0], rightStr = _b[1];
71190                 if (!tryGiveBetterPrimaryError(errNode, wouldWorkWithAwait, leftStr, rightStr)) {
71191                     errorAndMaybeSuggestAwait(errNode, wouldWorkWithAwait, ts.Diagnostics.Operator_0_cannot_be_applied_to_types_1_and_2, ts.tokenToString(operatorToken.kind), leftStr, rightStr);
71192                 }
71193             }
71194             function tryGiveBetterPrimaryError(errNode, maybeMissingAwait, leftStr, rightStr) {
71195                 var typeName;
71196                 switch (operatorToken.kind) {
71197                     case 36 /* EqualsEqualsEqualsToken */:
71198                     case 34 /* EqualsEqualsToken */:
71199                         typeName = "false";
71200                         break;
71201                     case 37 /* ExclamationEqualsEqualsToken */:
71202                     case 35 /* ExclamationEqualsToken */:
71203                         typeName = "true";
71204                 }
71205                 if (typeName) {
71206                     return errorAndMaybeSuggestAwait(errNode, maybeMissingAwait, ts.Diagnostics.This_condition_will_always_return_0_since_the_types_1_and_2_have_no_overlap, typeName, leftStr, rightStr);
71207                 }
71208                 return undefined;
71209             }
71210         }
71211         function getBaseTypesIfUnrelated(leftType, rightType, isRelated) {
71212             var effectiveLeft = leftType;
71213             var effectiveRight = rightType;
71214             var leftBase = getBaseTypeOfLiteralType(leftType);
71215             var rightBase = getBaseTypeOfLiteralType(rightType);
71216             if (!isRelated(leftBase, rightBase)) {
71217                 effectiveLeft = leftBase;
71218                 effectiveRight = rightBase;
71219             }
71220             return [effectiveLeft, effectiveRight];
71221         }
71222         function checkYieldExpression(node) {
71223             // Grammar checking
71224             if (produceDiagnostics) {
71225                 if (!(node.flags & 8192 /* YieldContext */)) {
71226                     grammarErrorOnFirstToken(node, ts.Diagnostics.A_yield_expression_is_only_allowed_in_a_generator_body);
71227                 }
71228                 if (isInParameterInitializerBeforeContainingFunction(node)) {
71229                     error(node, ts.Diagnostics.yield_expressions_cannot_be_used_in_a_parameter_initializer);
71230                 }
71231             }
71232             var func = ts.getContainingFunction(node);
71233             if (!func)
71234                 return anyType;
71235             var functionFlags = ts.getFunctionFlags(func);
71236             if (!(functionFlags & 1 /* Generator */)) {
71237                 // If the user's code is syntactically correct, the func should always have a star. After all, we are in a yield context.
71238                 return anyType;
71239             }
71240             var isAsync = (functionFlags & 2 /* Async */) !== 0;
71241             if (node.asteriskToken) {
71242                 // Async generator functions prior to ESNext require the __await, __asyncDelegator,
71243                 // and __asyncValues helpers
71244                 if (isAsync && languageVersion < 99 /* ESNext */) {
71245                     checkExternalEmitHelpers(node, 53248 /* AsyncDelegatorIncludes */);
71246                 }
71247                 // Generator functions prior to ES2015 require the __values helper
71248                 if (!isAsync && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
71249                     checkExternalEmitHelpers(node, 256 /* Values */);
71250                 }
71251             }
71252             // There is no point in doing an assignability check if the function
71253             // has no explicit return type because the return type is directly computed
71254             // from the yield expressions.
71255             var returnType = getReturnTypeFromAnnotation(func);
71256             var iterationTypes = returnType && getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsync);
71257             var signatureYieldType = iterationTypes && iterationTypes.yieldType || anyType;
71258             var signatureNextType = iterationTypes && iterationTypes.nextType || anyType;
71259             var resolvedSignatureNextType = isAsync ? getAwaitedType(signatureNextType) || anyType : signatureNextType;
71260             var yieldExpressionType = node.expression ? checkExpression(node.expression) : undefinedWideningType;
71261             var yieldedType = getYieldedTypeOfYieldExpression(node, yieldExpressionType, resolvedSignatureNextType, isAsync);
71262             if (returnType && yieldedType) {
71263                 checkTypeAssignableToAndOptionallyElaborate(yieldedType, signatureYieldType, node.expression || node, node.expression);
71264             }
71265             if (node.asteriskToken) {
71266                 var use = isAsync ? 19 /* AsyncYieldStar */ : 17 /* YieldStar */;
71267                 return getIterationTypeOfIterable(use, 1 /* Return */, yieldExpressionType, node.expression)
71268                     || anyType;
71269             }
71270             else if (returnType) {
71271                 return getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, isAsync)
71272                     || anyType;
71273             }
71274             return getContextualIterationType(2 /* Next */, func) || anyType;
71275         }
71276         function checkConditionalExpression(node, checkMode) {
71277             var type = checkTruthinessExpression(node.condition);
71278             checkTestingKnownTruthyCallableType(node.condition, node.whenTrue, type);
71279             var type1 = checkExpression(node.whenTrue, checkMode);
71280             var type2 = checkExpression(node.whenFalse, checkMode);
71281             return getUnionType([type1, type2], 2 /* Subtype */);
71282         }
71283         function checkTemplateExpression(node) {
71284             var texts = [node.head.text];
71285             var types = [];
71286             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
71287                 var span = _a[_i];
71288                 var type = checkExpression(span.expression);
71289                 if (maybeTypeOfKind(type, 12288 /* ESSymbolLike */)) {
71290                     error(span.expression, ts.Diagnostics.Implicit_conversion_of_a_symbol_to_a_string_will_fail_at_runtime_Consider_wrapping_this_expression_in_String);
71291                 }
71292                 texts.push(span.literal.text);
71293                 types.push(isTypeAssignableTo(type, templateConstraintType) ? type : stringType);
71294             }
71295             return isConstContext(node) ? getTemplateLiteralType(texts, types) : stringType;
71296         }
71297         function getContextNode(node) {
71298             if (node.kind === 281 /* JsxAttributes */ && !ts.isJsxSelfClosingElement(node.parent)) {
71299                 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)
71300             }
71301             return node;
71302         }
71303         function checkExpressionWithContextualType(node, contextualType, inferenceContext, checkMode) {
71304             var context = getContextNode(node);
71305             var saveContextualType = context.contextualType;
71306             var saveInferenceContext = context.inferenceContext;
71307             try {
71308                 context.contextualType = contextualType;
71309                 context.inferenceContext = inferenceContext;
71310                 var type = checkExpression(node, checkMode | 1 /* Contextual */ | (inferenceContext ? 2 /* Inferential */ : 0));
71311                 // We strip literal freshness when an appropriate contextual type is present such that contextually typed
71312                 // literals always preserve their literal types (otherwise they might widen during type inference). An alternative
71313                 // here would be to not mark contextually typed literals as fresh in the first place.
71314                 var result = maybeTypeOfKind(type, 2944 /* Literal */) && isLiteralOfContextualType(type, instantiateContextualType(contextualType, node)) ?
71315                     getRegularTypeOfLiteralType(type) : type;
71316                 return result;
71317             }
71318             finally {
71319                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
71320                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
71321                 // may hold onto the checker that created it.
71322                 context.contextualType = saveContextualType;
71323                 context.inferenceContext = saveInferenceContext;
71324             }
71325         }
71326         function checkExpressionCached(node, checkMode) {
71327             var links = getNodeLinks(node);
71328             if (!links.resolvedType) {
71329                 if (checkMode && checkMode !== 0 /* Normal */) {
71330                     return checkExpression(node, checkMode);
71331                 }
71332                 // When computing a type that we're going to cache, we need to ignore any ongoing control flow
71333                 // analysis because variables may have transient types in indeterminable states. Moving flowLoopStart
71334                 // to the top of the stack ensures all transient types are computed from a known point.
71335                 var saveFlowLoopStart = flowLoopStart;
71336                 var saveFlowTypeCache = flowTypeCache;
71337                 flowLoopStart = flowLoopCount;
71338                 flowTypeCache = undefined;
71339                 links.resolvedType = checkExpression(node, checkMode);
71340                 flowTypeCache = saveFlowTypeCache;
71341                 flowLoopStart = saveFlowLoopStart;
71342             }
71343             return links.resolvedType;
71344         }
71345         function isTypeAssertion(node) {
71346             node = ts.skipParentheses(node);
71347             return node.kind === 206 /* TypeAssertionExpression */ || node.kind === 224 /* AsExpression */;
71348         }
71349         function checkDeclarationInitializer(declaration, contextualType) {
71350             var initializer = ts.getEffectiveInitializer(declaration);
71351             var type = getQuickTypeOfExpression(initializer) ||
71352                 (contextualType ? checkExpressionWithContextualType(initializer, contextualType, /*inferenceContext*/ undefined, 0 /* Normal */) : checkExpressionCached(initializer));
71353             return ts.isParameter(declaration) && declaration.name.kind === 197 /* ArrayBindingPattern */ &&
71354                 isTupleType(type) && !type.target.hasRestElement && getTypeReferenceArity(type) < declaration.name.elements.length ?
71355                 padTupleType(type, declaration.name) : type;
71356         }
71357         function padTupleType(type, pattern) {
71358             var patternElements = pattern.elements;
71359             var elementTypes = getTypeArguments(type).slice();
71360             var elementFlags = type.target.elementFlags.slice();
71361             for (var i = getTypeReferenceArity(type); i < patternElements.length; i++) {
71362                 var e = patternElements[i];
71363                 if (i < patternElements.length - 1 || !(e.kind === 198 /* BindingElement */ && e.dotDotDotToken)) {
71364                     elementTypes.push(!ts.isOmittedExpression(e) && hasDefaultValue(e) ? getTypeFromBindingElement(e, /*includePatternInType*/ false, /*reportErrors*/ false) : anyType);
71365                     elementFlags.push(2 /* Optional */);
71366                     if (!ts.isOmittedExpression(e) && !hasDefaultValue(e)) {
71367                         reportImplicitAny(e, anyType);
71368                     }
71369                 }
71370             }
71371             return createTupleType(elementTypes, elementFlags, type.target.readonly);
71372         }
71373         function widenTypeInferredFromInitializer(declaration, type) {
71374             var widened = ts.getCombinedNodeFlags(declaration) & 2 /* Const */ || ts.isDeclarationReadonly(declaration) ? type : getWidenedLiteralType(type);
71375             if (ts.isInJSFile(declaration)) {
71376                 if (widened.flags & 98304 /* Nullable */) {
71377                     reportImplicitAny(declaration, anyType);
71378                     return anyType;
71379                 }
71380                 else if (isEmptyArrayLiteralType(widened)) {
71381                     reportImplicitAny(declaration, anyArrayType);
71382                     return anyArrayType;
71383                 }
71384             }
71385             return widened;
71386         }
71387         function isLiteralOfContextualType(candidateType, contextualType) {
71388             if (contextualType) {
71389                 if (contextualType.flags & 3145728 /* UnionOrIntersection */) {
71390                     var types = contextualType.types;
71391                     return ts.some(types, function (t) { return isLiteralOfContextualType(candidateType, t); });
71392                 }
71393                 if (contextualType.flags & 58982400 /* InstantiableNonPrimitive */) {
71394                     // If the contextual type is a type variable constrained to a primitive type, consider
71395                     // this a literal context for literals of that primitive type. For example, given a
71396                     // type parameter 'T extends string', infer string literal types for T.
71397                     var constraint = getBaseConstraintOfType(contextualType) || unknownType;
71398                     return maybeTypeOfKind(constraint, 4 /* String */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
71399                         maybeTypeOfKind(constraint, 8 /* Number */) && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
71400                         maybeTypeOfKind(constraint, 64 /* BigInt */) && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
71401                         maybeTypeOfKind(constraint, 4096 /* ESSymbol */) && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */) ||
71402                         isLiteralOfContextualType(candidateType, constraint);
71403                 }
71404                 // If the contextual type is a literal of a particular primitive type, we consider this a
71405                 // literal context for all literals of that primitive type.
71406                 return !!(contextualType.flags & (128 /* StringLiteral */ | 4194304 /* Index */ | 134217728 /* TemplateLiteral */ | 268435456 /* StringMapping */) && maybeTypeOfKind(candidateType, 128 /* StringLiteral */) ||
71407                     contextualType.flags & 256 /* NumberLiteral */ && maybeTypeOfKind(candidateType, 256 /* NumberLiteral */) ||
71408                     contextualType.flags & 2048 /* BigIntLiteral */ && maybeTypeOfKind(candidateType, 2048 /* BigIntLiteral */) ||
71409                     contextualType.flags & 512 /* BooleanLiteral */ && maybeTypeOfKind(candidateType, 512 /* BooleanLiteral */) ||
71410                     contextualType.flags & 8192 /* UniqueESSymbol */ && maybeTypeOfKind(candidateType, 8192 /* UniqueESSymbol */));
71411             }
71412             return false;
71413         }
71414         function isConstContext(node) {
71415             var parent = node.parent;
71416             return ts.isAssertionExpression(parent) && ts.isConstTypeReference(parent.type) ||
71417                 (ts.isParenthesizedExpression(parent) || ts.isArrayLiteralExpression(parent) || ts.isSpreadElement(parent)) && isConstContext(parent) ||
71418                 (ts.isPropertyAssignment(parent) || ts.isShorthandPropertyAssignment(parent) || ts.isTemplateSpan(parent)) && isConstContext(parent.parent);
71419         }
71420         function checkExpressionForMutableLocation(node, checkMode, contextualType, forceTuple) {
71421             var type = checkExpression(node, checkMode, forceTuple);
71422             return isConstContext(node) ? getRegularTypeOfLiteralType(type) :
71423                 isTypeAssertion(node) ? type :
71424                     getWidenedLiteralLikeTypeForContextualType(type, instantiateContextualType(arguments.length === 2 ? getContextualType(node) : contextualType, node));
71425         }
71426         function checkPropertyAssignment(node, checkMode) {
71427             // Do not use hasDynamicName here, because that returns false for well known symbols.
71428             // We want to perform checkComputedPropertyName for all computed properties, including
71429             // well known symbols.
71430             if (node.name.kind === 158 /* ComputedPropertyName */) {
71431                 checkComputedPropertyName(node.name);
71432             }
71433             return checkExpressionForMutableLocation(node.initializer, checkMode);
71434         }
71435         function checkObjectLiteralMethod(node, checkMode) {
71436             // Grammar checking
71437             checkGrammarMethod(node);
71438             // Do not use hasDynamicName here, because that returns false for well known symbols.
71439             // We want to perform checkComputedPropertyName for all computed properties, including
71440             // well known symbols.
71441             if (node.name.kind === 158 /* ComputedPropertyName */) {
71442                 checkComputedPropertyName(node.name);
71443             }
71444             var uninstantiatedType = checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
71445             return instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
71446         }
71447         function instantiateTypeWithSingleGenericCallSignature(node, type, checkMode) {
71448             if (checkMode && checkMode & (2 /* Inferential */ | 8 /* SkipGenericFunctions */)) {
71449                 var callSignature = getSingleSignature(type, 0 /* Call */, /*allowMembers*/ true);
71450                 var constructSignature = getSingleSignature(type, 1 /* Construct */, /*allowMembers*/ true);
71451                 var signature = callSignature || constructSignature;
71452                 if (signature && signature.typeParameters) {
71453                     var contextualType = getApparentTypeOfContextualType(node, 2 /* NoConstraints */);
71454                     if (contextualType) {
71455                         var contextualSignature = getSingleSignature(getNonNullableType(contextualType), callSignature ? 0 /* Call */ : 1 /* Construct */, /*allowMembers*/ false);
71456                         if (contextualSignature && !contextualSignature.typeParameters) {
71457                             if (checkMode & 8 /* SkipGenericFunctions */) {
71458                                 skippedGenericFunction(node, checkMode);
71459                                 return anyFunctionType;
71460                             }
71461                             var context = getInferenceContext(node);
71462                             // We have an expression that is an argument of a generic function for which we are performing
71463                             // type argument inference. The expression is of a function type with a single generic call
71464                             // signature and a contextual function type with a single non-generic call signature. Now check
71465                             // if the outer function returns a function type with a single non-generic call signature and
71466                             // if some of the outer function type parameters have no inferences so far. If so, we can
71467                             // potentially add inferred type parameters to the outer function return type.
71468                             var returnType = context.signature && getReturnTypeOfSignature(context.signature);
71469                             var returnSignature = returnType && getSingleCallOrConstructSignature(returnType);
71470                             if (returnSignature && !returnSignature.typeParameters && !ts.every(context.inferences, hasInferenceCandidates)) {
71471                                 // Instantiate the signature with its own type parameters as type arguments, possibly
71472                                 // renaming the type parameters to ensure they have unique names.
71473                                 var uniqueTypeParameters = getUniqueTypeParameters(context, signature.typeParameters);
71474                                 var instantiatedSignature = getSignatureInstantiationWithoutFillingInTypeArguments(signature, uniqueTypeParameters);
71475                                 // Infer from the parameters of the instantiated signature to the parameters of the
71476                                 // contextual signature starting with an empty set of inference candidates.
71477                                 var inferences_3 = ts.map(context.inferences, function (info) { return createInferenceInfo(info.typeParameter); });
71478                                 applyToParameterTypes(instantiatedSignature, contextualSignature, function (source, target) {
71479                                     inferTypes(inferences_3, source, target, /*priority*/ 0, /*contravariant*/ true);
71480                                 });
71481                                 if (ts.some(inferences_3, hasInferenceCandidates)) {
71482                                     // We have inference candidates, indicating that one or more type parameters are referenced
71483                                     // in the parameter types of the contextual signature. Now also infer from the return type.
71484                                     applyToReturnTypes(instantiatedSignature, contextualSignature, function (source, target) {
71485                                         inferTypes(inferences_3, source, target);
71486                                     });
71487                                     // If the type parameters for which we produced candidates do not have any inferences yet,
71488                                     // we adopt the new inference candidates and add the type parameters of the expression type
71489                                     // to the set of inferred type parameters for the outer function return type.
71490                                     if (!hasOverlappingInferences(context.inferences, inferences_3)) {
71491                                         mergeInferences(context.inferences, inferences_3);
71492                                         context.inferredTypeParameters = ts.concatenate(context.inferredTypeParameters, uniqueTypeParameters);
71493                                         return getOrCreateTypeFromSignature(instantiatedSignature);
71494                                     }
71495                                 }
71496                             }
71497                             return getOrCreateTypeFromSignature(instantiateSignatureInContextOf(signature, contextualSignature, context));
71498                         }
71499                     }
71500                 }
71501             }
71502             return type;
71503         }
71504         function skippedGenericFunction(node, checkMode) {
71505             if (checkMode & 2 /* Inferential */) {
71506                 // We have skipped a generic function during inferential typing. Obtain the inference context and
71507                 // indicate this has occurred such that we know a second pass of inference is be needed.
71508                 var context = getInferenceContext(node);
71509                 context.flags |= 4 /* SkippedGenericFunction */;
71510             }
71511         }
71512         function hasInferenceCandidates(info) {
71513             return !!(info.candidates || info.contraCandidates);
71514         }
71515         function hasOverlappingInferences(a, b) {
71516             for (var i = 0; i < a.length; i++) {
71517                 if (hasInferenceCandidates(a[i]) && hasInferenceCandidates(b[i])) {
71518                     return true;
71519                 }
71520             }
71521             return false;
71522         }
71523         function mergeInferences(target, source) {
71524             for (var i = 0; i < target.length; i++) {
71525                 if (!hasInferenceCandidates(target[i]) && hasInferenceCandidates(source[i])) {
71526                     target[i] = source[i];
71527                 }
71528             }
71529         }
71530         function getUniqueTypeParameters(context, typeParameters) {
71531             var result = [];
71532             var oldTypeParameters;
71533             var newTypeParameters;
71534             for (var _i = 0, typeParameters_2 = typeParameters; _i < typeParameters_2.length; _i++) {
71535                 var tp = typeParameters_2[_i];
71536                 var name = tp.symbol.escapedName;
71537                 if (hasTypeParameterByName(context.inferredTypeParameters, name) || hasTypeParameterByName(result, name)) {
71538                     var newName = getUniqueTypeParameterName(ts.concatenate(context.inferredTypeParameters, result), name);
71539                     var symbol = createSymbol(262144 /* TypeParameter */, newName);
71540                     var newTypeParameter = createTypeParameter(symbol);
71541                     newTypeParameter.target = tp;
71542                     oldTypeParameters = ts.append(oldTypeParameters, tp);
71543                     newTypeParameters = ts.append(newTypeParameters, newTypeParameter);
71544                     result.push(newTypeParameter);
71545                 }
71546                 else {
71547                     result.push(tp);
71548                 }
71549             }
71550             if (newTypeParameters) {
71551                 var mapper = createTypeMapper(oldTypeParameters, newTypeParameters);
71552                 for (var _a = 0, newTypeParameters_1 = newTypeParameters; _a < newTypeParameters_1.length; _a++) {
71553                     var tp = newTypeParameters_1[_a];
71554                     tp.mapper = mapper;
71555                 }
71556             }
71557             return result;
71558         }
71559         function hasTypeParameterByName(typeParameters, name) {
71560             return ts.some(typeParameters, function (tp) { return tp.symbol.escapedName === name; });
71561         }
71562         function getUniqueTypeParameterName(typeParameters, baseName) {
71563             var len = baseName.length;
71564             while (len > 1 && baseName.charCodeAt(len - 1) >= 48 /* _0 */ && baseName.charCodeAt(len - 1) <= 57 /* _9 */)
71565                 len--;
71566             var s = baseName.slice(0, len);
71567             for (var index = 1; true; index++) {
71568                 var augmentedName = (s + index);
71569                 if (!hasTypeParameterByName(typeParameters, augmentedName)) {
71570                     return augmentedName;
71571                 }
71572             }
71573         }
71574         function getReturnTypeOfSingleNonGenericCallSignature(funcType) {
71575             var signature = getSingleCallSignature(funcType);
71576             if (signature && !signature.typeParameters) {
71577                 return getReturnTypeOfSignature(signature);
71578             }
71579         }
71580         function getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) {
71581             var funcType = checkExpression(expr.expression);
71582             var nonOptionalType = getOptionalExpressionType(funcType, expr.expression);
71583             var returnType = getReturnTypeOfSingleNonGenericCallSignature(funcType);
71584             return returnType && propagateOptionalTypeMarker(returnType, expr, nonOptionalType !== funcType);
71585         }
71586         /**
71587          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
71588          * with computing the type and may not fully check all contained sub-expressions for errors.
71589          */
71590         function getTypeOfExpression(node) {
71591             // Don't bother caching types that require no flow analysis and are quick to compute.
71592             var quickType = getQuickTypeOfExpression(node);
71593             if (quickType) {
71594                 return quickType;
71595             }
71596             // If a type has been cached for the node, return it.
71597             if (node.flags & 67108864 /* TypeCached */ && flowTypeCache) {
71598                 var cachedType = flowTypeCache[getNodeId(node)];
71599                 if (cachedType) {
71600                     return cachedType;
71601                 }
71602             }
71603             var startInvocationCount = flowInvocationCount;
71604             var type = checkExpression(node);
71605             // If control flow analysis was required to determine the type, it is worth caching.
71606             if (flowInvocationCount !== startInvocationCount) {
71607                 var cache = flowTypeCache || (flowTypeCache = []);
71608                 cache[getNodeId(node)] = type;
71609                 ts.setNodeFlags(node, node.flags | 67108864 /* TypeCached */);
71610             }
71611             return type;
71612         }
71613         function getQuickTypeOfExpression(node) {
71614             var expr = ts.skipParentheses(node);
71615             // Optimize for the common case of a call to a function with a single non-generic call
71616             // signature where we can just fetch the return type without checking the arguments.
71617             if (ts.isCallExpression(expr) && expr.expression.kind !== 105 /* SuperKeyword */ && !ts.isRequireCall(expr, /*checkArgumentIsStringLiteralLike*/ true) && !isSymbolOrSymbolForCall(expr)) {
71618                 var type = ts.isCallChain(expr) ? getReturnTypeOfSingleNonGenericSignatureOfCallChain(expr) :
71619                     getReturnTypeOfSingleNonGenericCallSignature(checkNonNullExpression(expr.expression));
71620                 if (type) {
71621                     return type;
71622                 }
71623             }
71624             else if (ts.isAssertionExpression(expr) && !ts.isConstTypeReference(expr.type)) {
71625                 return getTypeFromTypeNode(expr.type);
71626             }
71627             else if (node.kind === 8 /* NumericLiteral */ || node.kind === 10 /* StringLiteral */ ||
71628                 node.kind === 109 /* TrueKeyword */ || node.kind === 94 /* FalseKeyword */) {
71629                 return checkExpression(node);
71630             }
71631             return undefined;
71632         }
71633         /**
71634          * Returns the type of an expression. Unlike checkExpression, this function is simply concerned
71635          * with computing the type and may not fully check all contained sub-expressions for errors.
71636          * It is intended for uses where you know there is no contextual type,
71637          * and requesting the contextual type might cause a circularity or other bad behaviour.
71638          * It sets the contextual type of the node to any before calling getTypeOfExpression.
71639          */
71640         function getContextFreeTypeOfExpression(node) {
71641             var links = getNodeLinks(node);
71642             if (links.contextFreeType) {
71643                 return links.contextFreeType;
71644             }
71645             var saveContextualType = node.contextualType;
71646             node.contextualType = anyType;
71647             try {
71648                 var type = links.contextFreeType = checkExpression(node, 4 /* SkipContextSensitive */);
71649                 return type;
71650             }
71651             finally {
71652                 // In the event our operation is canceled or some other exception occurs, reset the contextual type
71653                 // so that we do not accidentally hold onto an instance of the checker, as a Type created in the services layer
71654                 // may hold onto the checker that created it.
71655                 node.contextualType = saveContextualType;
71656             }
71657         }
71658         function checkExpression(node, checkMode, forceTuple) {
71659             ts.tracing.push("check" /* Check */, "checkExpression", { kind: node.kind, pos: node.pos, end: node.end });
71660             var saveCurrentNode = currentNode;
71661             currentNode = node;
71662             instantiationCount = 0;
71663             var uninstantiatedType = checkExpressionWorker(node, checkMode, forceTuple);
71664             var type = instantiateTypeWithSingleGenericCallSignature(node, uninstantiatedType, checkMode);
71665             if (isConstEnumObjectType(type)) {
71666                 checkConstEnumAccess(node, type);
71667             }
71668             currentNode = saveCurrentNode;
71669             ts.tracing.pop();
71670             return type;
71671         }
71672         function checkConstEnumAccess(node, type) {
71673             // enum object type for const enums are only permitted in:
71674             // - 'left' in property access
71675             // - 'object' in indexed access
71676             // - target in rhs of import statement
71677             var ok = (node.parent.kind === 201 /* PropertyAccessExpression */ && node.parent.expression === node) ||
71678                 (node.parent.kind === 202 /* ElementAccessExpression */ && node.parent.expression === node) ||
71679                 ((node.kind === 78 /* Identifier */ || node.kind === 157 /* QualifiedName */) && isInRightSideOfImportOrExportAssignment(node) ||
71680                     (node.parent.kind === 176 /* TypeQuery */ && node.parent.exprName === node)) ||
71681                 (node.parent.kind === 270 /* ExportSpecifier */); // We allow reexporting const enums
71682             if (!ok) {
71683                 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);
71684             }
71685             if (compilerOptions.isolatedModules) {
71686                 ts.Debug.assert(!!(type.symbol.flags & 128 /* ConstEnum */));
71687                 var constEnumDeclaration = type.symbol.valueDeclaration;
71688                 if (constEnumDeclaration.flags & 8388608 /* Ambient */) {
71689                     error(node, ts.Diagnostics.Cannot_access_ambient_const_enums_when_the_isolatedModules_flag_is_provided);
71690                 }
71691             }
71692         }
71693         function checkParenthesizedExpression(node, checkMode) {
71694             var tag = ts.isInJSFile(node) ? ts.getJSDocTypeTag(node) : undefined;
71695             if (tag) {
71696                 return checkAssertionWorker(tag, tag.typeExpression.type, node.expression, checkMode);
71697             }
71698             return checkExpression(node.expression, checkMode);
71699         }
71700         function checkExpressionWorker(node, checkMode, forceTuple) {
71701             var kind = node.kind;
71702             if (cancellationToken) {
71703                 // Only bother checking on a few construct kinds.  We don't want to be excessively
71704                 // hitting the cancellation token on every node we check.
71705                 switch (kind) {
71706                     case 221 /* ClassExpression */:
71707                     case 208 /* FunctionExpression */:
71708                     case 209 /* ArrowFunction */:
71709                         cancellationToken.throwIfCancellationRequested();
71710                 }
71711             }
71712             switch (kind) {
71713                 case 78 /* Identifier */:
71714                     return checkIdentifier(node);
71715                 case 107 /* ThisKeyword */:
71716                     return checkThisExpression(node);
71717                 case 105 /* SuperKeyword */:
71718                     return checkSuperExpression(node);
71719                 case 103 /* NullKeyword */:
71720                     return nullWideningType;
71721                 case 14 /* NoSubstitutionTemplateLiteral */:
71722                 case 10 /* StringLiteral */:
71723                     return getFreshTypeOfLiteralType(getLiteralType(node.text));
71724                 case 8 /* NumericLiteral */:
71725                     checkGrammarNumericLiteral(node);
71726                     return getFreshTypeOfLiteralType(getLiteralType(+node.text));
71727                 case 9 /* BigIntLiteral */:
71728                     checkGrammarBigIntLiteral(node);
71729                     return getFreshTypeOfLiteralType(getBigIntLiteralType(node));
71730                 case 109 /* TrueKeyword */:
71731                     return trueType;
71732                 case 94 /* FalseKeyword */:
71733                     return falseType;
71734                 case 218 /* TemplateExpression */:
71735                     return checkTemplateExpression(node);
71736                 case 13 /* RegularExpressionLiteral */:
71737                     return globalRegExpType;
71738                 case 199 /* ArrayLiteralExpression */:
71739                     return checkArrayLiteral(node, checkMode, forceTuple);
71740                 case 200 /* ObjectLiteralExpression */:
71741                     return checkObjectLiteral(node, checkMode);
71742                 case 201 /* PropertyAccessExpression */:
71743                     return checkPropertyAccessExpression(node);
71744                 case 157 /* QualifiedName */:
71745                     return checkQualifiedName(node);
71746                 case 202 /* ElementAccessExpression */:
71747                     return checkIndexedAccess(node);
71748                 case 203 /* CallExpression */:
71749                     if (node.expression.kind === 99 /* ImportKeyword */) {
71750                         return checkImportCallExpression(node);
71751                     }
71752                 // falls through
71753                 case 204 /* NewExpression */:
71754                     return checkCallExpression(node, checkMode);
71755                 case 205 /* TaggedTemplateExpression */:
71756                     return checkTaggedTemplateExpression(node);
71757                 case 207 /* ParenthesizedExpression */:
71758                     return checkParenthesizedExpression(node, checkMode);
71759                 case 221 /* ClassExpression */:
71760                     return checkClassExpression(node);
71761                 case 208 /* FunctionExpression */:
71762                 case 209 /* ArrowFunction */:
71763                     return checkFunctionExpressionOrObjectLiteralMethod(node, checkMode);
71764                 case 211 /* TypeOfExpression */:
71765                     return checkTypeOfExpression(node);
71766                 case 206 /* TypeAssertionExpression */:
71767                 case 224 /* AsExpression */:
71768                     return checkAssertion(node);
71769                 case 225 /* NonNullExpression */:
71770                     return checkNonNullAssertion(node);
71771                 case 226 /* MetaProperty */:
71772                     return checkMetaProperty(node);
71773                 case 210 /* DeleteExpression */:
71774                     return checkDeleteExpression(node);
71775                 case 212 /* VoidExpression */:
71776                     return checkVoidExpression(node);
71777                 case 213 /* AwaitExpression */:
71778                     return checkAwaitExpression(node);
71779                 case 214 /* PrefixUnaryExpression */:
71780                     return checkPrefixUnaryExpression(node);
71781                 case 215 /* PostfixUnaryExpression */:
71782                     return checkPostfixUnaryExpression(node);
71783                 case 216 /* BinaryExpression */:
71784                     return checkBinaryExpression(node, checkMode);
71785                 case 217 /* ConditionalExpression */:
71786                     return checkConditionalExpression(node, checkMode);
71787                 case 220 /* SpreadElement */:
71788                     return checkSpreadExpression(node, checkMode);
71789                 case 222 /* OmittedExpression */:
71790                     return undefinedWideningType;
71791                 case 219 /* YieldExpression */:
71792                     return checkYieldExpression(node);
71793                 case 227 /* SyntheticExpression */:
71794                     return checkSyntheticExpression(node);
71795                 case 283 /* JsxExpression */:
71796                     return checkJsxExpression(node, checkMode);
71797                 case 273 /* JsxElement */:
71798                     return checkJsxElement(node, checkMode);
71799                 case 274 /* JsxSelfClosingElement */:
71800                     return checkJsxSelfClosingElement(node, checkMode);
71801                 case 277 /* JsxFragment */:
71802                     return checkJsxFragment(node);
71803                 case 281 /* JsxAttributes */:
71804                     return checkJsxAttributes(node, checkMode);
71805                 case 275 /* JsxOpeningElement */:
71806                     ts.Debug.fail("Shouldn't ever directly check a JsxOpeningElement");
71807             }
71808             return errorType;
71809         }
71810         // DECLARATION AND STATEMENT TYPE CHECKING
71811         function checkTypeParameter(node) {
71812             // Grammar Checking
71813             if (node.expression) {
71814                 grammarErrorOnFirstToken(node.expression, ts.Diagnostics.Type_expected);
71815             }
71816             checkSourceElement(node.constraint);
71817             checkSourceElement(node.default);
71818             var typeParameter = getDeclaredTypeOfTypeParameter(getSymbolOfNode(node));
71819             // Resolve base constraint to reveal circularity errors
71820             getBaseConstraintOfType(typeParameter);
71821             if (!hasNonCircularTypeParameterDefault(typeParameter)) {
71822                 error(node.default, ts.Diagnostics.Type_parameter_0_has_a_circular_default, typeToString(typeParameter));
71823             }
71824             var constraintType = getConstraintOfTypeParameter(typeParameter);
71825             var defaultType = getDefaultFromTypeParameter(typeParameter);
71826             if (constraintType && defaultType) {
71827                 checkTypeAssignableTo(defaultType, getTypeWithThisArgument(instantiateType(constraintType, makeUnaryTypeMapper(typeParameter, defaultType)), defaultType), node.default, ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
71828             }
71829             if (produceDiagnostics) {
71830                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_parameter_name_cannot_be_0);
71831             }
71832         }
71833         function checkParameter(node) {
71834             // Grammar checking
71835             // It is a SyntaxError if the Identifier "eval" or the Identifier "arguments" occurs as the
71836             // Identifier in a PropertySetParameterList of a PropertyAssignment that is contained in strict code
71837             // or if its FunctionBody is strict code(11.1.5).
71838             checkGrammarDecoratorsAndModifiers(node);
71839             checkVariableLikeDeclaration(node);
71840             var func = ts.getContainingFunction(node);
71841             if (ts.hasSyntacticModifier(node, 92 /* ParameterPropertyModifier */)) {
71842                 if (!(func.kind === 166 /* Constructor */ && ts.nodeIsPresent(func.body))) {
71843                     error(node, ts.Diagnostics.A_parameter_property_is_only_allowed_in_a_constructor_implementation);
71844                 }
71845                 if (func.kind === 166 /* Constructor */ && ts.isIdentifier(node.name) && node.name.escapedText === "constructor") {
71846                     error(node.name, ts.Diagnostics.constructor_cannot_be_used_as_a_parameter_property_name);
71847                 }
71848             }
71849             if (node.questionToken && ts.isBindingPattern(node.name) && func.body) {
71850                 error(node, ts.Diagnostics.A_binding_pattern_parameter_cannot_be_optional_in_an_implementation_signature);
71851             }
71852             if (node.name && ts.isIdentifier(node.name) && (node.name.escapedText === "this" || node.name.escapedText === "new")) {
71853                 if (func.parameters.indexOf(node) !== 0) {
71854                     error(node, ts.Diagnostics.A_0_parameter_must_be_the_first_parameter, node.name.escapedText);
71855                 }
71856                 if (func.kind === 166 /* Constructor */ || func.kind === 170 /* ConstructSignature */ || func.kind === 175 /* ConstructorType */) {
71857                     error(node, ts.Diagnostics.A_constructor_cannot_have_a_this_parameter);
71858                 }
71859                 if (func.kind === 209 /* ArrowFunction */) {
71860                     error(node, ts.Diagnostics.An_arrow_function_cannot_have_a_this_parameter);
71861                 }
71862                 if (func.kind === 167 /* GetAccessor */ || func.kind === 168 /* SetAccessor */) {
71863                     error(node, ts.Diagnostics.get_and_set_accessors_cannot_declare_this_parameters);
71864                 }
71865             }
71866             // Only check rest parameter type if it's not a binding pattern. Since binding patterns are
71867             // not allowed in a rest parameter, we already have an error from checkGrammarParameterList.
71868             if (node.dotDotDotToken && !ts.isBindingPattern(node.name) && !isTypeAssignableTo(getReducedType(getTypeOfSymbol(node.symbol)), anyReadonlyArrayType)) {
71869                 error(node, ts.Diagnostics.A_rest_parameter_must_be_of_an_array_type);
71870             }
71871         }
71872         function checkTypePredicate(node) {
71873             var parent = getTypePredicateParent(node);
71874             if (!parent) {
71875                 // The parent must not be valid.
71876                 error(node, ts.Diagnostics.A_type_predicate_is_only_allowed_in_return_type_position_for_functions_and_methods);
71877                 return;
71878             }
71879             var signature = getSignatureFromDeclaration(parent);
71880             var typePredicate = getTypePredicateOfSignature(signature);
71881             if (!typePredicate) {
71882                 return;
71883             }
71884             checkSourceElement(node.type);
71885             var parameterName = node.parameterName;
71886             if (typePredicate.kind === 0 /* This */ || typePredicate.kind === 2 /* AssertsThis */) {
71887                 getTypeFromThisTypeNode(parameterName);
71888             }
71889             else {
71890                 if (typePredicate.parameterIndex >= 0) {
71891                     if (signatureHasRestParameter(signature) && typePredicate.parameterIndex === signature.parameters.length - 1) {
71892                         error(parameterName, ts.Diagnostics.A_type_predicate_cannot_reference_a_rest_parameter);
71893                     }
71894                     else {
71895                         if (typePredicate.type) {
71896                             var leadingError = function () { return ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.A_type_predicate_s_type_must_be_assignable_to_its_parameter_s_type); };
71897                             checkTypeAssignableTo(typePredicate.type, getTypeOfSymbol(signature.parameters[typePredicate.parameterIndex]), node.type, 
71898                             /*headMessage*/ undefined, leadingError);
71899                         }
71900                     }
71901                 }
71902                 else if (parameterName) {
71903                     var hasReportedError = false;
71904                     for (var _i = 0, _a = parent.parameters; _i < _a.length; _i++) {
71905                         var name = _a[_i].name;
71906                         if (ts.isBindingPattern(name) &&
71907                             checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, parameterName, typePredicate.parameterName)) {
71908                             hasReportedError = true;
71909                             break;
71910                         }
71911                     }
71912                     if (!hasReportedError) {
71913                         error(node.parameterName, ts.Diagnostics.Cannot_find_parameter_0, typePredicate.parameterName);
71914                     }
71915                 }
71916             }
71917         }
71918         function getTypePredicateParent(node) {
71919             switch (node.parent.kind) {
71920                 case 209 /* ArrowFunction */:
71921                 case 169 /* CallSignature */:
71922                 case 251 /* FunctionDeclaration */:
71923                 case 208 /* FunctionExpression */:
71924                 case 174 /* FunctionType */:
71925                 case 165 /* MethodDeclaration */:
71926                 case 164 /* MethodSignature */:
71927                     var parent = node.parent;
71928                     if (node === parent.type) {
71929                         return parent;
71930                     }
71931             }
71932         }
71933         function checkIfTypePredicateVariableIsDeclaredInBindingPattern(pattern, predicateVariableNode, predicateVariableName) {
71934             for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
71935                 var element = _a[_i];
71936                 if (ts.isOmittedExpression(element)) {
71937                     continue;
71938                 }
71939                 var name = element.name;
71940                 if (name.kind === 78 /* Identifier */ && name.escapedText === predicateVariableName) {
71941                     error(predicateVariableNode, ts.Diagnostics.A_type_predicate_cannot_reference_element_0_in_a_binding_pattern, predicateVariableName);
71942                     return true;
71943                 }
71944                 else if (name.kind === 197 /* ArrayBindingPattern */ || name.kind === 196 /* ObjectBindingPattern */) {
71945                     if (checkIfTypePredicateVariableIsDeclaredInBindingPattern(name, predicateVariableNode, predicateVariableName)) {
71946                         return true;
71947                     }
71948                 }
71949             }
71950         }
71951         function checkSignatureDeclaration(node) {
71952             // Grammar checking
71953             if (node.kind === 171 /* IndexSignature */) {
71954                 checkGrammarIndexSignature(node);
71955             }
71956             // TODO (yuisu): Remove this check in else-if when SyntaxKind.Construct is moved and ambient context is handled
71957             else if (node.kind === 174 /* FunctionType */ || node.kind === 251 /* FunctionDeclaration */ || node.kind === 175 /* ConstructorType */ ||
71958                 node.kind === 169 /* CallSignature */ || node.kind === 166 /* Constructor */ ||
71959                 node.kind === 170 /* ConstructSignature */) {
71960                 checkGrammarFunctionLikeDeclaration(node);
71961             }
71962             var functionFlags = ts.getFunctionFlags(node);
71963             if (!(functionFlags & 4 /* Invalid */)) {
71964                 // Async generators prior to ESNext require the __await and __asyncGenerator helpers
71965                 if ((functionFlags & 3 /* AsyncGenerator */) === 3 /* AsyncGenerator */ && languageVersion < 99 /* ESNext */) {
71966                     checkExternalEmitHelpers(node, 12288 /* AsyncGeneratorIncludes */);
71967                 }
71968                 // Async functions prior to ES2017 require the __awaiter helper
71969                 if ((functionFlags & 3 /* AsyncGenerator */) === 2 /* Async */ && languageVersion < 4 /* ES2017 */) {
71970                     checkExternalEmitHelpers(node, 64 /* Awaiter */);
71971                 }
71972                 // Generator functions, Async functions, and Async Generator functions prior to
71973                 // ES2015 require the __generator helper
71974                 if ((functionFlags & 3 /* AsyncGenerator */) !== 0 /* Normal */ && languageVersion < 2 /* ES2015 */) {
71975                     checkExternalEmitHelpers(node, 128 /* Generator */);
71976                 }
71977             }
71978             checkTypeParameters(node.typeParameters);
71979             ts.forEach(node.parameters, checkParameter);
71980             // TODO(rbuckton): Should we start checking JSDoc types?
71981             if (node.type) {
71982                 checkSourceElement(node.type);
71983             }
71984             if (produceDiagnostics) {
71985                 checkCollisionWithArgumentsInGeneratedCode(node);
71986                 var returnTypeNode = ts.getEffectiveReturnTypeNode(node);
71987                 if (noImplicitAny && !returnTypeNode) {
71988                     switch (node.kind) {
71989                         case 170 /* ConstructSignature */:
71990                             error(node, ts.Diagnostics.Construct_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
71991                             break;
71992                         case 169 /* CallSignature */:
71993                             error(node, ts.Diagnostics.Call_signature_which_lacks_return_type_annotation_implicitly_has_an_any_return_type);
71994                             break;
71995                     }
71996                 }
71997                 if (returnTypeNode) {
71998                     var functionFlags_1 = ts.getFunctionFlags(node);
71999                     if ((functionFlags_1 & (4 /* Invalid */ | 1 /* Generator */)) === 1 /* Generator */) {
72000                         var returnType = getTypeFromTypeNode(returnTypeNode);
72001                         if (returnType === voidType) {
72002                             error(returnTypeNode, ts.Diagnostics.A_generator_cannot_have_a_void_type_annotation);
72003                         }
72004                         else {
72005                             // Naively, one could check that Generator<any, any, any> is assignable to the return type annotation.
72006                             // However, that would not catch the error in the following case.
72007                             //
72008                             //    interface BadGenerator extends Iterable<number>, Iterator<string> { }
72009                             //    function* g(): BadGenerator { } // Iterable and Iterator have different types!
72010                             //
72011                             var generatorYieldType = getIterationTypeOfGeneratorFunctionReturnType(0 /* Yield */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || anyType;
72012                             var generatorReturnType = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || generatorYieldType;
72013                             var generatorNextType = getIterationTypeOfGeneratorFunctionReturnType(2 /* Next */, returnType, (functionFlags_1 & 2 /* Async */) !== 0) || unknownType;
72014                             var generatorInstantiation = createGeneratorReturnType(generatorYieldType, generatorReturnType, generatorNextType, !!(functionFlags_1 & 2 /* Async */));
72015                             checkTypeAssignableTo(generatorInstantiation, returnType, returnTypeNode);
72016                         }
72017                     }
72018                     else if ((functionFlags_1 & 3 /* AsyncGenerator */) === 2 /* Async */) {
72019                         checkAsyncFunctionReturnType(node, returnTypeNode);
72020                     }
72021                 }
72022                 if (node.kind !== 171 /* IndexSignature */ && node.kind !== 308 /* JSDocFunctionType */) {
72023                     registerForUnusedIdentifiersCheck(node);
72024                 }
72025             }
72026         }
72027         function checkClassForDuplicateDeclarations(node) {
72028             var instanceNames = new ts.Map();
72029             var staticNames = new ts.Map();
72030             // instance and static private identifiers share the same scope
72031             var privateIdentifiers = new ts.Map();
72032             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
72033                 var member = _a[_i];
72034                 if (member.kind === 166 /* Constructor */) {
72035                     for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
72036                         var param = _c[_b];
72037                         if (ts.isParameterPropertyDeclaration(param, member) && !ts.isBindingPattern(param.name)) {
72038                             addName(instanceNames, param.name, param.name.escapedText, 3 /* GetOrSetAccessor */);
72039                         }
72040                     }
72041                 }
72042                 else {
72043                     var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */);
72044                     var name = member.name;
72045                     if (!name) {
72046                         return;
72047                     }
72048                     var names = ts.isPrivateIdentifier(name) ? privateIdentifiers :
72049                         isStatic ? staticNames :
72050                             instanceNames;
72051                     var memberName = name && ts.getPropertyNameForPropertyNameNode(name);
72052                     if (memberName) {
72053                         switch (member.kind) {
72054                             case 167 /* GetAccessor */:
72055                                 addName(names, name, memberName, 1 /* GetAccessor */);
72056                                 break;
72057                             case 168 /* SetAccessor */:
72058                                 addName(names, name, memberName, 2 /* SetAccessor */);
72059                                 break;
72060                             case 163 /* PropertyDeclaration */:
72061                                 addName(names, name, memberName, 3 /* GetOrSetAccessor */);
72062                                 break;
72063                             case 165 /* MethodDeclaration */:
72064                                 addName(names, name, memberName, 8 /* Method */);
72065                                 break;
72066                         }
72067                     }
72068                 }
72069             }
72070             function addName(names, location, name, meaning) {
72071                 var prev = names.get(name);
72072                 if (prev) {
72073                     if (prev & 8 /* Method */) {
72074                         if (meaning !== 8 /* Method */) {
72075                             error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
72076                         }
72077                     }
72078                     else if (prev & meaning) {
72079                         error(location, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(location));
72080                     }
72081                     else {
72082                         names.set(name, prev | meaning);
72083                     }
72084                 }
72085                 else {
72086                     names.set(name, meaning);
72087                 }
72088             }
72089         }
72090         /**
72091          * Static members being set on a constructor function may conflict with built-in properties
72092          * of Function. Esp. in ECMAScript 5 there are non-configurable and non-writable
72093          * built-in properties. This check issues a transpile error when a class has a static
72094          * member with the same name as a non-writable built-in property.
72095          *
72096          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.3
72097          * @see http://www.ecma-international.org/ecma-262/5.1/#sec-15.3.5
72098          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-properties-of-the-function-constructor
72099          * @see http://www.ecma-international.org/ecma-262/6.0/#sec-function-instances
72100          */
72101         function checkClassForStaticPropertyNameConflicts(node) {
72102             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
72103                 var member = _a[_i];
72104                 var memberNameNode = member.name;
72105                 var isStatic = ts.hasSyntacticModifier(member, 32 /* Static */);
72106                 if (isStatic && memberNameNode) {
72107                     var memberName = ts.getPropertyNameForPropertyNameNode(memberNameNode);
72108                     switch (memberName) {
72109                         case "name":
72110                         case "length":
72111                         case "caller":
72112                         case "arguments":
72113                         case "prototype":
72114                             var message = ts.Diagnostics.Static_property_0_conflicts_with_built_in_property_Function_0_of_constructor_function_1;
72115                             var className = getNameOfSymbolAsWritten(getSymbolOfNode(node));
72116                             error(memberNameNode, message, memberName, className);
72117                             break;
72118                     }
72119                 }
72120             }
72121         }
72122         function checkObjectTypeForDuplicateDeclarations(node) {
72123             var names = new ts.Map();
72124             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
72125                 var member = _a[_i];
72126                 if (member.kind === 162 /* PropertySignature */) {
72127                     var memberName = void 0;
72128                     var name = member.name;
72129                     switch (name.kind) {
72130                         case 10 /* StringLiteral */:
72131                         case 8 /* NumericLiteral */:
72132                             memberName = name.text;
72133                             break;
72134                         case 78 /* Identifier */:
72135                             memberName = ts.idText(name);
72136                             break;
72137                         default:
72138                             continue;
72139                     }
72140                     if (names.get(memberName)) {
72141                         error(ts.getNameOfDeclaration(member.symbol.valueDeclaration), ts.Diagnostics.Duplicate_identifier_0, memberName);
72142                         error(member.name, ts.Diagnostics.Duplicate_identifier_0, memberName);
72143                     }
72144                     else {
72145                         names.set(memberName, true);
72146                     }
72147                 }
72148             }
72149         }
72150         function checkTypeForDuplicateIndexSignatures(node) {
72151             if (node.kind === 253 /* InterfaceDeclaration */) {
72152                 var nodeSymbol = getSymbolOfNode(node);
72153                 // in case of merging interface declaration it is possible that we'll enter this check procedure several times for every declaration
72154                 // to prevent this run check only for the first declaration of a given kind
72155                 if (nodeSymbol.declarations.length > 0 && nodeSymbol.declarations[0] !== node) {
72156                     return;
72157                 }
72158             }
72159             // TypeScript 1.0 spec (April 2014)
72160             // 3.7.4: An object type can contain at most one string index signature and one numeric index signature.
72161             // 8.5: A class declaration can have at most one string index member declaration and one numeric index member declaration
72162             var indexSymbol = getIndexSymbol(getSymbolOfNode(node));
72163             if (indexSymbol) {
72164                 var seenNumericIndexer = false;
72165                 var seenStringIndexer = false;
72166                 for (var _i = 0, _a = indexSymbol.declarations; _i < _a.length; _i++) {
72167                     var decl = _a[_i];
72168                     var declaration = decl;
72169                     if (declaration.parameters.length === 1 && declaration.parameters[0].type) {
72170                         switch (declaration.parameters[0].type.kind) {
72171                             case 147 /* StringKeyword */:
72172                                 if (!seenStringIndexer) {
72173                                     seenStringIndexer = true;
72174                                 }
72175                                 else {
72176                                     error(declaration, ts.Diagnostics.Duplicate_string_index_signature);
72177                                 }
72178                                 break;
72179                             case 144 /* NumberKeyword */:
72180                                 if (!seenNumericIndexer) {
72181                                     seenNumericIndexer = true;
72182                                 }
72183                                 else {
72184                                     error(declaration, ts.Diagnostics.Duplicate_number_index_signature);
72185                                 }
72186                                 break;
72187                         }
72188                     }
72189                 }
72190             }
72191         }
72192         function checkPropertyDeclaration(node) {
72193             // Grammar checking
72194             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarProperty(node))
72195                 checkGrammarComputedPropertyName(node.name);
72196             checkVariableLikeDeclaration(node);
72197             // Private class fields transformation relies on WeakMaps.
72198             if (ts.isPrivateIdentifier(node.name) && languageVersion < 99 /* ESNext */) {
72199                 for (var lexicalScope = ts.getEnclosingBlockScopeContainer(node); !!lexicalScope; lexicalScope = ts.getEnclosingBlockScopeContainer(lexicalScope)) {
72200                     getNodeLinks(lexicalScope).flags |= 67108864 /* ContainsClassWithPrivateIdentifiers */;
72201                 }
72202             }
72203         }
72204         function checkPropertySignature(node) {
72205             if (ts.isPrivateIdentifier(node.name)) {
72206                 error(node, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
72207             }
72208             return checkPropertyDeclaration(node);
72209         }
72210         function checkMethodDeclaration(node) {
72211             // Grammar checking
72212             if (!checkGrammarMethod(node))
72213                 checkGrammarComputedPropertyName(node.name);
72214             if (ts.isPrivateIdentifier(node.name)) {
72215                 error(node, ts.Diagnostics.A_method_cannot_be_named_with_a_private_identifier);
72216             }
72217             // Grammar checking for modifiers is done inside the function checkGrammarFunctionLikeDeclaration
72218             checkFunctionOrMethodDeclaration(node);
72219             // Abstract methods cannot have an implementation.
72220             // Extra checks are to avoid reporting multiple errors relating to the "abstractness" of the node.
72221             if (ts.hasSyntacticModifier(node, 128 /* Abstract */) && node.kind === 165 /* MethodDeclaration */ && node.body) {
72222                 error(node, ts.Diagnostics.Method_0_cannot_have_an_implementation_because_it_is_marked_abstract, ts.declarationNameToString(node.name));
72223             }
72224         }
72225         function checkConstructorDeclaration(node) {
72226             // Grammar check on signature of constructor and modifier of the constructor is done in checkSignatureDeclaration function.
72227             checkSignatureDeclaration(node);
72228             // Grammar check for checking only related to constructorDeclaration
72229             if (!checkGrammarConstructorTypeParameters(node))
72230                 checkGrammarConstructorTypeAnnotation(node);
72231             checkSourceElement(node.body);
72232             var symbol = getSymbolOfNode(node);
72233             var firstDeclaration = ts.getDeclarationOfKind(symbol, node.kind);
72234             // Only type check the symbol once
72235             if (node === firstDeclaration) {
72236                 checkFunctionOrConstructorSymbol(symbol);
72237             }
72238             // exit early in the case of signature - super checks are not relevant to them
72239             if (ts.nodeIsMissing(node.body)) {
72240                 return;
72241             }
72242             if (!produceDiagnostics) {
72243                 return;
72244             }
72245             function isInstancePropertyWithInitializerOrPrivateIdentifierProperty(n) {
72246                 if (ts.isPrivateIdentifierPropertyDeclaration(n)) {
72247                     return true;
72248                 }
72249                 return n.kind === 163 /* PropertyDeclaration */ &&
72250                     !ts.hasSyntacticModifier(n, 32 /* Static */) &&
72251                     !!n.initializer;
72252             }
72253             // TS 1.0 spec (April 2014): 8.3.2
72254             // Constructors of classes with no extends clause may not contain super calls, whereas
72255             // constructors of derived classes must contain at least one super call somewhere in their function body.
72256             var containingClassDecl = node.parent;
72257             if (ts.getClassExtendsHeritageElement(containingClassDecl)) {
72258                 captureLexicalThis(node.parent, containingClassDecl);
72259                 var classExtendsNull = classDeclarationExtendsNull(containingClassDecl);
72260                 var superCall = findFirstSuperCall(node.body);
72261                 if (superCall) {
72262                     if (classExtendsNull) {
72263                         error(superCall, ts.Diagnostics.A_constructor_cannot_contain_a_super_call_when_its_class_extends_null);
72264                     }
72265                     // The first statement in the body of a constructor (excluding prologue directives) must be a super call
72266                     // if both of the following are true:
72267                     // - The containing class is a derived class.
72268                     // - The constructor declares parameter properties
72269                     //   or the containing class declares instance member variables with initializers.
72270                     var superCallShouldBeFirst = (compilerOptions.target !== 99 /* ESNext */ || !compilerOptions.useDefineForClassFields) &&
72271                         (ts.some(node.parent.members, isInstancePropertyWithInitializerOrPrivateIdentifierProperty) ||
72272                             ts.some(node.parameters, function (p) { return ts.hasSyntacticModifier(p, 92 /* ParameterPropertyModifier */); }));
72273                     // Skip past any prologue directives to find the first statement
72274                     // to ensure that it was a super call.
72275                     if (superCallShouldBeFirst) {
72276                         var statements = node.body.statements;
72277                         var superCallStatement = void 0;
72278                         for (var _i = 0, statements_4 = statements; _i < statements_4.length; _i++) {
72279                             var statement = statements_4[_i];
72280                             if (statement.kind === 233 /* ExpressionStatement */ && ts.isSuperCall(statement.expression)) {
72281                                 superCallStatement = statement;
72282                                 break;
72283                             }
72284                             if (!ts.isPrologueDirective(statement)) {
72285                                 break;
72286                             }
72287                         }
72288                         if (!superCallStatement) {
72289                             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);
72290                         }
72291                     }
72292                 }
72293                 else if (!classExtendsNull) {
72294                     error(node, ts.Diagnostics.Constructors_for_derived_classes_must_contain_a_super_call);
72295                 }
72296             }
72297         }
72298         function checkAccessorDeclaration(node) {
72299             if (produceDiagnostics) {
72300                 // Grammar checking accessors
72301                 if (!checkGrammarFunctionLikeDeclaration(node) && !checkGrammarAccessor(node))
72302                     checkGrammarComputedPropertyName(node.name);
72303                 checkDecorators(node);
72304                 checkSignatureDeclaration(node);
72305                 if (node.kind === 167 /* GetAccessor */) {
72306                     if (!(node.flags & 8388608 /* Ambient */) && ts.nodeIsPresent(node.body) && (node.flags & 256 /* HasImplicitReturn */)) {
72307                         if (!(node.flags & 512 /* HasExplicitReturn */)) {
72308                             error(node.name, ts.Diagnostics.A_get_accessor_must_return_a_value);
72309                         }
72310                     }
72311                 }
72312                 // Do not use hasDynamicName here, because that returns false for well known symbols.
72313                 // We want to perform checkComputedPropertyName for all computed properties, including
72314                 // well known symbols.
72315                 if (node.name.kind === 158 /* ComputedPropertyName */) {
72316                     checkComputedPropertyName(node.name);
72317                 }
72318                 if (ts.isPrivateIdentifier(node.name)) {
72319                     error(node.name, ts.Diagnostics.An_accessor_cannot_be_named_with_a_private_identifier);
72320                 }
72321                 if (!hasNonBindableDynamicName(node)) {
72322                     // TypeScript 1.0 spec (April 2014): 8.4.3
72323                     // Accessors for the same member name must specify the same accessibility.
72324                     var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
72325                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
72326                     if (otherAccessor) {
72327                         var nodeFlags = ts.getEffectiveModifierFlags(node);
72328                         var otherFlags = ts.getEffectiveModifierFlags(otherAccessor);
72329                         if ((nodeFlags & 28 /* AccessibilityModifier */) !== (otherFlags & 28 /* AccessibilityModifier */)) {
72330                             error(node.name, ts.Diagnostics.Getter_and_setter_accessors_do_not_agree_in_visibility);
72331                         }
72332                         if ((nodeFlags & 128 /* Abstract */) !== (otherFlags & 128 /* Abstract */)) {
72333                             error(node.name, ts.Diagnostics.Accessors_must_both_be_abstract_or_non_abstract);
72334                         }
72335                         // TypeScript 1.0 spec (April 2014): 4.5
72336                         // If both accessors include type annotations, the specified types must be identical.
72337                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getAnnotatedAccessorType, ts.Diagnostics.get_and_set_accessor_must_have_the_same_type);
72338                         checkAccessorDeclarationTypesIdentical(node, otherAccessor, getThisTypeOfDeclaration, ts.Diagnostics.get_and_set_accessor_must_have_the_same_this_type);
72339                     }
72340                 }
72341                 var returnType = getTypeOfAccessors(getSymbolOfNode(node));
72342                 if (node.kind === 167 /* GetAccessor */) {
72343                     checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, returnType);
72344                 }
72345             }
72346             checkSourceElement(node.body);
72347         }
72348         function checkAccessorDeclarationTypesIdentical(first, second, getAnnotatedType, message) {
72349             var firstType = getAnnotatedType(first);
72350             var secondType = getAnnotatedType(second);
72351             if (firstType && secondType && !isTypeIdenticalTo(firstType, secondType)) {
72352                 error(first, message);
72353             }
72354         }
72355         function checkMissingDeclaration(node) {
72356             checkDecorators(node);
72357         }
72358         function getEffectiveTypeArguments(node, typeParameters) {
72359             return fillMissingTypeArguments(ts.map(node.typeArguments, getTypeFromTypeNode), typeParameters, getMinTypeArgumentCount(typeParameters), ts.isInJSFile(node));
72360         }
72361         function checkTypeArgumentConstraints(node, typeParameters) {
72362             var typeArguments;
72363             var mapper;
72364             var result = true;
72365             for (var i = 0; i < typeParameters.length; i++) {
72366                 var constraint = getConstraintOfTypeParameter(typeParameters[i]);
72367                 if (constraint) {
72368                     if (!typeArguments) {
72369                         typeArguments = getEffectiveTypeArguments(node, typeParameters);
72370                         mapper = createTypeMapper(typeParameters, typeArguments);
72371                     }
72372                     result = result && checkTypeAssignableTo(typeArguments[i], instantiateType(constraint, mapper), node.typeArguments[i], ts.Diagnostics.Type_0_does_not_satisfy_the_constraint_1);
72373                 }
72374             }
72375             return result;
72376         }
72377         function getTypeParametersForTypeReference(node) {
72378             var type = getTypeFromTypeReference(node);
72379             if (type !== errorType) {
72380                 var symbol = getNodeLinks(node).resolvedSymbol;
72381                 if (symbol) {
72382                     return symbol.flags & 524288 /* TypeAlias */ && getSymbolLinks(symbol).typeParameters ||
72383                         (ts.getObjectFlags(type) & 4 /* Reference */ ? type.target.localTypeParameters : undefined);
72384                 }
72385             }
72386             return undefined;
72387         }
72388         function checkTypeReferenceNode(node) {
72389             checkGrammarTypeArguments(node, node.typeArguments);
72390             if (node.kind === 173 /* TypeReference */ && node.typeName.jsdocDotPos !== undefined && !ts.isInJSFile(node) && !ts.isInJSDoc(node)) {
72391                 grammarErrorAtPos(node, node.typeName.jsdocDotPos, 1, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
72392             }
72393             ts.forEach(node.typeArguments, checkSourceElement);
72394             var type = getTypeFromTypeReference(node);
72395             if (type !== errorType) {
72396                 if (node.typeArguments && produceDiagnostics) {
72397                     var typeParameters = getTypeParametersForTypeReference(node);
72398                     if (typeParameters) {
72399                         checkTypeArgumentConstraints(node, typeParameters);
72400                     }
72401                 }
72402                 var symbol = getNodeLinks(node).resolvedSymbol;
72403                 if (symbol) {
72404                     if (ts.some(symbol.declarations, function (d) { return isTypeDeclaration(d) && !!(d.flags & 134217728 /* Deprecated */); })) {
72405                         errorOrSuggestion(/* isError */ false, getDeprecatedSuggestionNode(node), ts.Diagnostics._0_is_deprecated, symbol.escapedName);
72406                     }
72407                     if (type.flags & 32 /* Enum */ && symbol.flags & 8 /* EnumMember */) {
72408                         error(node, ts.Diagnostics.Enum_type_0_has_members_with_initializers_that_are_not_literals, typeToString(type));
72409                     }
72410                 }
72411             }
72412         }
72413         function getTypeArgumentConstraint(node) {
72414             var typeReferenceNode = ts.tryCast(node.parent, ts.isTypeReferenceType);
72415             if (!typeReferenceNode)
72416                 return undefined;
72417             var typeParameters = getTypeParametersForTypeReference(typeReferenceNode); // TODO: GH#18217
72418             var constraint = getConstraintOfTypeParameter(typeParameters[typeReferenceNode.typeArguments.indexOf(node)]);
72419             return constraint && instantiateType(constraint, createTypeMapper(typeParameters, getEffectiveTypeArguments(typeReferenceNode, typeParameters)));
72420         }
72421         function checkTypeQuery(node) {
72422             getTypeFromTypeQueryNode(node);
72423         }
72424         function checkTypeLiteral(node) {
72425             ts.forEach(node.members, checkSourceElement);
72426             if (produceDiagnostics) {
72427                 var type = getTypeFromTypeLiteralOrFunctionOrConstructorTypeNode(node);
72428                 checkIndexConstraints(type);
72429                 checkTypeForDuplicateIndexSignatures(node);
72430                 checkObjectTypeForDuplicateDeclarations(node);
72431             }
72432         }
72433         function checkArrayType(node) {
72434             checkSourceElement(node.elementType);
72435         }
72436         function checkTupleType(node) {
72437             var elementTypes = node.elements;
72438             var seenOptionalElement = false;
72439             var seenRestElement = false;
72440             var hasNamedElement = ts.some(elementTypes, ts.isNamedTupleMember);
72441             for (var i = 0; i < elementTypes.length; i++) {
72442                 var e = elementTypes[i];
72443                 if (e.kind !== 192 /* NamedTupleMember */ && hasNamedElement) {
72444                     grammarErrorOnNode(e, ts.Diagnostics.Tuple_members_must_all_have_names_or_all_not_have_names);
72445                     break;
72446                 }
72447                 var flags = getTupleElementFlags(e);
72448                 if (flags & 8 /* Variadic */) {
72449                     var type = getTypeFromTypeNode(e.type);
72450                     if (!isArrayLikeType(type)) {
72451                         error(e, ts.Diagnostics.A_rest_element_type_must_be_an_array_type);
72452                         break;
72453                     }
72454                     if (isArrayType(type) || isTupleType(type) && type.target.combinedFlags & 4 /* Rest */) {
72455                         seenRestElement = true;
72456                     }
72457                 }
72458                 else if (flags & 4 /* Rest */) {
72459                     seenRestElement = true;
72460                 }
72461                 else if (flags & 2 /* Optional */) {
72462                     seenOptionalElement = true;
72463                 }
72464                 else if (seenOptionalElement) {
72465                     grammarErrorOnNode(e, ts.Diagnostics.A_required_element_cannot_follow_an_optional_element);
72466                     break;
72467                 }
72468                 if (seenRestElement && i !== elementTypes.length - 1) {
72469                     grammarErrorOnNode(e, ts.Diagnostics.A_rest_element_must_be_last_in_a_tuple_type);
72470                     break;
72471                 }
72472             }
72473             ts.forEach(node.elements, checkSourceElement);
72474             getTypeFromTypeNode(node);
72475         }
72476         function checkUnionOrIntersectionType(node) {
72477             ts.forEach(node.types, checkSourceElement);
72478             getTypeFromTypeNode(node);
72479         }
72480         function checkIndexedAccessIndexType(type, accessNode) {
72481             if (!(type.flags & 8388608 /* IndexedAccess */)) {
72482                 return type;
72483             }
72484             // Check if the index type is assignable to 'keyof T' for the object type.
72485             var objectType = type.objectType;
72486             var indexType = type.indexType;
72487             if (isTypeAssignableTo(indexType, getIndexType(objectType, /*stringsOnly*/ false))) {
72488                 if (accessNode.kind === 202 /* ElementAccessExpression */ && ts.isAssignmentTarget(accessNode) &&
72489                     ts.getObjectFlags(objectType) & 32 /* Mapped */ && getMappedTypeModifiers(objectType) & 1 /* IncludeReadonly */) {
72490                     error(accessNode, ts.Diagnostics.Index_signature_in_type_0_only_permits_reading, typeToString(objectType));
72491                 }
72492                 return type;
72493             }
72494             // Check if we're indexing with a numeric type and if either object or index types
72495             // is a generic type with a constraint that has a numeric index signature.
72496             var apparentObjectType = getApparentType(objectType);
72497             if (getIndexInfoOfType(apparentObjectType, 1 /* Number */) && isTypeAssignableToKind(indexType, 296 /* NumberLike */)) {
72498                 return type;
72499             }
72500             if (isGenericObjectType(objectType)) {
72501                 var propertyName_1 = getPropertyNameFromIndex(indexType, accessNode);
72502                 if (propertyName_1) {
72503                     var propertySymbol = forEachType(apparentObjectType, function (t) { return getPropertyOfType(t, propertyName_1); });
72504                     if (propertySymbol && ts.getDeclarationModifierFlagsFromSymbol(propertySymbol) & 24 /* NonPublicAccessibilityModifier */) {
72505                         error(accessNode, ts.Diagnostics.Private_or_protected_member_0_cannot_be_accessed_on_a_type_parameter, ts.unescapeLeadingUnderscores(propertyName_1));
72506                         return errorType;
72507                     }
72508                 }
72509             }
72510             error(accessNode, ts.Diagnostics.Type_0_cannot_be_used_to_index_type_1, typeToString(indexType), typeToString(objectType));
72511             return errorType;
72512         }
72513         function checkIndexedAccessType(node) {
72514             checkSourceElement(node.objectType);
72515             checkSourceElement(node.indexType);
72516             checkIndexedAccessIndexType(getTypeFromIndexedAccessTypeNode(node), node);
72517         }
72518         function checkMappedType(node) {
72519             checkSourceElement(node.typeParameter);
72520             checkSourceElement(node.nameType);
72521             checkSourceElement(node.type);
72522             if (!node.type) {
72523                 reportImplicitAny(node, anyType);
72524             }
72525             var type = getTypeFromMappedTypeNode(node);
72526             var nameType = getNameTypeFromMappedType(type);
72527             if (nameType) {
72528                 checkTypeAssignableTo(nameType, keyofConstraintType, node.nameType);
72529             }
72530             else {
72531                 var constraintType = getConstraintTypeFromMappedType(type);
72532                 checkTypeAssignableTo(constraintType, keyofConstraintType, ts.getEffectiveConstraintOfTypeParameter(node.typeParameter));
72533             }
72534         }
72535         function checkThisType(node) {
72536             getTypeFromThisTypeNode(node);
72537         }
72538         function checkTypeOperator(node) {
72539             checkGrammarTypeOperatorNode(node);
72540             checkSourceElement(node.type);
72541         }
72542         function checkConditionalType(node) {
72543             ts.forEachChild(node, checkSourceElement);
72544         }
72545         function checkInferType(node) {
72546             if (!ts.findAncestor(node, function (n) { return n.parent && n.parent.kind === 184 /* ConditionalType */ && n.parent.extendsType === n; })) {
72547                 grammarErrorOnNode(node, ts.Diagnostics.infer_declarations_are_only_permitted_in_the_extends_clause_of_a_conditional_type);
72548             }
72549             checkSourceElement(node.typeParameter);
72550             registerForUnusedIdentifiersCheck(node);
72551         }
72552         function checkTemplateLiteralType(node) {
72553             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
72554                 var span = _a[_i];
72555                 checkSourceElement(span.type);
72556                 var type = getTypeFromTypeNode(span.type);
72557                 checkTypeAssignableTo(type, templateConstraintType, span.type);
72558             }
72559             getTypeFromTypeNode(node);
72560         }
72561         function checkImportType(node) {
72562             checkSourceElement(node.argument);
72563             getTypeFromTypeNode(node);
72564         }
72565         function checkNamedTupleMember(node) {
72566             if (node.dotDotDotToken && node.questionToken) {
72567                 grammarErrorOnNode(node, ts.Diagnostics.A_tuple_member_cannot_be_both_optional_and_rest);
72568             }
72569             if (node.type.kind === 180 /* OptionalType */) {
72570                 grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_optional_with_a_question_mark_after_the_name_and_before_the_colon_rather_than_after_the_type);
72571             }
72572             if (node.type.kind === 181 /* RestType */) {
72573                 grammarErrorOnNode(node.type, ts.Diagnostics.A_labeled_tuple_element_is_declared_as_rest_with_a_before_the_name_rather_than_before_the_type);
72574             }
72575             checkSourceElement(node.type);
72576             getTypeFromTypeNode(node);
72577         }
72578         function isPrivateWithinAmbient(node) {
72579             return (ts.hasEffectiveModifier(node, 8 /* Private */) || ts.isPrivateIdentifierPropertyDeclaration(node)) && !!(node.flags & 8388608 /* Ambient */);
72580         }
72581         function getEffectiveDeclarationFlags(n, flagsToCheck) {
72582             var flags = ts.getCombinedModifierFlags(n);
72583             // children of classes (even ambient classes) should not be marked as ambient or export
72584             // because those flags have no useful semantics there.
72585             if (n.parent.kind !== 253 /* InterfaceDeclaration */ &&
72586                 n.parent.kind !== 252 /* ClassDeclaration */ &&
72587                 n.parent.kind !== 221 /* ClassExpression */ &&
72588                 n.flags & 8388608 /* Ambient */) {
72589                 if (!(flags & 2 /* Ambient */) && !(ts.isModuleBlock(n.parent) && ts.isModuleDeclaration(n.parent.parent) && ts.isGlobalScopeAugmentation(n.parent.parent))) {
72590                     // It is nested in an ambient context, which means it is automatically exported
72591                     flags |= 1 /* Export */;
72592                 }
72593                 flags |= 2 /* Ambient */;
72594             }
72595             return flags & flagsToCheck;
72596         }
72597         function checkFunctionOrConstructorSymbol(symbol) {
72598             if (!produceDiagnostics) {
72599                 return;
72600             }
72601             function getCanonicalOverload(overloads, implementation) {
72602                 // Consider the canonical set of flags to be the flags of the bodyDeclaration or the first declaration
72603                 // Error on all deviations from this canonical set of flags
72604                 // The caveat is that if some overloads are defined in lib.d.ts, we don't want to
72605                 // report the errors on those. To achieve this, we will say that the implementation is
72606                 // the canonical signature only if it is in the same container as the first overload
72607                 var implementationSharesContainerWithFirstOverload = implementation !== undefined && implementation.parent === overloads[0].parent;
72608                 return implementationSharesContainerWithFirstOverload ? implementation : overloads[0];
72609             }
72610             function checkFlagAgreementBetweenOverloads(overloads, implementation, flagsToCheck, someOverloadFlags, allOverloadFlags) {
72611                 // Error if some overloads have a flag that is not shared by all overloads. To find the
72612                 // deviations, we XOR someOverloadFlags with allOverloadFlags
72613                 var someButNotAllOverloadFlags = someOverloadFlags ^ allOverloadFlags;
72614                 if (someButNotAllOverloadFlags !== 0) {
72615                     var canonicalFlags_1 = getEffectiveDeclarationFlags(getCanonicalOverload(overloads, implementation), flagsToCheck);
72616                     ts.forEach(overloads, function (o) {
72617                         var deviation = getEffectiveDeclarationFlags(o, flagsToCheck) ^ canonicalFlags_1;
72618                         if (deviation & 1 /* Export */) {
72619                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_exported_or_non_exported);
72620                         }
72621                         else if (deviation & 2 /* Ambient */) {
72622                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_ambient_or_non_ambient);
72623                         }
72624                         else if (deviation & (8 /* Private */ | 16 /* Protected */)) {
72625                             error(ts.getNameOfDeclaration(o) || o, ts.Diagnostics.Overload_signatures_must_all_be_public_private_or_protected);
72626                         }
72627                         else if (deviation & 128 /* Abstract */) {
72628                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_abstract_or_non_abstract);
72629                         }
72630                     });
72631                 }
72632             }
72633             function checkQuestionTokenAgreementBetweenOverloads(overloads, implementation, someHaveQuestionToken, allHaveQuestionToken) {
72634                 if (someHaveQuestionToken !== allHaveQuestionToken) {
72635                     var canonicalHasQuestionToken_1 = ts.hasQuestionToken(getCanonicalOverload(overloads, implementation));
72636                     ts.forEach(overloads, function (o) {
72637                         var deviation = ts.hasQuestionToken(o) !== canonicalHasQuestionToken_1;
72638                         if (deviation) {
72639                             error(ts.getNameOfDeclaration(o), ts.Diagnostics.Overload_signatures_must_all_be_optional_or_required);
72640                         }
72641                     });
72642                 }
72643             }
72644             var flagsToCheck = 1 /* Export */ | 2 /* Ambient */ | 8 /* Private */ | 16 /* Protected */ | 128 /* Abstract */;
72645             var someNodeFlags = 0 /* None */;
72646             var allNodeFlags = flagsToCheck;
72647             var someHaveQuestionToken = false;
72648             var allHaveQuestionToken = true;
72649             var hasOverloads = false;
72650             var bodyDeclaration;
72651             var lastSeenNonAmbientDeclaration;
72652             var previousDeclaration;
72653             var declarations = symbol.declarations;
72654             var isConstructor = (symbol.flags & 16384 /* Constructor */) !== 0;
72655             function reportImplementationExpectedError(node) {
72656                 if (node.name && ts.nodeIsMissing(node.name)) {
72657                     return;
72658                 }
72659                 var seen = false;
72660                 var subsequentNode = ts.forEachChild(node.parent, function (c) {
72661                     if (seen) {
72662                         return c;
72663                     }
72664                     else {
72665                         seen = c === node;
72666                     }
72667                 });
72668                 // We may be here because of some extra nodes between overloads that could not be parsed into a valid node.
72669                 // In this case the subsequent node is not really consecutive (.pos !== node.end), and we must ignore it here.
72670                 if (subsequentNode && subsequentNode.pos === node.end) {
72671                     if (subsequentNode.kind === node.kind) {
72672                         var errorNode_1 = subsequentNode.name || subsequentNode;
72673                         var subsequentName = subsequentNode.name;
72674                         if (node.name && subsequentName && (
72675                         // both are private identifiers
72676                         ts.isPrivateIdentifier(node.name) && ts.isPrivateIdentifier(subsequentName) && node.name.escapedText === subsequentName.escapedText ||
72677                             // Both are computed property names
72678                             // TODO: GH#17345: These are methods, so handle computed name case. (`Always allowing computed property names is *not* the correct behavior!)
72679                             ts.isComputedPropertyName(node.name) && ts.isComputedPropertyName(subsequentName) ||
72680                             // Both are literal property names that are the same.
72681                             ts.isPropertyNameLiteral(node.name) && ts.isPropertyNameLiteral(subsequentName) &&
72682                                 ts.getEscapedTextOfIdentifierOrLiteral(node.name) === ts.getEscapedTextOfIdentifierOrLiteral(subsequentName))) {
72683                             var reportError = (node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */) &&
72684                                 ts.hasSyntacticModifier(node, 32 /* Static */) !== ts.hasSyntacticModifier(subsequentNode, 32 /* Static */);
72685                             // we can get here in two cases
72686                             // 1. mixed static and instance class members
72687                             // 2. something with the same name was defined before the set of overloads that prevents them from merging
72688                             // here we'll report error only for the first case since for second we should already report error in binder
72689                             if (reportError) {
72690                                 var diagnostic = ts.hasSyntacticModifier(node, 32 /* Static */) ? ts.Diagnostics.Function_overload_must_be_static : ts.Diagnostics.Function_overload_must_not_be_static;
72691                                 error(errorNode_1, diagnostic);
72692                             }
72693                             return;
72694                         }
72695                         if (ts.nodeIsPresent(subsequentNode.body)) {
72696                             error(errorNode_1, ts.Diagnostics.Function_implementation_name_must_be_0, ts.declarationNameToString(node.name));
72697                             return;
72698                         }
72699                     }
72700                 }
72701                 var errorNode = node.name || node;
72702                 if (isConstructor) {
72703                     error(errorNode, ts.Diagnostics.Constructor_implementation_is_missing);
72704                 }
72705                 else {
72706                     // Report different errors regarding non-consecutive blocks of declarations depending on whether
72707                     // the node in question is abstract.
72708                     if (ts.hasSyntacticModifier(node, 128 /* Abstract */)) {
72709                         error(errorNode, ts.Diagnostics.All_declarations_of_an_abstract_method_must_be_consecutive);
72710                     }
72711                     else {
72712                         error(errorNode, ts.Diagnostics.Function_implementation_is_missing_or_not_immediately_following_the_declaration);
72713                     }
72714                 }
72715             }
72716             var duplicateFunctionDeclaration = false;
72717             var multipleConstructorImplementation = false;
72718             var hasNonAmbientClass = false;
72719             var functionDeclarations = [];
72720             for (var _i = 0, declarations_4 = declarations; _i < declarations_4.length; _i++) {
72721                 var current = declarations_4[_i];
72722                 var node = current;
72723                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
72724                 var inAmbientContextOrInterface = node.parent && (node.parent.kind === 253 /* InterfaceDeclaration */ || node.parent.kind === 177 /* TypeLiteral */) || inAmbientContext;
72725                 if (inAmbientContextOrInterface) {
72726                     // check if declarations are consecutive only if they are non-ambient
72727                     // 1. ambient declarations can be interleaved
72728                     // i.e. this is legal
72729                     //     declare function foo();
72730                     //     declare function bar();
72731                     //     declare function foo();
72732                     // 2. mixing ambient and non-ambient declarations is a separate error that will be reported - do not want to report an extra one
72733                     previousDeclaration = undefined;
72734                 }
72735                 if ((node.kind === 252 /* ClassDeclaration */ || node.kind === 221 /* ClassExpression */) && !inAmbientContext) {
72736                     hasNonAmbientClass = true;
72737                 }
72738                 if (node.kind === 251 /* FunctionDeclaration */ || node.kind === 165 /* MethodDeclaration */ || node.kind === 164 /* MethodSignature */ || node.kind === 166 /* Constructor */) {
72739                     functionDeclarations.push(node);
72740                     var currentNodeFlags = getEffectiveDeclarationFlags(node, flagsToCheck);
72741                     someNodeFlags |= currentNodeFlags;
72742                     allNodeFlags &= currentNodeFlags;
72743                     someHaveQuestionToken = someHaveQuestionToken || ts.hasQuestionToken(node);
72744                     allHaveQuestionToken = allHaveQuestionToken && ts.hasQuestionToken(node);
72745                     var bodyIsPresent = ts.nodeIsPresent(node.body);
72746                     if (bodyIsPresent && bodyDeclaration) {
72747                         if (isConstructor) {
72748                             multipleConstructorImplementation = true;
72749                         }
72750                         else {
72751                             duplicateFunctionDeclaration = true;
72752                         }
72753                     }
72754                     else if ((previousDeclaration === null || previousDeclaration === void 0 ? void 0 : previousDeclaration.parent) === node.parent && previousDeclaration.end !== node.pos) {
72755                         reportImplementationExpectedError(previousDeclaration);
72756                     }
72757                     if (bodyIsPresent) {
72758                         if (!bodyDeclaration) {
72759                             bodyDeclaration = node;
72760                         }
72761                     }
72762                     else {
72763                         hasOverloads = true;
72764                     }
72765                     previousDeclaration = node;
72766                     if (!inAmbientContextOrInterface) {
72767                         lastSeenNonAmbientDeclaration = node;
72768                     }
72769                 }
72770             }
72771             if (multipleConstructorImplementation) {
72772                 ts.forEach(functionDeclarations, function (declaration) {
72773                     error(declaration, ts.Diagnostics.Multiple_constructor_implementations_are_not_allowed);
72774                 });
72775             }
72776             if (duplicateFunctionDeclaration) {
72777                 ts.forEach(functionDeclarations, function (declaration) {
72778                     error(ts.getNameOfDeclaration(declaration) || declaration, ts.Diagnostics.Duplicate_function_implementation);
72779                 });
72780             }
72781             if (hasNonAmbientClass && !isConstructor && symbol.flags & 16 /* Function */) {
72782                 // A non-ambient class cannot be an implementation for a non-constructor function/class merge
72783                 // TODO: The below just replicates our older error from when classes and functions were
72784                 // entirely unable to merge - a more helpful message like "Class declaration cannot implement overload list"
72785                 // might be warranted. :shrug:
72786                 ts.forEach(declarations, function (declaration) {
72787                     addDuplicateDeclarationError(declaration, ts.Diagnostics.Duplicate_identifier_0, ts.symbolName(symbol), declarations);
72788                 });
72789             }
72790             // Abstract methods can't have an implementation -- in particular, they don't need one.
72791             if (lastSeenNonAmbientDeclaration && !lastSeenNonAmbientDeclaration.body &&
72792                 !ts.hasSyntacticModifier(lastSeenNonAmbientDeclaration, 128 /* Abstract */) && !lastSeenNonAmbientDeclaration.questionToken) {
72793                 reportImplementationExpectedError(lastSeenNonAmbientDeclaration);
72794             }
72795             if (hasOverloads) {
72796                 checkFlagAgreementBetweenOverloads(declarations, bodyDeclaration, flagsToCheck, someNodeFlags, allNodeFlags);
72797                 checkQuestionTokenAgreementBetweenOverloads(declarations, bodyDeclaration, someHaveQuestionToken, allHaveQuestionToken);
72798                 if (bodyDeclaration) {
72799                     var signatures = getSignaturesOfSymbol(symbol);
72800                     var bodySignature = getSignatureFromDeclaration(bodyDeclaration);
72801                     for (var _a = 0, signatures_10 = signatures; _a < signatures_10.length; _a++) {
72802                         var signature = signatures_10[_a];
72803                         if (!isImplementationCompatibleWithOverload(bodySignature, signature)) {
72804                             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));
72805                             break;
72806                         }
72807                     }
72808                 }
72809             }
72810         }
72811         function checkExportsOnMergedDeclarations(node) {
72812             if (!produceDiagnostics) {
72813                 return;
72814             }
72815             // if localSymbol is defined on node then node itself is exported - check is required
72816             var symbol = node.localSymbol;
72817             if (!symbol) {
72818                 // local symbol is undefined => this declaration is non-exported.
72819                 // however symbol might contain other declarations that are exported
72820                 symbol = getSymbolOfNode(node);
72821                 if (!symbol.exportSymbol) {
72822                     // this is a pure local symbol (all declarations are non-exported) - no need to check anything
72823                     return;
72824                 }
72825             }
72826             // run the check only for the first declaration in the list
72827             if (ts.getDeclarationOfKind(symbol, node.kind) !== node) {
72828                 return;
72829             }
72830             var exportedDeclarationSpaces = 0 /* None */;
72831             var nonExportedDeclarationSpaces = 0 /* None */;
72832             var defaultExportedDeclarationSpaces = 0 /* None */;
72833             for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
72834                 var d = _a[_i];
72835                 var declarationSpaces = getDeclarationSpaces(d);
72836                 var effectiveDeclarationFlags = getEffectiveDeclarationFlags(d, 1 /* Export */ | 512 /* Default */);
72837                 if (effectiveDeclarationFlags & 1 /* Export */) {
72838                     if (effectiveDeclarationFlags & 512 /* Default */) {
72839                         defaultExportedDeclarationSpaces |= declarationSpaces;
72840                     }
72841                     else {
72842                         exportedDeclarationSpaces |= declarationSpaces;
72843                     }
72844                 }
72845                 else {
72846                     nonExportedDeclarationSpaces |= declarationSpaces;
72847                 }
72848             }
72849             // Spaces for anything not declared a 'default export'.
72850             var nonDefaultExportedDeclarationSpaces = exportedDeclarationSpaces | nonExportedDeclarationSpaces;
72851             var commonDeclarationSpacesForExportsAndLocals = exportedDeclarationSpaces & nonExportedDeclarationSpaces;
72852             var commonDeclarationSpacesForDefaultAndNonDefault = defaultExportedDeclarationSpaces & nonDefaultExportedDeclarationSpaces;
72853             if (commonDeclarationSpacesForExportsAndLocals || commonDeclarationSpacesForDefaultAndNonDefault) {
72854                 // declaration spaces for exported and non-exported declarations intersect
72855                 for (var _b = 0, _c = symbol.declarations; _b < _c.length; _b++) {
72856                     var d = _c[_b];
72857                     var declarationSpaces = getDeclarationSpaces(d);
72858                     var name = ts.getNameOfDeclaration(d);
72859                     // Only error on the declarations that contributed to the intersecting spaces.
72860                     if (declarationSpaces & commonDeclarationSpacesForDefaultAndNonDefault) {
72861                         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));
72862                     }
72863                     else if (declarationSpaces & commonDeclarationSpacesForExportsAndLocals) {
72864                         error(name, ts.Diagnostics.Individual_declarations_in_merged_declaration_0_must_be_all_exported_or_all_local, ts.declarationNameToString(name));
72865                     }
72866                 }
72867             }
72868             function getDeclarationSpaces(decl) {
72869                 var d = decl;
72870                 switch (d.kind) {
72871                     case 253 /* InterfaceDeclaration */:
72872                     case 254 /* TypeAliasDeclaration */:
72873                     // A jsdoc typedef and callback are, by definition, type aliases.
72874                     // falls through
72875                     case 331 /* JSDocTypedefTag */:
72876                     case 324 /* JSDocCallbackTag */:
72877                     case 325 /* JSDocEnumTag */:
72878                         return 2 /* ExportType */;
72879                     case 256 /* ModuleDeclaration */:
72880                         return ts.isAmbientModule(d) || ts.getModuleInstanceState(d) !== 0 /* NonInstantiated */
72881                             ? 4 /* ExportNamespace */ | 1 /* ExportValue */
72882                             : 4 /* ExportNamespace */;
72883                     case 252 /* ClassDeclaration */:
72884                     case 255 /* EnumDeclaration */:
72885                     case 291 /* EnumMember */:
72886                         return 2 /* ExportType */ | 1 /* ExportValue */;
72887                     case 297 /* SourceFile */:
72888                         return 2 /* ExportType */ | 1 /* ExportValue */ | 4 /* ExportNamespace */;
72889                     case 266 /* ExportAssignment */:
72890                         // Export assigned entity name expressions act as aliases and should fall through, otherwise they export values
72891                         if (!ts.isEntityNameExpression(d.expression)) {
72892                             return 1 /* ExportValue */;
72893                         }
72894                         d = d.expression;
72895                     // The below options all declare an Alias, which is allowed to merge with other values within the importing module.
72896                     // falls through
72897                     case 260 /* ImportEqualsDeclaration */:
72898                     case 263 /* NamespaceImport */:
72899                     case 262 /* ImportClause */:
72900                         var result_12 = 0 /* None */;
72901                         var target = resolveAlias(getSymbolOfNode(d));
72902                         ts.forEach(target.declarations, function (d) { result_12 |= getDeclarationSpaces(d); });
72903                         return result_12;
72904                     case 249 /* VariableDeclaration */:
72905                     case 198 /* BindingElement */:
72906                     case 251 /* FunctionDeclaration */:
72907                     case 265 /* ImportSpecifier */: // https://github.com/Microsoft/TypeScript/pull/7591
72908                     case 78 /* Identifier */: // https://github.com/microsoft/TypeScript/issues/36098
72909                         // Identifiers are used as declarations of assignment declarations whose parents may be
72910                         // SyntaxKind.CallExpression - `Object.defineProperty(thing, "aField", {value: 42});`
72911                         // SyntaxKind.ElementAccessExpression - `thing["aField"] = 42;` or `thing["aField"];` (with a doc comment on it)
72912                         // or SyntaxKind.PropertyAccessExpression - `thing.aField = 42;`
72913                         // all of which are pretty much always values, or at least imply a value meaning.
72914                         // It may be apprpriate to treat these as aliases in the future.
72915                         return 1 /* ExportValue */;
72916                     default:
72917                         return ts.Debug.failBadSyntaxKind(d);
72918                 }
72919             }
72920         }
72921         function getAwaitedTypeOfPromise(type, errorNode, diagnosticMessage, arg0) {
72922             var promisedType = getPromisedTypeOfPromise(type, errorNode);
72923             return promisedType && getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
72924         }
72925         /**
72926          * Gets the "promised type" of a promise.
72927          * @param type The type of the promise.
72928          * @remarks The "promised type" of a type is the type of the "value" parameter of the "onfulfilled" callback.
72929          */
72930         function getPromisedTypeOfPromise(type, errorNode) {
72931             //
72932             //  { // type
72933             //      then( // thenFunction
72934             //          onfulfilled: ( // onfulfilledParameterType
72935             //              value: T // valueParameterType
72936             //          ) => any
72937             //      ): any;
72938             //  }
72939             //
72940             if (isTypeAny(type)) {
72941                 return undefined;
72942             }
72943             var typeAsPromise = type;
72944             if (typeAsPromise.promisedTypeOfPromise) {
72945                 return typeAsPromise.promisedTypeOfPromise;
72946             }
72947             if (isReferenceToType(type, getGlobalPromiseType(/*reportErrors*/ false))) {
72948                 return typeAsPromise.promisedTypeOfPromise = getTypeArguments(type)[0];
72949             }
72950             var thenFunction = getTypeOfPropertyOfType(type, "then"); // TODO: GH#18217
72951             if (isTypeAny(thenFunction)) {
72952                 return undefined;
72953             }
72954             var thenSignatures = thenFunction ? getSignaturesOfType(thenFunction, 0 /* Call */) : ts.emptyArray;
72955             if (thenSignatures.length === 0) {
72956                 if (errorNode) {
72957                     error(errorNode, ts.Diagnostics.A_promise_must_have_a_then_method);
72958                 }
72959                 return undefined;
72960             }
72961             var onfulfilledParameterType = getTypeWithFacts(getUnionType(ts.map(thenSignatures, getTypeOfFirstParameterOfSignature)), 2097152 /* NEUndefinedOrNull */);
72962             if (isTypeAny(onfulfilledParameterType)) {
72963                 return undefined;
72964             }
72965             var onfulfilledParameterSignatures = getSignaturesOfType(onfulfilledParameterType, 0 /* Call */);
72966             if (onfulfilledParameterSignatures.length === 0) {
72967                 if (errorNode) {
72968                     error(errorNode, ts.Diagnostics.The_first_parameter_of_the_then_method_of_a_promise_must_be_a_callback);
72969                 }
72970                 return undefined;
72971             }
72972             return typeAsPromise.promisedTypeOfPromise = getUnionType(ts.map(onfulfilledParameterSignatures, getTypeOfFirstParameterOfSignature), 2 /* Subtype */);
72973         }
72974         /**
72975          * Gets the "awaited type" of a type.
72976          * @param type The type to await.
72977          * @remarks The "awaited type" of an expression is its "promised type" if the expression is a
72978          * Promise-like type; otherwise, it is the type of the expression. This is used to reflect
72979          * The runtime behavior of the `await` keyword.
72980          */
72981         function checkAwaitedType(type, errorNode, diagnosticMessage, arg0) {
72982             var awaitedType = getAwaitedType(type, errorNode, diagnosticMessage, arg0);
72983             return awaitedType || errorType;
72984         }
72985         /**
72986          * Determines whether a type has a callable `then` member.
72987          */
72988         function isThenableType(type) {
72989             var thenFunction = getTypeOfPropertyOfType(type, "then");
72990             return !!thenFunction && getSignaturesOfType(getTypeWithFacts(thenFunction, 2097152 /* NEUndefinedOrNull */), 0 /* Call */).length > 0;
72991         }
72992         /**
72993          * Gets the "awaited type" of a type.
72994          *
72995          * The "awaited type" of an expression is its "promised type" if the expression is a
72996          * Promise-like type; otherwise, it is the type of the expression. If the "promised
72997          * type" is itself a Promise-like, the "promised type" is recursively unwrapped until a
72998          * non-promise type is found.
72999          *
73000          * This is used to reflect the runtime behavior of the `await` keyword.
73001          */
73002         function getAwaitedType(type, errorNode, diagnosticMessage, arg0) {
73003             if (isTypeAny(type)) {
73004                 return type;
73005             }
73006             var typeAsAwaitable = type;
73007             if (typeAsAwaitable.awaitedTypeOfType) {
73008                 return typeAsAwaitable.awaitedTypeOfType;
73009             }
73010             // For a union, get a union of the awaited types of each constituent.
73011             //
73012             return typeAsAwaitable.awaitedTypeOfType =
73013                 mapType(type, errorNode ? function (constituentType) { return getAwaitedTypeWorker(constituentType, errorNode, diagnosticMessage, arg0); } : getAwaitedTypeWorker);
73014         }
73015         function getAwaitedTypeWorker(type, errorNode, diagnosticMessage, arg0) {
73016             var typeAsAwaitable = type;
73017             if (typeAsAwaitable.awaitedTypeOfType) {
73018                 return typeAsAwaitable.awaitedTypeOfType;
73019             }
73020             var promisedType = getPromisedTypeOfPromise(type);
73021             if (promisedType) {
73022                 if (type.id === promisedType.id || awaitedTypeStack.lastIndexOf(promisedType.id) >= 0) {
73023                     // Verify that we don't have a bad actor in the form of a promise whose
73024                     // promised type is the same as the promise type, or a mutually recursive
73025                     // promise. If so, we return undefined as we cannot guess the shape. If this
73026                     // were the actual case in the JavaScript, this Promise would never resolve.
73027                     //
73028                     // An example of a bad actor with a singly-recursive promise type might
73029                     // be:
73030                     //
73031                     //  interface BadPromise {
73032                     //      then(
73033                     //          onfulfilled: (value: BadPromise) => any,
73034                     //          onrejected: (error: any) => any): BadPromise;
73035                     //  }
73036                     //
73037                     // The above interface will pass the PromiseLike check, and return a
73038                     // promised type of `BadPromise`. Since this is a self reference, we
73039                     // don't want to keep recursing ad infinitum.
73040                     //
73041                     // An example of a bad actor in the form of a mutually-recursive
73042                     // promise type might be:
73043                     //
73044                     //  interface BadPromiseA {
73045                     //      then(
73046                     //          onfulfilled: (value: BadPromiseB) => any,
73047                     //          onrejected: (error: any) => any): BadPromiseB;
73048                     //  }
73049                     //
73050                     //  interface BadPromiseB {
73051                     //      then(
73052                     //          onfulfilled: (value: BadPromiseA) => any,
73053                     //          onrejected: (error: any) => any): BadPromiseA;
73054                     //  }
73055                     //
73056                     if (errorNode) {
73057                         error(errorNode, ts.Diagnostics.Type_is_referenced_directly_or_indirectly_in_the_fulfillment_callback_of_its_own_then_method);
73058                     }
73059                     return undefined;
73060                 }
73061                 // Keep track of the type we're about to unwrap to avoid bad recursive promise types.
73062                 // See the comments above for more information.
73063                 awaitedTypeStack.push(type.id);
73064                 var awaitedType = getAwaitedType(promisedType, errorNode, diagnosticMessage, arg0);
73065                 awaitedTypeStack.pop();
73066                 if (!awaitedType) {
73067                     return undefined;
73068                 }
73069                 return typeAsAwaitable.awaitedTypeOfType = awaitedType;
73070             }
73071             // The type was not a promise, so it could not be unwrapped any further.
73072             // As long as the type does not have a callable "then" property, it is
73073             // safe to return the type; otherwise, an error is reported and we return
73074             // undefined.
73075             //
73076             // An example of a non-promise "thenable" might be:
73077             //
73078             //  await { then(): void {} }
73079             //
73080             // The "thenable" does not match the minimal definition for a promise. When
73081             // a Promise/A+-compatible or ES6 promise tries to adopt this value, the promise
73082             // will never settle. We treat this as an error to help flag an early indicator
73083             // of a runtime problem. If the user wants to return this value from an async
73084             // function, they would need to wrap it in some other value. If they want it to
73085             // be treated as a promise, they can cast to <any>.
73086             if (isThenableType(type)) {
73087                 if (errorNode) {
73088                     if (!diagnosticMessage)
73089                         return ts.Debug.fail();
73090                     error(errorNode, diagnosticMessage, arg0);
73091                 }
73092                 return undefined;
73093             }
73094             return typeAsAwaitable.awaitedTypeOfType = type;
73095         }
73096         /**
73097          * Checks the return type of an async function to ensure it is a compatible
73098          * Promise implementation.
73099          *
73100          * This checks that an async function has a valid Promise-compatible return type.
73101          * An async function has a valid Promise-compatible return type if the resolved value
73102          * of the return type has a construct signature that takes in an `initializer` function
73103          * that in turn supplies a `resolve` function as one of its arguments and results in an
73104          * object with a callable `then` signature.
73105          *
73106          * @param node The signature to check
73107          */
73108         function checkAsyncFunctionReturnType(node, returnTypeNode) {
73109             // As part of our emit for an async function, we will need to emit the entity name of
73110             // the return type annotation as an expression. To meet the necessary runtime semantics
73111             // for __awaiter, we must also check that the type of the declaration (e.g. the static
73112             // side or "constructor" of the promise type) is compatible `PromiseConstructorLike`.
73113             //
73114             // An example might be (from lib.es6.d.ts):
73115             //
73116             //  interface Promise<T> { ... }
73117             //  interface PromiseConstructor {
73118             //      new <T>(...): Promise<T>;
73119             //  }
73120             //  declare var Promise: PromiseConstructor;
73121             //
73122             // When an async function declares a return type annotation of `Promise<T>`, we
73123             // need to get the type of the `Promise` variable declaration above, which would
73124             // be `PromiseConstructor`.
73125             //
73126             // The same case applies to a class:
73127             //
73128             //  declare class Promise<T> {
73129             //      constructor(...);
73130             //      then<U>(...): Promise<U>;
73131             //  }
73132             //
73133             var returnType = getTypeFromTypeNode(returnTypeNode);
73134             if (languageVersion >= 2 /* ES2015 */) {
73135                 if (returnType === errorType) {
73136                     return;
73137                 }
73138                 var globalPromiseType = getGlobalPromiseType(/*reportErrors*/ true);
73139                 if (globalPromiseType !== emptyGenericType && !isReferenceToType(returnType, globalPromiseType)) {
73140                     // The promise type was not a valid type reference to the global promise type, so we
73141                     // report an error and return the unknown type.
73142                     error(returnTypeNode, ts.Diagnostics.The_return_type_of_an_async_function_or_method_must_be_the_global_Promise_T_type_Did_you_mean_to_write_Promise_0, typeToString(getAwaitedType(returnType) || voidType));
73143                     return;
73144                 }
73145             }
73146             else {
73147                 // Always mark the type node as referenced if it points to a value
73148                 markTypeNodeAsReferenced(returnTypeNode);
73149                 if (returnType === errorType) {
73150                     return;
73151                 }
73152                 var promiseConstructorName = ts.getEntityNameFromTypeNode(returnTypeNode);
73153                 if (promiseConstructorName === undefined) {
73154                     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));
73155                     return;
73156                 }
73157                 var promiseConstructorSymbol = resolveEntityName(promiseConstructorName, 111551 /* Value */, /*ignoreErrors*/ true);
73158                 var promiseConstructorType = promiseConstructorSymbol ? getTypeOfSymbol(promiseConstructorSymbol) : errorType;
73159                 if (promiseConstructorType === errorType) {
73160                     if (promiseConstructorName.kind === 78 /* Identifier */ && promiseConstructorName.escapedText === "Promise" && getTargetType(returnType) === getGlobalPromiseType(/*reportErrors*/ false)) {
73161                         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);
73162                     }
73163                     else {
73164                         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));
73165                     }
73166                     return;
73167                 }
73168                 var globalPromiseConstructorLikeType = getGlobalPromiseConstructorLikeType(/*reportErrors*/ true);
73169                 if (globalPromiseConstructorLikeType === emptyObjectType) {
73170                     // If we couldn't resolve the global PromiseConstructorLike type we cannot verify
73171                     // compatibility with __awaiter.
73172                     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));
73173                     return;
73174                 }
73175                 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)) {
73176                     return;
73177                 }
73178                 // Verify there is no local declaration that could collide with the promise constructor.
73179                 var rootName = promiseConstructorName && ts.getFirstIdentifier(promiseConstructorName);
73180                 var collidingSymbol = getSymbol(node.locals, rootName.escapedText, 111551 /* Value */);
73181                 if (collidingSymbol) {
73182                     error(collidingSymbol.valueDeclaration, ts.Diagnostics.Duplicate_identifier_0_Compiler_uses_declaration_1_to_support_async_functions, ts.idText(rootName), ts.entityNameToString(promiseConstructorName));
73183                     return;
73184                 }
73185             }
73186             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);
73187         }
73188         /** Check a decorator */
73189         function checkDecorator(node) {
73190             var signature = getResolvedSignature(node);
73191             checkDeprecatedSignature(signature, node);
73192             var returnType = getReturnTypeOfSignature(signature);
73193             if (returnType.flags & 1 /* Any */) {
73194                 return;
73195             }
73196             var expectedReturnType;
73197             var headMessage = getDiagnosticHeadMessageForDecoratorResolution(node);
73198             var errorInfo;
73199             switch (node.parent.kind) {
73200                 case 252 /* ClassDeclaration */:
73201                     var classSymbol = getSymbolOfNode(node.parent);
73202                     var classConstructorType = getTypeOfSymbol(classSymbol);
73203                     expectedReturnType = getUnionType([classConstructorType, voidType]);
73204                     break;
73205                 case 160 /* Parameter */:
73206                     expectedReturnType = voidType;
73207                     errorInfo = ts.chainDiagnosticMessages(
73208                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_parameter_decorator_function_must_be_either_void_or_any);
73209                     break;
73210                 case 163 /* PropertyDeclaration */:
73211                     expectedReturnType = voidType;
73212                     errorInfo = ts.chainDiagnosticMessages(
73213                     /*details*/ undefined, ts.Diagnostics.The_return_type_of_a_property_decorator_function_must_be_either_void_or_any);
73214                     break;
73215                 case 165 /* MethodDeclaration */:
73216                 case 167 /* GetAccessor */:
73217                 case 168 /* SetAccessor */:
73218                     var methodType = getTypeOfNode(node.parent);
73219                     var descriptorType = createTypedPropertyDescriptorType(methodType);
73220                     expectedReturnType = getUnionType([descriptorType, voidType]);
73221                     break;
73222                 default:
73223                     return ts.Debug.fail();
73224             }
73225             checkTypeAssignableTo(returnType, expectedReturnType, node, headMessage, function () { return errorInfo; });
73226         }
73227         /**
73228          * If a TypeNode can be resolved to a value symbol imported from an external module, it is
73229          * marked as referenced to prevent import elision.
73230          */
73231         function markTypeNodeAsReferenced(node) {
73232             markEntityNameOrEntityExpressionAsReference(node && ts.getEntityNameFromTypeNode(node));
73233         }
73234         function markEntityNameOrEntityExpressionAsReference(typeName) {
73235             if (!typeName)
73236                 return;
73237             var rootName = ts.getFirstIdentifier(typeName);
73238             var meaning = (typeName.kind === 78 /* Identifier */ ? 788968 /* Type */ : 1920 /* Namespace */) | 2097152 /* Alias */;
73239             var rootSymbol = resolveName(rootName, rootName.escapedText, meaning, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isRefernce*/ true);
73240             if (rootSymbol
73241                 && rootSymbol.flags & 2097152 /* Alias */
73242                 && symbolIsValue(rootSymbol)
73243                 && !isConstEnumOrConstEnumOnlyModule(resolveAlias(rootSymbol))
73244                 && !getTypeOnlyAliasDeclaration(rootSymbol)) {
73245                 markAliasSymbolAsReferenced(rootSymbol);
73246             }
73247         }
73248         /**
73249          * This function marks the type used for metadata decorator as referenced if it is import
73250          * from external module.
73251          * This is different from markTypeNodeAsReferenced because it tries to simplify type nodes in
73252          * union and intersection type
73253          * @param node
73254          */
73255         function markDecoratorMedataDataTypeNodeAsReferenced(node) {
73256             var entityName = getEntityNameForDecoratorMetadata(node);
73257             if (entityName && ts.isEntityName(entityName)) {
73258                 markEntityNameOrEntityExpressionAsReference(entityName);
73259             }
73260         }
73261         function getEntityNameForDecoratorMetadata(node) {
73262             if (node) {
73263                 switch (node.kind) {
73264                     case 183 /* IntersectionType */:
73265                     case 182 /* UnionType */:
73266                         return getEntityNameForDecoratorMetadataFromTypeList(node.types);
73267                     case 184 /* ConditionalType */:
73268                         return getEntityNameForDecoratorMetadataFromTypeList([node.trueType, node.falseType]);
73269                     case 186 /* ParenthesizedType */:
73270                     case 192 /* NamedTupleMember */:
73271                         return getEntityNameForDecoratorMetadata(node.type);
73272                     case 173 /* TypeReference */:
73273                         return node.typeName;
73274                 }
73275             }
73276         }
73277         function getEntityNameForDecoratorMetadataFromTypeList(types) {
73278             var commonEntityName;
73279             for (var _i = 0, types_21 = types; _i < types_21.length; _i++) {
73280                 var typeNode = types_21[_i];
73281                 while (typeNode.kind === 186 /* ParenthesizedType */ || typeNode.kind === 192 /* NamedTupleMember */) {
73282                     typeNode = typeNode.type; // Skip parens if need be
73283                 }
73284                 if (typeNode.kind === 141 /* NeverKeyword */) {
73285                     continue; // Always elide `never` from the union/intersection if possible
73286                 }
73287                 if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) {
73288                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
73289                 }
73290                 var individualEntityName = getEntityNameForDecoratorMetadata(typeNode);
73291                 if (!individualEntityName) {
73292                     // Individual is something like string number
73293                     // So it would be serialized to either that type or object
73294                     // Safe to return here
73295                     return undefined;
73296                 }
73297                 if (commonEntityName) {
73298                     // Note this is in sync with the transformation that happens for type node.
73299                     // Keep this in sync with serializeUnionOrIntersectionType
73300                     // Verify if they refer to same entity and is identifier
73301                     // return undefined if they dont match because we would emit object
73302                     if (!ts.isIdentifier(commonEntityName) ||
73303                         !ts.isIdentifier(individualEntityName) ||
73304                         commonEntityName.escapedText !== individualEntityName.escapedText) {
73305                         return undefined;
73306                     }
73307                 }
73308                 else {
73309                     commonEntityName = individualEntityName;
73310                 }
73311             }
73312             return commonEntityName;
73313         }
73314         function getParameterTypeNodeForDecoratorCheck(node) {
73315             var typeNode = ts.getEffectiveTypeAnnotationNode(node);
73316             return ts.isRestParameter(node) ? ts.getRestParameterElementType(typeNode) : typeNode;
73317         }
73318         /** Check the decorators of a node */
73319         function checkDecorators(node) {
73320             if (!node.decorators) {
73321                 return;
73322             }
73323             // skip this check for nodes that cannot have decorators. These should have already had an error reported by
73324             // checkGrammarDecorators.
73325             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
73326                 return;
73327             }
73328             if (!compilerOptions.experimentalDecorators) {
73329                 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);
73330             }
73331             var firstDecorator = node.decorators[0];
73332             checkExternalEmitHelpers(firstDecorator, 8 /* Decorate */);
73333             if (node.kind === 160 /* Parameter */) {
73334                 checkExternalEmitHelpers(firstDecorator, 32 /* Param */);
73335             }
73336             if (compilerOptions.emitDecoratorMetadata) {
73337                 checkExternalEmitHelpers(firstDecorator, 16 /* Metadata */);
73338                 // we only need to perform these checks if we are emitting serialized type metadata for the target of a decorator.
73339                 switch (node.kind) {
73340                     case 252 /* ClassDeclaration */:
73341                         var constructor = ts.getFirstConstructorWithBody(node);
73342                         if (constructor) {
73343                             for (var _i = 0, _a = constructor.parameters; _i < _a.length; _i++) {
73344                                 var parameter = _a[_i];
73345                                 markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
73346                             }
73347                         }
73348                         break;
73349                     case 167 /* GetAccessor */:
73350                     case 168 /* SetAccessor */:
73351                         var otherKind = node.kind === 167 /* GetAccessor */ ? 168 /* SetAccessor */ : 167 /* GetAccessor */;
73352                         var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(node), otherKind);
73353                         markDecoratorMedataDataTypeNodeAsReferenced(getAnnotatedAccessorTypeNode(node) || otherAccessor && getAnnotatedAccessorTypeNode(otherAccessor));
73354                         break;
73355                     case 165 /* MethodDeclaration */:
73356                         for (var _b = 0, _c = node.parameters; _b < _c.length; _b++) {
73357                             var parameter = _c[_b];
73358                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
73359                         }
73360                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveReturnTypeNode(node));
73361                         break;
73362                     case 163 /* PropertyDeclaration */:
73363                         markDecoratorMedataDataTypeNodeAsReferenced(ts.getEffectiveTypeAnnotationNode(node));
73364                         break;
73365                     case 160 /* Parameter */:
73366                         markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(node));
73367                         var containingSignature = node.parent;
73368                         for (var _d = 0, _e = containingSignature.parameters; _d < _e.length; _d++) {
73369                             var parameter = _e[_d];
73370                             markDecoratorMedataDataTypeNodeAsReferenced(getParameterTypeNodeForDecoratorCheck(parameter));
73371                         }
73372                         break;
73373                 }
73374             }
73375             ts.forEach(node.decorators, checkDecorator);
73376         }
73377         function checkFunctionDeclaration(node) {
73378             if (produceDiagnostics) {
73379                 checkFunctionOrMethodDeclaration(node);
73380                 checkGrammarForGenerator(node);
73381                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
73382                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
73383             }
73384         }
73385         function checkJSDocTypeAliasTag(node) {
73386             if (!node.typeExpression) {
73387                 // If the node had `@property` tags, `typeExpression` would have been set to the first property tag.
73388                 error(node.name, ts.Diagnostics.JSDoc_typedef_tag_should_either_have_a_type_annotation_or_be_followed_by_property_or_member_tags);
73389             }
73390             if (node.name) {
73391                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
73392             }
73393             checkSourceElement(node.typeExpression);
73394         }
73395         function checkJSDocTemplateTag(node) {
73396             checkSourceElement(node.constraint);
73397             for (var _i = 0, _a = node.typeParameters; _i < _a.length; _i++) {
73398                 var tp = _a[_i];
73399                 checkSourceElement(tp);
73400             }
73401         }
73402         function checkJSDocTypeTag(node) {
73403             checkSourceElement(node.typeExpression);
73404         }
73405         function checkJSDocParameterTag(node) {
73406             checkSourceElement(node.typeExpression);
73407             if (!ts.getParameterSymbolFromJSDoc(node)) {
73408                 var decl = ts.getHostSignatureFromJSDoc(node);
73409                 // don't issue an error for invalid hosts -- just functions --
73410                 // and give a better error message when the host function mentions `arguments`
73411                 // but the tag doesn't have an array type
73412                 if (decl) {
73413                     var i = ts.getJSDocTags(decl).filter(ts.isJSDocParameterTag).indexOf(node);
73414                     if (i > -1 && i < decl.parameters.length && ts.isBindingPattern(decl.parameters[i].name)) {
73415                         return;
73416                     }
73417                     if (!containsArgumentsReference(decl)) {
73418                         if (ts.isQualifiedName(node.name)) {
73419                             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));
73420                         }
73421                         else {
73422                             error(node.name, ts.Diagnostics.JSDoc_param_tag_has_name_0_but_there_is_no_parameter_with_that_name, ts.idText(node.name));
73423                         }
73424                     }
73425                     else if (ts.findLast(ts.getJSDocTags(decl), ts.isJSDocParameterTag) === node &&
73426                         node.typeExpression && node.typeExpression.type &&
73427                         !isArrayType(getTypeFromTypeNode(node.typeExpression.type))) {
73428                         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 === 157 /* QualifiedName */ ? node.name.right : node.name));
73429                     }
73430                 }
73431             }
73432         }
73433         function checkJSDocPropertyTag(node) {
73434             checkSourceElement(node.typeExpression);
73435         }
73436         function checkJSDocFunctionType(node) {
73437             if (produceDiagnostics && !node.type && !ts.isJSDocConstructSignature(node)) {
73438                 reportImplicitAny(node, anyType);
73439             }
73440             checkSignatureDeclaration(node);
73441         }
73442         function checkJSDocImplementsTag(node) {
73443             var classLike = ts.getEffectiveJSDocHost(node);
73444             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
73445                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
73446             }
73447         }
73448         function checkJSDocAugmentsTag(node) {
73449             var classLike = ts.getEffectiveJSDocHost(node);
73450             if (!classLike || !ts.isClassDeclaration(classLike) && !ts.isClassExpression(classLike)) {
73451                 error(classLike, ts.Diagnostics.JSDoc_0_is_not_attached_to_a_class, ts.idText(node.tagName));
73452                 return;
73453             }
73454             var augmentsTags = ts.getJSDocTags(classLike).filter(ts.isJSDocAugmentsTag);
73455             ts.Debug.assert(augmentsTags.length > 0);
73456             if (augmentsTags.length > 1) {
73457                 error(augmentsTags[1], ts.Diagnostics.Class_declarations_cannot_have_more_than_one_augments_or_extends_tag);
73458             }
73459             var name = getIdentifierFromEntityNameExpression(node.class.expression);
73460             var extend = ts.getClassExtendsHeritageElement(classLike);
73461             if (extend) {
73462                 var className = getIdentifierFromEntityNameExpression(extend.expression);
73463                 if (className && name.escapedText !== className.escapedText) {
73464                     error(name, ts.Diagnostics.JSDoc_0_1_does_not_match_the_extends_2_clause, ts.idText(node.tagName), ts.idText(name), ts.idText(className));
73465                 }
73466             }
73467         }
73468         function getIdentifierFromEntityNameExpression(node) {
73469             switch (node.kind) {
73470                 case 78 /* Identifier */:
73471                     return node;
73472                 case 201 /* PropertyAccessExpression */:
73473                     return node.name;
73474                 default:
73475                     return undefined;
73476             }
73477         }
73478         function checkFunctionOrMethodDeclaration(node) {
73479             checkDecorators(node);
73480             checkSignatureDeclaration(node);
73481             var functionFlags = ts.getFunctionFlags(node);
73482             // Do not use hasDynamicName here, because that returns false for well known symbols.
73483             // We want to perform checkComputedPropertyName for all computed properties, including
73484             // well known symbols.
73485             if (node.name && node.name.kind === 158 /* ComputedPropertyName */) {
73486                 // This check will account for methods in class/interface declarations,
73487                 // as well as accessors in classes/object literals
73488                 checkComputedPropertyName(node.name);
73489             }
73490             if (!hasNonBindableDynamicName(node)) {
73491                 // first we want to check the local symbol that contain this declaration
73492                 // - if node.localSymbol !== undefined - this is current declaration is exported and localSymbol points to the local symbol
73493                 // - if node.localSymbol === undefined - this node is non-exported so we can just pick the result of getSymbolOfNode
73494                 var symbol = getSymbolOfNode(node);
73495                 var localSymbol = node.localSymbol || symbol;
73496                 // Since the javascript won't do semantic analysis like typescript,
73497                 // if the javascript file comes before the typescript file and both contain same name functions,
73498                 // checkFunctionOrConstructorSymbol wouldn't be called if we didnt ignore javascript function.
73499                 var firstDeclaration = ts.find(localSymbol.declarations, 
73500                 // Get first non javascript function declaration
73501                 function (declaration) { return declaration.kind === node.kind && !(declaration.flags & 131072 /* JavaScriptFile */); });
73502                 // Only type check the symbol once
73503                 if (node === firstDeclaration) {
73504                     checkFunctionOrConstructorSymbol(localSymbol);
73505                 }
73506                 if (symbol.parent) {
73507                     // run check on export symbol to check that modifiers agree across all exported declarations
73508                     checkFunctionOrConstructorSymbol(symbol);
73509                 }
73510             }
73511             var body = node.kind === 164 /* MethodSignature */ ? undefined : node.body;
73512             checkSourceElement(body);
73513             checkAllCodePathsInNonVoidFunctionReturnOrThrow(node, getReturnTypeFromAnnotation(node));
73514             if (produceDiagnostics && !ts.getEffectiveReturnTypeNode(node)) {
73515                 // Report an implicit any error if there is no body, no explicit return type, and node is not a private method
73516                 // in an ambient context
73517                 if (ts.nodeIsMissing(body) && !isPrivateWithinAmbient(node)) {
73518                     reportImplicitAny(node, anyType);
73519                 }
73520                 if (functionFlags & 1 /* Generator */ && ts.nodeIsPresent(body)) {
73521                     // A generator with a body and no type annotation can still cause errors. It can error if the
73522                     // yielded values have no common supertype, or it can give an implicit any error if it has no
73523                     // yielded values. The only way to trigger these errors is to try checking its return type.
73524                     getReturnTypeOfSignature(getSignatureFromDeclaration(node));
73525                 }
73526             }
73527             // A js function declaration can have a @type tag instead of a return type node, but that type must have a call signature
73528             if (ts.isInJSFile(node)) {
73529                 var typeTag = ts.getJSDocTypeTag(node);
73530                 if (typeTag && typeTag.typeExpression && !getContextualCallSignature(getTypeFromTypeNode(typeTag.typeExpression), node)) {
73531                     error(typeTag, ts.Diagnostics.The_type_of_a_function_declaration_must_match_the_function_s_signature);
73532                 }
73533             }
73534         }
73535         function registerForUnusedIdentifiersCheck(node) {
73536             // May be in a call such as getTypeOfNode that happened to call this. But potentiallyUnusedIdentifiers is only defined in the scope of `checkSourceFile`.
73537             if (produceDiagnostics) {
73538                 var sourceFile = ts.getSourceFileOfNode(node);
73539                 var potentiallyUnusedIdentifiers = allPotentiallyUnusedIdentifiers.get(sourceFile.path);
73540                 if (!potentiallyUnusedIdentifiers) {
73541                     potentiallyUnusedIdentifiers = [];
73542                     allPotentiallyUnusedIdentifiers.set(sourceFile.path, potentiallyUnusedIdentifiers);
73543                 }
73544                 // TODO: GH#22580
73545                 // Debug.assert(addToSeen(seenPotentiallyUnusedIdentifiers, getNodeId(node)), "Adding potentially-unused identifier twice");
73546                 potentiallyUnusedIdentifiers.push(node);
73547             }
73548         }
73549         function checkUnusedIdentifiers(potentiallyUnusedIdentifiers, addDiagnostic) {
73550             for (var _i = 0, potentiallyUnusedIdentifiers_1 = potentiallyUnusedIdentifiers; _i < potentiallyUnusedIdentifiers_1.length; _i++) {
73551                 var node = potentiallyUnusedIdentifiers_1[_i];
73552                 switch (node.kind) {
73553                     case 252 /* ClassDeclaration */:
73554                     case 221 /* ClassExpression */:
73555                         checkUnusedClassMembers(node, addDiagnostic);
73556                         checkUnusedTypeParameters(node, addDiagnostic);
73557                         break;
73558                     case 297 /* SourceFile */:
73559                     case 256 /* ModuleDeclaration */:
73560                     case 230 /* Block */:
73561                     case 258 /* CaseBlock */:
73562                     case 237 /* ForStatement */:
73563                     case 238 /* ForInStatement */:
73564                     case 239 /* ForOfStatement */:
73565                         checkUnusedLocalsAndParameters(node, addDiagnostic);
73566                         break;
73567                     case 166 /* Constructor */:
73568                     case 208 /* FunctionExpression */:
73569                     case 251 /* FunctionDeclaration */:
73570                     case 209 /* ArrowFunction */:
73571                     case 165 /* MethodDeclaration */:
73572                     case 167 /* GetAccessor */:
73573                     case 168 /* SetAccessor */:
73574                         if (node.body) { // Don't report unused parameters in overloads
73575                             checkUnusedLocalsAndParameters(node, addDiagnostic);
73576                         }
73577                         checkUnusedTypeParameters(node, addDiagnostic);
73578                         break;
73579                     case 164 /* MethodSignature */:
73580                     case 169 /* CallSignature */:
73581                     case 170 /* ConstructSignature */:
73582                     case 174 /* FunctionType */:
73583                     case 175 /* ConstructorType */:
73584                     case 254 /* TypeAliasDeclaration */:
73585                     case 253 /* InterfaceDeclaration */:
73586                         checkUnusedTypeParameters(node, addDiagnostic);
73587                         break;
73588                     case 185 /* InferType */:
73589                         checkUnusedInferTypeParameter(node, addDiagnostic);
73590                         break;
73591                     default:
73592                         ts.Debug.assertNever(node, "Node should not have been registered for unused identifiers check");
73593                 }
73594             }
73595         }
73596         function errorUnusedLocal(declaration, name, addDiagnostic) {
73597             var node = ts.getNameOfDeclaration(declaration) || declaration;
73598             var message = isTypeDeclaration(declaration) ? ts.Diagnostics._0_is_declared_but_never_used : ts.Diagnostics._0_is_declared_but_its_value_is_never_read;
73599             addDiagnostic(declaration, 0 /* Local */, ts.createDiagnosticForNode(node, message, name));
73600         }
73601         function isIdentifierThatStartsWithUnderscore(node) {
73602             return ts.isIdentifier(node) && ts.idText(node).charCodeAt(0) === 95 /* _ */;
73603         }
73604         function checkUnusedClassMembers(node, addDiagnostic) {
73605             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
73606                 var member = _a[_i];
73607                 switch (member.kind) {
73608                     case 165 /* MethodDeclaration */:
73609                     case 163 /* PropertyDeclaration */:
73610                     case 167 /* GetAccessor */:
73611                     case 168 /* SetAccessor */:
73612                         if (member.kind === 168 /* SetAccessor */ && member.symbol.flags & 32768 /* GetAccessor */) {
73613                             // Already would have reported an error on the getter.
73614                             break;
73615                         }
73616                         var symbol = getSymbolOfNode(member);
73617                         if (!symbol.isReferenced
73618                             && (ts.hasEffectiveModifier(member, 8 /* Private */) || ts.isNamedDeclaration(member) && ts.isPrivateIdentifier(member.name))
73619                             && !(member.flags & 8388608 /* Ambient */)) {
73620                             addDiagnostic(member, 0 /* Local */, ts.createDiagnosticForNode(member.name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, symbolToString(symbol)));
73621                         }
73622                         break;
73623                     case 166 /* Constructor */:
73624                         for (var _b = 0, _c = member.parameters; _b < _c.length; _b++) {
73625                             var parameter = _c[_b];
73626                             if (!parameter.symbol.isReferenced && ts.hasSyntacticModifier(parameter, 8 /* Private */)) {
73627                                 addDiagnostic(parameter, 0 /* Local */, ts.createDiagnosticForNode(parameter.name, ts.Diagnostics.Property_0_is_declared_but_its_value_is_never_read, ts.symbolName(parameter.symbol)));
73628                             }
73629                         }
73630                         break;
73631                     case 171 /* IndexSignature */:
73632                     case 229 /* SemicolonClassElement */:
73633                         // Can't be private
73634                         break;
73635                     default:
73636                         ts.Debug.fail();
73637                 }
73638             }
73639         }
73640         function checkUnusedInferTypeParameter(node, addDiagnostic) {
73641             var typeParameter = node.typeParameter;
73642             if (isTypeParameterUnused(typeParameter)) {
73643                 addDiagnostic(node, 1 /* Parameter */, ts.createDiagnosticForNode(node, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(typeParameter.name)));
73644             }
73645         }
73646         function checkUnusedTypeParameters(node, addDiagnostic) {
73647             // Only report errors on the last declaration for the type parameter container;
73648             // this ensures that all uses have been accounted for.
73649             if (ts.last(getSymbolOfNode(node).declarations) !== node)
73650                 return;
73651             var typeParameters = ts.getEffectiveTypeParameterDeclarations(node);
73652             var seenParentsWithEveryUnused = new ts.Set();
73653             for (var _i = 0, typeParameters_3 = typeParameters; _i < typeParameters_3.length; _i++) {
73654                 var typeParameter = typeParameters_3[_i];
73655                 if (!isTypeParameterUnused(typeParameter))
73656                     continue;
73657                 var name = ts.idText(typeParameter.name);
73658                 var parent = typeParameter.parent;
73659                 if (parent.kind !== 185 /* InferType */ && parent.typeParameters.every(isTypeParameterUnused)) {
73660                     if (ts.tryAddToSet(seenParentsWithEveryUnused, parent)) {
73661                         var range = ts.isJSDocTemplateTag(parent)
73662                             // Whole @template tag
73663                             ? ts.rangeOfNode(parent)
73664                             // Include the `<>` in the error message
73665                             : ts.rangeOfTypeParameters(parent.typeParameters);
73666                         var only = parent.typeParameters.length === 1;
73667                         var message = only ? ts.Diagnostics._0_is_declared_but_its_value_is_never_read : ts.Diagnostics.All_type_parameters_are_unused;
73668                         var arg0 = only ? name : undefined;
73669                         addDiagnostic(typeParameter, 1 /* Parameter */, ts.createFileDiagnostic(ts.getSourceFileOfNode(parent), range.pos, range.end - range.pos, message, arg0));
73670                     }
73671                 }
73672                 else {
73673                     addDiagnostic(typeParameter, 1 /* Parameter */, ts.createDiagnosticForNode(typeParameter, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, name));
73674                 }
73675             }
73676         }
73677         function isTypeParameterUnused(typeParameter) {
73678             return !(getMergedSymbol(typeParameter.symbol).isReferenced & 262144 /* TypeParameter */) && !isIdentifierThatStartsWithUnderscore(typeParameter.name);
73679         }
73680         function addToGroup(map, key, value, getKey) {
73681             var keyString = String(getKey(key));
73682             var group = map.get(keyString);
73683             if (group) {
73684                 group[1].push(value);
73685             }
73686             else {
73687                 map.set(keyString, [key, [value]]);
73688             }
73689         }
73690         function tryGetRootParameterDeclaration(node) {
73691             return ts.tryCast(ts.getRootDeclaration(node), ts.isParameter);
73692         }
73693         function isValidUnusedLocalDeclaration(declaration) {
73694             if (ts.isBindingElement(declaration) && isIdentifierThatStartsWithUnderscore(declaration.name)) {
73695                 return !!ts.findAncestor(declaration.parent, function (ancestor) {
73696                     return ts.isArrayBindingPattern(ancestor) || ts.isVariableDeclaration(ancestor) || ts.isVariableDeclarationList(ancestor) ? false :
73697                         ts.isForOfStatement(ancestor) ? true : "quit";
73698                 });
73699             }
73700             return ts.isAmbientModule(declaration) ||
73701                 (ts.isVariableDeclaration(declaration) && ts.isForInOrOfStatement(declaration.parent.parent) || isImportedDeclaration(declaration)) && isIdentifierThatStartsWithUnderscore(declaration.name);
73702         }
73703         function checkUnusedLocalsAndParameters(nodeWithLocals, addDiagnostic) {
73704             // 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.
73705             var unusedImports = new ts.Map();
73706             var unusedDestructures = new ts.Map();
73707             var unusedVariables = new ts.Map();
73708             nodeWithLocals.locals.forEach(function (local) {
73709                 // If it's purely a type parameter, ignore, will be checked in `checkUnusedTypeParameters`.
73710                 // If it's a type parameter merged with a parameter, check if the parameter-side is used.
73711                 if (local.flags & 262144 /* TypeParameter */ ? !(local.flags & 3 /* Variable */ && !(local.isReferenced & 3 /* Variable */)) : local.isReferenced || local.exportSymbol) {
73712                     return;
73713                 }
73714                 for (var _i = 0, _a = local.declarations; _i < _a.length; _i++) {
73715                     var declaration = _a[_i];
73716                     if (isValidUnusedLocalDeclaration(declaration)) {
73717                         continue;
73718                     }
73719                     if (isImportedDeclaration(declaration)) {
73720                         addToGroup(unusedImports, importClauseFromImported(declaration), declaration, getNodeId);
73721                     }
73722                     else if (ts.isBindingElement(declaration) && ts.isObjectBindingPattern(declaration.parent)) {
73723                         // In `{ a, ...b }, `a` is considered used since it removes a property from `b`. `b` may still be unused though.
73724                         var lastElement = ts.last(declaration.parent.elements);
73725                         if (declaration === lastElement || !ts.last(declaration.parent.elements).dotDotDotToken) {
73726                             addToGroup(unusedDestructures, declaration.parent, declaration, getNodeId);
73727                         }
73728                     }
73729                     else if (ts.isVariableDeclaration(declaration)) {
73730                         addToGroup(unusedVariables, declaration.parent, declaration, getNodeId);
73731                     }
73732                     else {
73733                         var parameter = local.valueDeclaration && tryGetRootParameterDeclaration(local.valueDeclaration);
73734                         var name = local.valueDeclaration && ts.getNameOfDeclaration(local.valueDeclaration);
73735                         if (parameter && name) {
73736                             if (!ts.isParameterPropertyDeclaration(parameter, parameter.parent) && !ts.parameterIsThisKeyword(parameter) && !isIdentifierThatStartsWithUnderscore(name)) {
73737                                 addDiagnostic(parameter, 1 /* Parameter */, ts.createDiagnosticForNode(name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.symbolName(local)));
73738                             }
73739                         }
73740                         else {
73741                             errorUnusedLocal(declaration, ts.symbolName(local), addDiagnostic);
73742                         }
73743                     }
73744                 }
73745             });
73746             unusedImports.forEach(function (_a) {
73747                 var importClause = _a[0], unuseds = _a[1];
73748                 var importDecl = importClause.parent;
73749                 var nDeclarations = (importClause.name ? 1 : 0) +
73750                     (importClause.namedBindings ?
73751                         (importClause.namedBindings.kind === 263 /* NamespaceImport */ ? 1 : importClause.namedBindings.elements.length)
73752                         : 0);
73753                 if (nDeclarations === unuseds.length) {
73754                     addDiagnostic(importDecl, 0 /* Local */, unuseds.length === 1
73755                         ? ts.createDiagnosticForNode(importDecl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, ts.idText(ts.first(unuseds).name))
73756                         : ts.createDiagnosticForNode(importDecl, ts.Diagnostics.All_imports_in_import_declaration_are_unused));
73757                 }
73758                 else {
73759                     for (var _i = 0, unuseds_1 = unuseds; _i < unuseds_1.length; _i++) {
73760                         var unused = unuseds_1[_i];
73761                         errorUnusedLocal(unused, ts.idText(unused.name), addDiagnostic);
73762                     }
73763                 }
73764             });
73765             unusedDestructures.forEach(function (_a) {
73766                 var bindingPattern = _a[0], bindingElements = _a[1];
73767                 var kind = tryGetRootParameterDeclaration(bindingPattern.parent) ? 1 /* Parameter */ : 0 /* Local */;
73768                 if (bindingPattern.elements.length === bindingElements.length) {
73769                     if (bindingElements.length === 1 && bindingPattern.parent.kind === 249 /* VariableDeclaration */ && bindingPattern.parent.parent.kind === 250 /* VariableDeclarationList */) {
73770                         addToGroup(unusedVariables, bindingPattern.parent.parent, bindingPattern.parent, getNodeId);
73771                     }
73772                     else {
73773                         addDiagnostic(bindingPattern, kind, bindingElements.length === 1
73774                             ? ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(bindingElements).name))
73775                             : ts.createDiagnosticForNode(bindingPattern, ts.Diagnostics.All_destructured_elements_are_unused));
73776                     }
73777                 }
73778                 else {
73779                     for (var _i = 0, bindingElements_1 = bindingElements; _i < bindingElements_1.length; _i++) {
73780                         var e = bindingElements_1[_i];
73781                         addDiagnostic(e, kind, ts.createDiagnosticForNode(e, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(e.name)));
73782                     }
73783                 }
73784             });
73785             unusedVariables.forEach(function (_a) {
73786                 var declarationList = _a[0], declarations = _a[1];
73787                 if (declarationList.declarations.length === declarations.length) {
73788                     addDiagnostic(declarationList, 0 /* Local */, declarations.length === 1
73789                         ? ts.createDiagnosticForNode(ts.first(declarations).name, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(ts.first(declarations).name))
73790                         : ts.createDiagnosticForNode(declarationList.parent.kind === 232 /* VariableStatement */ ? declarationList.parent : declarationList, ts.Diagnostics.All_variables_are_unused));
73791                 }
73792                 else {
73793                     for (var _i = 0, declarations_5 = declarations; _i < declarations_5.length; _i++) {
73794                         var decl = declarations_5[_i];
73795                         addDiagnostic(decl, 0 /* Local */, ts.createDiagnosticForNode(decl, ts.Diagnostics._0_is_declared_but_its_value_is_never_read, bindingNameText(decl.name)));
73796                     }
73797                 }
73798             });
73799         }
73800         function bindingNameText(name) {
73801             switch (name.kind) {
73802                 case 78 /* Identifier */:
73803                     return ts.idText(name);
73804                 case 197 /* ArrayBindingPattern */:
73805                 case 196 /* ObjectBindingPattern */:
73806                     return bindingNameText(ts.cast(ts.first(name.elements), ts.isBindingElement).name);
73807                 default:
73808                     return ts.Debug.assertNever(name);
73809             }
73810         }
73811         function isImportedDeclaration(node) {
73812             return node.kind === 262 /* ImportClause */ || node.kind === 265 /* ImportSpecifier */ || node.kind === 263 /* NamespaceImport */;
73813         }
73814         function importClauseFromImported(decl) {
73815             return decl.kind === 262 /* ImportClause */ ? decl : decl.kind === 263 /* NamespaceImport */ ? decl.parent : decl.parent.parent;
73816         }
73817         function checkBlock(node) {
73818             // Grammar checking for SyntaxKind.Block
73819             if (node.kind === 230 /* Block */) {
73820                 checkGrammarStatementInAmbientContext(node);
73821             }
73822             if (ts.isFunctionOrModuleBlock(node)) {
73823                 var saveFlowAnalysisDisabled = flowAnalysisDisabled;
73824                 ts.forEach(node.statements, checkSourceElement);
73825                 flowAnalysisDisabled = saveFlowAnalysisDisabled;
73826             }
73827             else {
73828                 ts.forEach(node.statements, checkSourceElement);
73829             }
73830             if (node.locals) {
73831                 registerForUnusedIdentifiersCheck(node);
73832             }
73833         }
73834         function checkCollisionWithArgumentsInGeneratedCode(node) {
73835             // no rest parameters \ declaration context \ overload - no codegen impact
73836             if (languageVersion >= 2 /* ES2015 */ || !ts.hasRestParameter(node) || node.flags & 8388608 /* Ambient */ || ts.nodeIsMissing(node.body)) {
73837                 return;
73838             }
73839             ts.forEach(node.parameters, function (p) {
73840                 if (p.name && !ts.isBindingPattern(p.name) && p.name.escapedText === argumentsSymbol.escapedName) {
73841                     errorSkippedOn("noEmit", p, ts.Diagnostics.Duplicate_identifier_arguments_Compiler_uses_arguments_to_initialize_rest_parameters);
73842                 }
73843             });
73844         }
73845         function needCollisionCheckForIdentifier(node, identifier, name) {
73846             if (!(identifier && identifier.escapedText === name)) {
73847                 return false;
73848             }
73849             if (node.kind === 163 /* PropertyDeclaration */ ||
73850                 node.kind === 162 /* PropertySignature */ ||
73851                 node.kind === 165 /* MethodDeclaration */ ||
73852                 node.kind === 164 /* MethodSignature */ ||
73853                 node.kind === 167 /* GetAccessor */ ||
73854                 node.kind === 168 /* SetAccessor */) {
73855                 // it is ok to have member named '_super' or '_this' - member access is always qualified
73856                 return false;
73857             }
73858             if (node.flags & 8388608 /* Ambient */) {
73859                 // ambient context - no codegen impact
73860                 return false;
73861             }
73862             var root = ts.getRootDeclaration(node);
73863             if (root.kind === 160 /* Parameter */ && ts.nodeIsMissing(root.parent.body)) {
73864                 // just an overload - no codegen impact
73865                 return false;
73866             }
73867             return true;
73868         }
73869         // this function will run after checking the source file so 'CaptureThis' is correct for all nodes
73870         function checkIfThisIsCapturedInEnclosingScope(node) {
73871             ts.findAncestor(node, function (current) {
73872                 if (getNodeCheckFlags(current) & 4 /* CaptureThis */) {
73873                     var isDeclaration_1 = node.kind !== 78 /* Identifier */;
73874                     if (isDeclaration_1) {
73875                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_this_Compiler_uses_variable_declaration_this_to_capture_this_reference);
73876                     }
73877                     else {
73878                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_this_that_compiler_uses_to_capture_this_reference);
73879                     }
73880                     return true;
73881                 }
73882                 return false;
73883             });
73884         }
73885         function checkIfNewTargetIsCapturedInEnclosingScope(node) {
73886             ts.findAncestor(node, function (current) {
73887                 if (getNodeCheckFlags(current) & 8 /* CaptureNewTarget */) {
73888                     var isDeclaration_2 = node.kind !== 78 /* Identifier */;
73889                     if (isDeclaration_2) {
73890                         error(ts.getNameOfDeclaration(node), ts.Diagnostics.Duplicate_identifier_newTarget_Compiler_uses_variable_declaration_newTarget_to_capture_new_target_meta_property_reference);
73891                     }
73892                     else {
73893                         error(node, ts.Diagnostics.Expression_resolves_to_variable_declaration_newTarget_that_compiler_uses_to_capture_new_target_meta_property_reference);
73894                     }
73895                     return true;
73896                 }
73897                 return false;
73898             });
73899         }
73900         function checkWeakMapCollision(node) {
73901             var enclosingBlockScope = ts.getEnclosingBlockScopeContainer(node);
73902             if (getNodeCheckFlags(enclosingBlockScope) & 67108864 /* ContainsClassWithPrivateIdentifiers */) {
73903                 errorSkippedOn("noEmit", node, ts.Diagnostics.Compiler_reserves_name_0_when_emitting_private_identifier_downlevel, "WeakMap");
73904             }
73905         }
73906         function checkCollisionWithRequireExportsInGeneratedCode(node, name) {
73907             // No need to check for require or exports for ES6 modules and later
73908             if (moduleKind >= ts.ModuleKind.ES2015) {
73909                 return;
73910             }
73911             if (!needCollisionCheckForIdentifier(node, name, "require") && !needCollisionCheckForIdentifier(node, name, "exports")) {
73912                 return;
73913             }
73914             // Uninstantiated modules shouldnt do this check
73915             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
73916                 return;
73917             }
73918             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
73919             var parent = getDeclarationContainer(node);
73920             if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent)) {
73921                 // If the declaration happens to be in external module, report error that require and exports are reserved keywords
73922                 errorSkippedOn("noEmit", name, ts.Diagnostics.Duplicate_identifier_0_Compiler_reserves_name_1_in_top_level_scope_of_a_module, ts.declarationNameToString(name), ts.declarationNameToString(name));
73923             }
73924         }
73925         function checkCollisionWithGlobalPromiseInGeneratedCode(node, name) {
73926             if (languageVersion >= 4 /* ES2017 */ || !needCollisionCheckForIdentifier(node, name, "Promise")) {
73927                 return;
73928             }
73929             // Uninstantiated modules shouldnt do this check
73930             if (ts.isModuleDeclaration(node) && ts.getModuleInstanceState(node) !== 1 /* Instantiated */) {
73931                 return;
73932             }
73933             // In case of variable declaration, node.parent is variable statement so look at the variable statement's parent
73934             var parent = getDeclarationContainer(node);
73935             if (parent.kind === 297 /* SourceFile */ && ts.isExternalOrCommonJsModule(parent) && parent.flags & 2048 /* HasAsyncFunctions */) {
73936                 // If the declaration happens to be in external module, report error that Promise is a reserved identifier.
73937                 errorSkippedOn("noEmit", 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));
73938             }
73939         }
73940         function checkVarDeclaredNamesNotShadowed(node) {
73941             // - ScriptBody : StatementList
73942             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
73943             // also occurs in the VarDeclaredNames of StatementList.
73944             // - Block : { StatementList }
73945             // It is a Syntax Error if any element of the LexicallyDeclaredNames of StatementList
73946             // also occurs in the VarDeclaredNames of StatementList.
73947             // Variable declarations are hoisted to the top of their function scope. They can shadow
73948             // block scoped declarations, which bind tighter. this will not be flagged as duplicate definition
73949             // by the binder as the declaration scope is different.
73950             // A non-initialized declaration is a no-op as the block declaration will resolve before the var
73951             // declaration. the problem is if the declaration has an initializer. this will act as a write to the
73952             // block declared value. this is fine for let, but not const.
73953             // Only consider declarations with initializers, uninitialized const declarations will not
73954             // step on a let/const variable.
73955             // Do not consider const and const declarations, as duplicate block-scoped declarations
73956             // are handled by the binder.
73957             // We are only looking for const declarations that step on let\const declarations from a
73958             // different scope. e.g.:
73959             //      {
73960             //          const x = 0; // localDeclarationSymbol obtained after name resolution will correspond to this declaration
73961             //          const x = 0; // symbol for this declaration will be 'symbol'
73962             //      }
73963             // skip block-scoped variables and parameters
73964             if ((ts.getCombinedNodeFlags(node) & 3 /* BlockScoped */) !== 0 || ts.isParameterDeclaration(node)) {
73965                 return;
73966             }
73967             // skip variable declarations that don't have initializers
73968             // NOTE: in ES6 spec initializer is required in variable declarations where name is binding pattern
73969             // so we'll always treat binding elements as initialized
73970             if (node.kind === 249 /* VariableDeclaration */ && !node.initializer) {
73971                 return;
73972             }
73973             var symbol = getSymbolOfNode(node);
73974             if (symbol.flags & 1 /* FunctionScopedVariable */) {
73975                 if (!ts.isIdentifier(node.name))
73976                     return ts.Debug.fail();
73977                 var localDeclarationSymbol = resolveName(node, node.name.escapedText, 3 /* Variable */, /*nodeNotFoundErrorMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false);
73978                 if (localDeclarationSymbol &&
73979                     localDeclarationSymbol !== symbol &&
73980                     localDeclarationSymbol.flags & 2 /* BlockScopedVariable */) {
73981                     if (getDeclarationNodeFlagsFromSymbol(localDeclarationSymbol) & 3 /* BlockScoped */) {
73982                         var varDeclList = ts.getAncestor(localDeclarationSymbol.valueDeclaration, 250 /* VariableDeclarationList */);
73983                         var container = varDeclList.parent.kind === 232 /* VariableStatement */ && varDeclList.parent.parent
73984                             ? varDeclList.parent.parent
73985                             : undefined;
73986                         // names of block-scoped and function scoped variables can collide only
73987                         // if block scoped variable is defined in the function\module\source file scope (because of variable hoisting)
73988                         var namesShareScope = container &&
73989                             (container.kind === 230 /* Block */ && ts.isFunctionLike(container.parent) ||
73990                                 container.kind === 257 /* ModuleBlock */ ||
73991                                 container.kind === 256 /* ModuleDeclaration */ ||
73992                                 container.kind === 297 /* SourceFile */);
73993                         // here we know that function scoped variable is shadowed by block scoped one
73994                         // if they are defined in the same scope - binder has already reported redeclaration error
73995                         // otherwise if variable has an initializer - show error that initialization will fail
73996                         // since LHS will be block scoped name instead of function scoped
73997                         if (!namesShareScope) {
73998                             var name = symbolToString(localDeclarationSymbol);
73999                             error(node, ts.Diagnostics.Cannot_initialize_outer_scoped_variable_0_in_the_same_scope_as_block_scoped_declaration_1, name, name);
74000                         }
74001                     }
74002                 }
74003             }
74004         }
74005         function convertAutoToAny(type) {
74006             return type === autoType ? anyType : type === autoArrayType ? anyArrayType : type;
74007         }
74008         // Check variable, parameter, or property declaration
74009         function checkVariableLikeDeclaration(node) {
74010             var _a;
74011             checkDecorators(node);
74012             if (!ts.isBindingElement(node)) {
74013                 checkSourceElement(node.type);
74014             }
74015             // JSDoc `function(string, string): string` syntax results in parameters with no name
74016             if (!node.name) {
74017                 return;
74018             }
74019             // For a computed property, just check the initializer and exit
74020             // Do not use hasDynamicName here, because that returns false for well known symbols.
74021             // We want to perform checkComputedPropertyName for all computed properties, including
74022             // well known symbols.
74023             if (node.name.kind === 158 /* ComputedPropertyName */) {
74024                 checkComputedPropertyName(node.name);
74025                 if (node.initializer) {
74026                     checkExpressionCached(node.initializer);
74027                 }
74028             }
74029             if (node.kind === 198 /* BindingElement */) {
74030                 if (node.parent.kind === 196 /* ObjectBindingPattern */ && languageVersion < 99 /* ESNext */) {
74031                     checkExternalEmitHelpers(node, 4 /* Rest */);
74032                 }
74033                 // check computed properties inside property names of binding elements
74034                 if (node.propertyName && node.propertyName.kind === 158 /* ComputedPropertyName */) {
74035                     checkComputedPropertyName(node.propertyName);
74036                 }
74037                 // check private/protected variable access
74038                 var parent = node.parent.parent;
74039                 var parentType = getTypeForBindingElementParent(parent);
74040                 var name = node.propertyName || node.name;
74041                 if (parentType && !ts.isBindingPattern(name)) {
74042                     var exprType = getLiteralTypeFromPropertyName(name);
74043                     if (isTypeUsableAsPropertyName(exprType)) {
74044                         var nameText = getPropertyNameFromType(exprType);
74045                         var property = getPropertyOfType(parentType, nameText);
74046                         if (property) {
74047                             markPropertyAsReferenced(property, /*nodeForCheckWriteOnly*/ undefined, /*isThisAccess*/ false); // A destructuring is never a write-only reference.
74048                             checkPropertyAccessibility(parent, !!parent.initializer && parent.initializer.kind === 105 /* SuperKeyword */, parentType, property);
74049                         }
74050                     }
74051                 }
74052             }
74053             // For a binding pattern, check contained binding elements
74054             if (ts.isBindingPattern(node.name)) {
74055                 if (node.name.kind === 197 /* ArrayBindingPattern */ && languageVersion < 2 /* ES2015 */ && compilerOptions.downlevelIteration) {
74056                     checkExternalEmitHelpers(node, 512 /* Read */);
74057                 }
74058                 ts.forEach(node.name.elements, checkSourceElement);
74059             }
74060             // For a parameter declaration with an initializer, error and exit if the containing function doesn't have a body
74061             if (node.initializer && ts.isParameterDeclaration(node) && ts.nodeIsMissing(ts.getContainingFunction(node).body)) {
74062                 error(node, ts.Diagnostics.A_parameter_initializer_is_only_allowed_in_a_function_or_constructor_implementation);
74063                 return;
74064             }
74065             // For a binding pattern, validate the initializer and exit
74066             if (ts.isBindingPattern(node.name)) {
74067                 var needCheckInitializer = node.initializer && node.parent.parent.kind !== 238 /* ForInStatement */;
74068                 var needCheckWidenedType = node.name.elements.length === 0;
74069                 if (needCheckInitializer || needCheckWidenedType) {
74070                     // Don't validate for-in initializer as it is already an error
74071                     var widenedType = getWidenedTypeForVariableLikeDeclaration(node);
74072                     if (needCheckInitializer) {
74073                         var initializerType = checkExpressionCached(node.initializer);
74074                         if (strictNullChecks && needCheckWidenedType) {
74075                             checkNonNullNonVoidType(initializerType, node);
74076                         }
74077                         else {
74078                             checkTypeAssignableToAndOptionallyElaborate(initializerType, getWidenedTypeForVariableLikeDeclaration(node), node, node.initializer);
74079                         }
74080                     }
74081                     // check the binding pattern with empty elements
74082                     if (needCheckWidenedType) {
74083                         if (ts.isArrayBindingPattern(node.name)) {
74084                             checkIteratedTypeOrElementType(65 /* Destructuring */, widenedType, undefinedType, node);
74085                         }
74086                         else if (strictNullChecks) {
74087                             checkNonNullNonVoidType(widenedType, node);
74088                         }
74089                     }
74090                 }
74091                 return;
74092             }
74093             // For a commonjs `const x = require`, validate the alias and exit
74094             var symbol = getSymbolOfNode(node);
74095             if (symbol.flags & 2097152 /* Alias */ && ts.isRequireVariableDeclaration(node, /*requireStringLiteralLikeArgument*/ true)) {
74096                 checkAliasSymbol(node);
74097                 return;
74098             }
74099             var type = convertAutoToAny(getTypeOfSymbol(symbol));
74100             if (node === symbol.valueDeclaration) {
74101                 // Node is the primary declaration of the symbol, just validate the initializer
74102                 // Don't validate for-in initializer as it is already an error
74103                 var initializer = ts.getEffectiveInitializer(node);
74104                 if (initializer) {
74105                     var isJSObjectLiteralInitializer = ts.isInJSFile(node) &&
74106                         ts.isObjectLiteralExpression(initializer) &&
74107                         (initializer.properties.length === 0 || ts.isPrototypeAccess(node.name)) &&
74108                         !!((_a = symbol.exports) === null || _a === void 0 ? void 0 : _a.size);
74109                     if (!isJSObjectLiteralInitializer && node.parent.parent.kind !== 238 /* ForInStatement */) {
74110                         checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(initializer), type, node, initializer, /*headMessage*/ undefined);
74111                     }
74112                 }
74113                 if (symbol.declarations.length > 1) {
74114                     if (ts.some(symbol.declarations, function (d) { return d !== node && ts.isVariableLike(d) && !areDeclarationFlagsIdentical(d, node); })) {
74115                         error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
74116                     }
74117                 }
74118             }
74119             else {
74120                 // Node is a secondary declaration, check that type is identical to primary declaration and check that
74121                 // initializer is consistent with type associated with the node
74122                 var declarationType = convertAutoToAny(getWidenedTypeForVariableLikeDeclaration(node));
74123                 if (type !== errorType && declarationType !== errorType &&
74124                     !isTypeIdenticalTo(type, declarationType) &&
74125                     !(symbol.flags & 67108864 /* Assignment */)) {
74126                     errorNextVariableOrPropertyDeclarationMustHaveSameType(symbol.valueDeclaration, type, node, declarationType);
74127                 }
74128                 if (node.initializer) {
74129                     checkTypeAssignableToAndOptionallyElaborate(checkExpressionCached(node.initializer), declarationType, node, node.initializer, /*headMessage*/ undefined);
74130                 }
74131                 if (!areDeclarationFlagsIdentical(node, symbol.valueDeclaration)) {
74132                     error(node.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_modifiers, ts.declarationNameToString(node.name));
74133                 }
74134             }
74135             if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */) {
74136                 // We know we don't have a binding pattern or computed name here
74137                 checkExportsOnMergedDeclarations(node);
74138                 if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) {
74139                     checkVarDeclaredNamesNotShadowed(node);
74140                 }
74141                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
74142                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
74143                 if (languageVersion < 99 /* ESNext */ && needCollisionCheckForIdentifier(node, node.name, "WeakMap")) {
74144                     potentialWeakMapCollisions.push(node);
74145                 }
74146             }
74147         }
74148         function errorNextVariableOrPropertyDeclarationMustHaveSameType(firstDeclaration, firstType, nextDeclaration, nextType) {
74149             var nextDeclarationName = ts.getNameOfDeclaration(nextDeclaration);
74150             var message = nextDeclaration.kind === 163 /* PropertyDeclaration */ || nextDeclaration.kind === 162 /* PropertySignature */
74151                 ? ts.Diagnostics.Subsequent_property_declarations_must_have_the_same_type_Property_0_must_be_of_type_1_but_here_has_type_2
74152                 : ts.Diagnostics.Subsequent_variable_declarations_must_have_the_same_type_Variable_0_must_be_of_type_1_but_here_has_type_2;
74153             var declName = ts.declarationNameToString(nextDeclarationName);
74154             var err = error(nextDeclarationName, message, declName, typeToString(firstType), typeToString(nextType));
74155             if (firstDeclaration) {
74156                 ts.addRelatedInfo(err, ts.createDiagnosticForNode(firstDeclaration, ts.Diagnostics._0_was_also_declared_here, declName));
74157             }
74158         }
74159         function areDeclarationFlagsIdentical(left, right) {
74160             if ((left.kind === 160 /* Parameter */ && right.kind === 249 /* VariableDeclaration */) ||
74161                 (left.kind === 249 /* VariableDeclaration */ && right.kind === 160 /* Parameter */)) {
74162                 // Differences in optionality between parameters and variables are allowed.
74163                 return true;
74164             }
74165             if (ts.hasQuestionToken(left) !== ts.hasQuestionToken(right)) {
74166                 return false;
74167             }
74168             var interestingFlags = 8 /* Private */ |
74169                 16 /* Protected */ |
74170                 256 /* Async */ |
74171                 128 /* Abstract */ |
74172                 64 /* Readonly */ |
74173                 32 /* Static */;
74174             return ts.getSelectedEffectiveModifierFlags(left, interestingFlags) === ts.getSelectedEffectiveModifierFlags(right, interestingFlags);
74175         }
74176         function checkVariableDeclaration(node) {
74177             ts.tracing.push("check" /* Check */, "checkVariableDeclaration", { kind: node.kind, pos: node.pos, end: node.end });
74178             checkGrammarVariableDeclaration(node);
74179             checkVariableLikeDeclaration(node);
74180             ts.tracing.pop();
74181         }
74182         function checkBindingElement(node) {
74183             checkGrammarBindingElement(node);
74184             return checkVariableLikeDeclaration(node);
74185         }
74186         function checkVariableStatement(node) {
74187             // Grammar checking
74188             if (!checkGrammarDecoratorsAndModifiers(node) && !checkGrammarVariableDeclarationList(node.declarationList))
74189                 checkGrammarForDisallowedLetOrConstStatement(node);
74190             ts.forEach(node.declarationList.declarations, checkSourceElement);
74191         }
74192         function checkExpressionStatement(node) {
74193             // Grammar checking
74194             checkGrammarStatementInAmbientContext(node);
74195             checkExpression(node.expression);
74196         }
74197         function checkIfStatement(node) {
74198             // Grammar checking
74199             checkGrammarStatementInAmbientContext(node);
74200             var type = checkTruthinessExpression(node.expression);
74201             checkTestingKnownTruthyCallableType(node.expression, node.thenStatement, type);
74202             checkSourceElement(node.thenStatement);
74203             if (node.thenStatement.kind === 231 /* EmptyStatement */) {
74204                 error(node.thenStatement, ts.Diagnostics.The_body_of_an_if_statement_cannot_be_the_empty_statement);
74205             }
74206             checkSourceElement(node.elseStatement);
74207         }
74208         function checkTestingKnownTruthyCallableType(condExpr, body, type) {
74209             if (!strictNullChecks) {
74210                 return;
74211             }
74212             var testedNode = ts.isIdentifier(condExpr)
74213                 ? condExpr
74214                 : ts.isPropertyAccessExpression(condExpr)
74215                     ? condExpr.name
74216                     : undefined;
74217             if (!testedNode) {
74218                 return;
74219             }
74220             var possiblyFalsy = getFalsyFlags(type);
74221             if (possiblyFalsy) {
74222                 return;
74223             }
74224             // While it technically should be invalid for any known-truthy value
74225             // to be tested, we de-scope to functions unrefenced in the block as a
74226             // heuristic to identify the most common bugs. There are too many
74227             // false positives for values sourced from type definitions without
74228             // strictNullChecks otherwise.
74229             var callSignatures = getSignaturesOfType(type, 0 /* Call */);
74230             if (callSignatures.length === 0) {
74231                 return;
74232             }
74233             var testedFunctionSymbol = getSymbolAtLocation(testedNode);
74234             if (!testedFunctionSymbol) {
74235                 return;
74236             }
74237             var functionIsUsedInBody = ts.forEachChild(body, function check(childNode) {
74238                 if (ts.isIdentifier(childNode)) {
74239                     var childSymbol = getSymbolAtLocation(childNode);
74240                     if (childSymbol && childSymbol === testedFunctionSymbol) {
74241                         // If the test was a simple identifier, the above check is sufficient
74242                         if (ts.isIdentifier(condExpr)) {
74243                             return true;
74244                         }
74245                         // Otherwise we need to ensure the symbol is called on the same target
74246                         var testedExpression = testedNode.parent;
74247                         var childExpression = childNode.parent;
74248                         while (testedExpression && childExpression) {
74249                             if (ts.isIdentifier(testedExpression) && ts.isIdentifier(childExpression) ||
74250                                 testedExpression.kind === 107 /* ThisKeyword */ && childExpression.kind === 107 /* ThisKeyword */) {
74251                                 return getSymbolAtLocation(testedExpression) === getSymbolAtLocation(childExpression);
74252                             }
74253                             if (ts.isPropertyAccessExpression(testedExpression) && ts.isPropertyAccessExpression(childExpression)) {
74254                                 if (getSymbolAtLocation(testedExpression.name) !== getSymbolAtLocation(childExpression.name)) {
74255                                     return false;
74256                                 }
74257                                 childExpression = childExpression.expression;
74258                                 testedExpression = testedExpression.expression;
74259                             }
74260                             else {
74261                                 return false;
74262                             }
74263                         }
74264                     }
74265                 }
74266                 return ts.forEachChild(childNode, check);
74267             });
74268             if (!functionIsUsedInBody) {
74269                 error(condExpr, ts.Diagnostics.This_condition_will_always_return_true_since_the_function_is_always_defined_Did_you_mean_to_call_it_instead);
74270             }
74271         }
74272         function checkDoStatement(node) {
74273             // Grammar checking
74274             checkGrammarStatementInAmbientContext(node);
74275             checkSourceElement(node.statement);
74276             checkTruthinessExpression(node.expression);
74277         }
74278         function checkWhileStatement(node) {
74279             // Grammar checking
74280             checkGrammarStatementInAmbientContext(node);
74281             checkTruthinessExpression(node.expression);
74282             checkSourceElement(node.statement);
74283         }
74284         function checkTruthinessOfType(type, node) {
74285             if (type.flags & 16384 /* Void */) {
74286                 error(node, ts.Diagnostics.An_expression_of_type_void_cannot_be_tested_for_truthiness);
74287             }
74288             return type;
74289         }
74290         function checkTruthinessExpression(node, checkMode) {
74291             return checkTruthinessOfType(checkExpression(node, checkMode), node);
74292         }
74293         function checkForStatement(node) {
74294             // Grammar checking
74295             if (!checkGrammarStatementInAmbientContext(node)) {
74296                 if (node.initializer && node.initializer.kind === 250 /* VariableDeclarationList */) {
74297                     checkGrammarVariableDeclarationList(node.initializer);
74298                 }
74299             }
74300             if (node.initializer) {
74301                 if (node.initializer.kind === 250 /* VariableDeclarationList */) {
74302                     ts.forEach(node.initializer.declarations, checkVariableDeclaration);
74303                 }
74304                 else {
74305                     checkExpression(node.initializer);
74306                 }
74307             }
74308             if (node.condition)
74309                 checkTruthinessExpression(node.condition);
74310             if (node.incrementor)
74311                 checkExpression(node.incrementor);
74312             checkSourceElement(node.statement);
74313             if (node.locals) {
74314                 registerForUnusedIdentifiersCheck(node);
74315             }
74316         }
74317         function checkForOfStatement(node) {
74318             checkGrammarForInOrForOfStatement(node);
74319             if (node.awaitModifier) {
74320                 var functionFlags = ts.getFunctionFlags(ts.getContainingFunction(node));
74321                 if ((functionFlags & (4 /* Invalid */ | 2 /* Async */)) === 2 /* Async */ && languageVersion < 99 /* ESNext */) {
74322                     // for..await..of in an async function or async generator function prior to ESNext requires the __asyncValues helper
74323                     checkExternalEmitHelpers(node, 32768 /* ForAwaitOfIncludes */);
74324                 }
74325             }
74326             else if (compilerOptions.downlevelIteration && languageVersion < 2 /* ES2015 */) {
74327                 // for..of prior to ES2015 requires the __values helper when downlevelIteration is enabled
74328                 checkExternalEmitHelpers(node, 256 /* ForOfIncludes */);
74329             }
74330             // Check the LHS and RHS
74331             // If the LHS is a declaration, just check it as a variable declaration, which will in turn check the RHS
74332             // via checkRightHandSideOfForOf.
74333             // If the LHS is an expression, check the LHS, as a destructuring assignment or as a reference.
74334             // Then check that the RHS is assignable to it.
74335             if (node.initializer.kind === 250 /* VariableDeclarationList */) {
74336                 checkForInOrForOfVariableDeclaration(node);
74337             }
74338             else {
74339                 var varExpr = node.initializer;
74340                 var iteratedType = checkRightHandSideOfForOf(node);
74341                 // There may be a destructuring assignment on the left side
74342                 if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) {
74343                     // iteratedType may be undefined. In this case, we still want to check the structure of
74344                     // varExpr, in particular making sure it's a valid LeftHandSideExpression. But we'd like
74345                     // to short circuit the type relation checking as much as possible, so we pass the unknownType.
74346                     checkDestructuringAssignment(varExpr, iteratedType || errorType);
74347                 }
74348                 else {
74349                     var leftType = checkExpression(varExpr);
74350                     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);
74351                     // iteratedType will be undefined if the rightType was missing properties/signatures
74352                     // required to get its iteratedType (like [Symbol.iterator] or next). This may be
74353                     // because we accessed properties from anyType, or it may have led to an error inside
74354                     // getElementTypeOfIterable.
74355                     if (iteratedType) {
74356                         checkTypeAssignableToAndOptionallyElaborate(iteratedType, leftType, varExpr, node.expression);
74357                     }
74358                 }
74359             }
74360             checkSourceElement(node.statement);
74361             if (node.locals) {
74362                 registerForUnusedIdentifiersCheck(node);
74363             }
74364         }
74365         function checkForInStatement(node) {
74366             // Grammar checking
74367             checkGrammarForInOrForOfStatement(node);
74368             var rightType = getNonNullableTypeIfNeeded(checkExpression(node.expression));
74369             // TypeScript 1.0 spec (April 2014): 5.4
74370             // In a 'for-in' statement of the form
74371             // for (let VarDecl in Expr) Statement
74372             //   VarDecl must be a variable declaration without a type annotation that declares a variable of type Any,
74373             //   and Expr must be an expression of type Any, an object type, or a type parameter type.
74374             if (node.initializer.kind === 250 /* VariableDeclarationList */) {
74375                 var variable = node.initializer.declarations[0];
74376                 if (variable && ts.isBindingPattern(variable.name)) {
74377                     error(variable.name, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
74378                 }
74379                 checkForInOrForOfVariableDeclaration(node);
74380             }
74381             else {
74382                 // In a 'for-in' statement of the form
74383                 // for (Var in Expr) Statement
74384                 //   Var must be an expression classified as a reference of type Any or the String primitive type,
74385                 //   and Expr must be an expression of type Any, an object type, or a type parameter type.
74386                 var varExpr = node.initializer;
74387                 var leftType = checkExpression(varExpr);
74388                 if (varExpr.kind === 199 /* ArrayLiteralExpression */ || varExpr.kind === 200 /* ObjectLiteralExpression */) {
74389                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_be_a_destructuring_pattern);
74390                 }
74391                 else if (!isTypeAssignableTo(getIndexTypeOrString(rightType), leftType)) {
74392                     error(varExpr, ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_must_be_of_type_string_or_any);
74393                 }
74394                 else {
74395                     // run check only former check succeeded to avoid cascading errors
74396                     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);
74397                 }
74398             }
74399             // unknownType is returned i.e. if node.expression is identifier whose name cannot be resolved
74400             // in this case error about missing name is already reported - do not report extra one
74401             if (rightType === neverType || !isTypeAssignableToKind(rightType, 67108864 /* NonPrimitive */ | 58982400 /* InstantiableNonPrimitive */)) {
74402                 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));
74403             }
74404             checkSourceElement(node.statement);
74405             if (node.locals) {
74406                 registerForUnusedIdentifiersCheck(node);
74407             }
74408         }
74409         function checkForInOrForOfVariableDeclaration(iterationStatement) {
74410             var variableDeclarationList = iterationStatement.initializer;
74411             // checkGrammarForInOrForOfStatement will check that there is exactly one declaration.
74412             if (variableDeclarationList.declarations.length >= 1) {
74413                 var decl = variableDeclarationList.declarations[0];
74414                 checkVariableDeclaration(decl);
74415             }
74416         }
74417         function checkRightHandSideOfForOf(statement) {
74418             var use = statement.awaitModifier ? 15 /* ForAwaitOf */ : 13 /* ForOf */;
74419             return checkIteratedTypeOrElementType(use, checkNonNullExpression(statement.expression), undefinedType, statement.expression);
74420         }
74421         function checkIteratedTypeOrElementType(use, inputType, sentType, errorNode) {
74422             if (isTypeAny(inputType)) {
74423                 return inputType;
74424             }
74425             return getIteratedTypeOrElementType(use, inputType, sentType, errorNode, /*checkAssignability*/ true) || anyType;
74426         }
74427         /**
74428          * When consuming an iterable type in a for..of, spread, or iterator destructuring assignment
74429          * we want to get the iterated type of an iterable for ES2015 or later, or the iterated type
74430          * of a iterable (if defined globally) or element type of an array like for ES2015 or earlier.
74431          */
74432         function getIteratedTypeOrElementType(use, inputType, sentType, errorNode, checkAssignability) {
74433             var allowAsyncIterables = (use & 2 /* AllowsAsyncIterablesFlag */) !== 0;
74434             if (inputType === neverType) {
74435                 reportTypeNotIterableError(errorNode, inputType, allowAsyncIterables); // TODO: GH#18217
74436                 return undefined;
74437             }
74438             var uplevelIteration = languageVersion >= 2 /* ES2015 */;
74439             var downlevelIteration = !uplevelIteration && compilerOptions.downlevelIteration;
74440             var possibleOutOfBounds = compilerOptions.noUncheckedIndexedAccess && !!(use & 128 /* PossiblyOutOfBounds */);
74441             // Get the iterated type of an `Iterable<T>` or `IterableIterator<T>` only in ES2015
74442             // or higher, when inside of an async generator or for-await-if, or when
74443             // downlevelIteration is requested.
74444             if (uplevelIteration || downlevelIteration || allowAsyncIterables) {
74445                 // We only report errors for an invalid iterable type in ES2015 or higher.
74446                 var iterationTypes = getIterationTypesOfIterable(inputType, use, uplevelIteration ? errorNode : undefined);
74447                 if (checkAssignability) {
74448                     if (iterationTypes) {
74449                         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 :
74450                             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 :
74451                                 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 :
74452                                     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 :
74453                                         undefined;
74454                         if (diagnostic) {
74455                             checkTypeAssignableTo(sentType, iterationTypes.nextType, errorNode, diagnostic);
74456                         }
74457                     }
74458                 }
74459                 if (iterationTypes || uplevelIteration) {
74460                     return possibleOutOfBounds ? includeUndefinedInIndexSignature(iterationTypes && iterationTypes.yieldType) : (iterationTypes && iterationTypes.yieldType);
74461                 }
74462             }
74463             var arrayType = inputType;
74464             var reportedError = false;
74465             var hasStringConstituent = false;
74466             // If strings are permitted, remove any string-like constituents from the array type.
74467             // This allows us to find other non-string element types from an array unioned with
74468             // a string.
74469             if (use & 4 /* AllowsStringInputFlag */) {
74470                 if (arrayType.flags & 1048576 /* Union */) {
74471                     // After we remove all types that are StringLike, we will know if there was a string constituent
74472                     // based on whether the result of filter is a new array.
74473                     var arrayTypes = inputType.types;
74474                     var filteredTypes = ts.filter(arrayTypes, function (t) { return !(t.flags & 402653316 /* StringLike */); });
74475                     if (filteredTypes !== arrayTypes) {
74476                         arrayType = getUnionType(filteredTypes, 2 /* Subtype */);
74477                     }
74478                 }
74479                 else if (arrayType.flags & 402653316 /* StringLike */) {
74480                     arrayType = neverType;
74481                 }
74482                 hasStringConstituent = arrayType !== inputType;
74483                 if (hasStringConstituent) {
74484                     if (languageVersion < 1 /* ES5 */) {
74485                         if (errorNode) {
74486                             error(errorNode, ts.Diagnostics.Using_a_string_in_a_for_of_statement_is_only_supported_in_ECMAScript_5_and_higher);
74487                             reportedError = true;
74488                         }
74489                     }
74490                     // Now that we've removed all the StringLike types, if no constituents remain, then the entire
74491                     // arrayOrStringType was a string.
74492                     if (arrayType.flags & 131072 /* Never */) {
74493                         return possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType;
74494                     }
74495                 }
74496             }
74497             if (!isArrayLikeType(arrayType)) {
74498                 if (errorNode && !reportedError) {
74499                     // Which error we report depends on whether we allow strings or if there was a
74500                     // string constituent. For example, if the input type is number | string, we
74501                     // want to say that number is not an array type. But if the input was just
74502                     // number and string input is allowed, we want to say that number is not an
74503                     // array type or a string type.
74504                     var yieldType = getIterationTypeOfIterable(use, 0 /* Yield */, inputType, /*errorNode*/ undefined);
74505                     var _a = !(use & 4 /* AllowsStringInputFlag */) || hasStringConstituent
74506                         ? downlevelIteration
74507                             ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_does_not_have_a_Symbol_iterator_method_that_returns_an_iterator, true]
74508                             : yieldType
74509                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
74510                                 : [ts.Diagnostics.Type_0_is_not_an_array_type, true]
74511                         : downlevelIteration
74512                             ? [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]
74513                             : yieldType
74514                                 ? [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type_Use_compiler_option_downlevelIteration_to_allow_iterating_of_iterators, false]
74515                                 : [ts.Diagnostics.Type_0_is_not_an_array_type_or_a_string_type, true], defaultDiagnostic = _a[0], maybeMissingAwait = _a[1];
74516                     errorAndMaybeSuggestAwait(errorNode, maybeMissingAwait && !!getAwaitedTypeOfPromise(arrayType), defaultDiagnostic, typeToString(arrayType));
74517                 }
74518                 return hasStringConstituent ? possibleOutOfBounds ? includeUndefinedInIndexSignature(stringType) : stringType : undefined;
74519             }
74520             var arrayElementType = getIndexTypeOfType(arrayType, 1 /* Number */);
74521             if (hasStringConstituent && arrayElementType) {
74522                 // This is just an optimization for the case where arrayOrStringType is string | string[]
74523                 if (arrayElementType.flags & 402653316 /* StringLike */ && !compilerOptions.noUncheckedIndexedAccess) {
74524                     return stringType;
74525                 }
74526                 return getUnionType(possibleOutOfBounds ? [arrayElementType, stringType, undefinedType] : [arrayElementType, stringType], 2 /* Subtype */);
74527             }
74528             return (use & 128 /* PossiblyOutOfBounds */) ? includeUndefinedInIndexSignature(arrayElementType) : arrayElementType;
74529         }
74530         /**
74531          * Gets the requested "iteration type" from an `Iterable`-like or `AsyncIterable`-like type.
74532          */
74533         function getIterationTypeOfIterable(use, typeKind, inputType, errorNode) {
74534             if (isTypeAny(inputType)) {
74535                 return undefined;
74536             }
74537             var iterationTypes = getIterationTypesOfIterable(inputType, use, errorNode);
74538             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(typeKind)];
74539         }
74540         function createIterationTypes(yieldType, returnType, nextType) {
74541             // `yieldType` and `returnType` are defaulted to `neverType` they each will be combined
74542             // via `getUnionType` when merging iteration types. `nextType` is defined as `unknownType`
74543             // as it is combined via `getIntersectionType` when merging iteration types.
74544             if (yieldType === void 0) { yieldType = neverType; }
74545             if (returnType === void 0) { returnType = neverType; }
74546             if (nextType === void 0) { nextType = unknownType; }
74547             // Use the cache only for intrinsic types to keep it small as they are likely to be
74548             // more frequently created (i.e. `Iterator<number, void, unknown>`). Iteration types
74549             // are also cached on the type they are requested for, so we shouldn't need to maintain
74550             // the cache for less-frequently used types.
74551             if (yieldType.flags & 67359327 /* Intrinsic */ &&
74552                 returnType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */) &&
74553                 nextType.flags & (1 /* Any */ | 131072 /* Never */ | 2 /* Unknown */ | 16384 /* Void */ | 32768 /* Undefined */)) {
74554                 var id = getTypeListId([yieldType, returnType, nextType]);
74555                 var iterationTypes = iterationTypesCache.get(id);
74556                 if (!iterationTypes) {
74557                     iterationTypes = { yieldType: yieldType, returnType: returnType, nextType: nextType };
74558                     iterationTypesCache.set(id, iterationTypes);
74559                 }
74560                 return iterationTypes;
74561             }
74562             return { yieldType: yieldType, returnType: returnType, nextType: nextType };
74563         }
74564         /**
74565          * Combines multiple `IterationTypes` records.
74566          *
74567          * If `array` is empty or all elements are missing or are references to `noIterationTypes`,
74568          * then `noIterationTypes` is returned. Otherwise, an `IterationTypes` record is returned
74569          * for the combined iteration types.
74570          */
74571         function combineIterationTypes(array) {
74572             var yieldTypes;
74573             var returnTypes;
74574             var nextTypes;
74575             for (var _i = 0, array_10 = array; _i < array_10.length; _i++) {
74576                 var iterationTypes = array_10[_i];
74577                 if (iterationTypes === undefined || iterationTypes === noIterationTypes) {
74578                     continue;
74579                 }
74580                 if (iterationTypes === anyIterationTypes) {
74581                     return anyIterationTypes;
74582                 }
74583                 yieldTypes = ts.append(yieldTypes, iterationTypes.yieldType);
74584                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
74585                 nextTypes = ts.append(nextTypes, iterationTypes.nextType);
74586             }
74587             if (yieldTypes || returnTypes || nextTypes) {
74588                 return createIterationTypes(yieldTypes && getUnionType(yieldTypes), returnTypes && getUnionType(returnTypes), nextTypes && getIntersectionType(nextTypes));
74589             }
74590             return noIterationTypes;
74591         }
74592         function getCachedIterationTypes(type, cacheKey) {
74593             return type[cacheKey];
74594         }
74595         function setCachedIterationTypes(type, cacheKey, cachedTypes) {
74596             return type[cacheKey] = cachedTypes;
74597         }
74598         /**
74599          * Gets the *yield*, *return*, and *next* types from an `Iterable`-like or `AsyncIterable`-like type.
74600          *
74601          * At every level that involves analyzing return types of signatures, we union the return types of all the signatures.
74602          *
74603          * Another thing to note is that at any step of this process, we could run into a dead end,
74604          * meaning either the property is missing, or we run into the anyType. If either of these things
74605          * happens, we return `undefined` to signal that we could not find the iteration type. If a property
74606          * is missing, and the previous step did not result in `any`, then we also give an error if the
74607          * caller requested it. Then the caller can decide what to do in the case where there is no iterated
74608          * type.
74609          *
74610          * For a **for-of** statement, `yield*` (in a normal generator), spread, array
74611          * destructuring, or normal generator we will only ever look for a `[Symbol.iterator]()`
74612          * method.
74613          *
74614          * For an async generator we will only ever look at the `[Symbol.asyncIterator]()` method.
74615          *
74616          * For a **for-await-of** statement or a `yield*` in an async generator we will look for
74617          * the `[Symbol.asyncIterator]()` method first, and then the `[Symbol.iterator]()` method.
74618          */
74619         function getIterationTypesOfIterable(type, use, errorNode) {
74620             if (isTypeAny(type)) {
74621                 return anyIterationTypes;
74622             }
74623             if (!(type.flags & 1048576 /* Union */)) {
74624                 var iterationTypes_1 = getIterationTypesOfIterableWorker(type, use, errorNode);
74625                 if (iterationTypes_1 === noIterationTypes) {
74626                     if (errorNode) {
74627                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
74628                     }
74629                     return undefined;
74630                 }
74631                 return iterationTypes_1;
74632             }
74633             var cacheKey = use & 2 /* AllowsAsyncIterablesFlag */ ? "iterationTypesOfAsyncIterable" : "iterationTypesOfIterable";
74634             var cachedTypes = getCachedIterationTypes(type, cacheKey);
74635             if (cachedTypes)
74636                 return cachedTypes === noIterationTypes ? undefined : cachedTypes;
74637             var allIterationTypes;
74638             for (var _i = 0, _a = type.types; _i < _a.length; _i++) {
74639                 var constituent = _a[_i];
74640                 var iterationTypes_2 = getIterationTypesOfIterableWorker(constituent, use, errorNode);
74641                 if (iterationTypes_2 === noIterationTypes) {
74642                     if (errorNode) {
74643                         reportTypeNotIterableError(errorNode, type, !!(use & 2 /* AllowsAsyncIterablesFlag */));
74644                     }
74645                     setCachedIterationTypes(type, cacheKey, noIterationTypes);
74646                     return undefined;
74647                 }
74648                 else {
74649                     allIterationTypes = ts.append(allIterationTypes, iterationTypes_2);
74650                 }
74651             }
74652             var iterationTypes = allIterationTypes ? combineIterationTypes(allIterationTypes) : noIterationTypes;
74653             setCachedIterationTypes(type, cacheKey, iterationTypes);
74654             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
74655         }
74656         function getAsyncFromSyncIterationTypes(iterationTypes, errorNode) {
74657             if (iterationTypes === noIterationTypes)
74658                 return noIterationTypes;
74659             if (iterationTypes === anyIterationTypes)
74660                 return anyIterationTypes;
74661             var yieldType = iterationTypes.yieldType, returnType = iterationTypes.returnType, nextType = iterationTypes.nextType;
74662             return createIterationTypes(getAwaitedType(yieldType, errorNode) || anyType, getAwaitedType(returnType, errorNode) || anyType, nextType);
74663         }
74664         /**
74665          * Gets the *yield*, *return*, and *next* types from a non-union type.
74666          *
74667          * If we are unable to find the *yield*, *return*, and *next* types, `noIterationTypes` is
74668          * returned to indicate to the caller that it should report an error. Otherwise, an
74669          * `IterationTypes` record is returned.
74670          *
74671          * NOTE: You probably don't want to call this directly and should be calling
74672          * `getIterationTypesOfIterable` instead.
74673          */
74674         function getIterationTypesOfIterableWorker(type, use, errorNode) {
74675             if (isTypeAny(type)) {
74676                 return anyIterationTypes;
74677             }
74678             if (use & 2 /* AllowsAsyncIterablesFlag */) {
74679                 var iterationTypes = getIterationTypesOfIterableCached(type, asyncIterationTypesResolver) ||
74680                     getIterationTypesOfIterableFast(type, asyncIterationTypesResolver);
74681                 if (iterationTypes) {
74682                     return iterationTypes;
74683                 }
74684             }
74685             if (use & 1 /* AllowsSyncIterablesFlag */) {
74686                 var iterationTypes = getIterationTypesOfIterableCached(type, syncIterationTypesResolver) ||
74687                     getIterationTypesOfIterableFast(type, syncIterationTypesResolver);
74688                 if (iterationTypes) {
74689                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
74690                         // for a sync iterable in an async context, only use the cached types if they are valid.
74691                         if (iterationTypes !== noIterationTypes) {
74692                             return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", getAsyncFromSyncIterationTypes(iterationTypes, errorNode));
74693                         }
74694                     }
74695                     else {
74696                         return iterationTypes;
74697                     }
74698                 }
74699             }
74700             if (use & 2 /* AllowsAsyncIterablesFlag */) {
74701                 var iterationTypes = getIterationTypesOfIterableSlow(type, asyncIterationTypesResolver, errorNode);
74702                 if (iterationTypes !== noIterationTypes) {
74703                     return iterationTypes;
74704                 }
74705             }
74706             if (use & 1 /* AllowsSyncIterablesFlag */) {
74707                 var iterationTypes = getIterationTypesOfIterableSlow(type, syncIterationTypesResolver, errorNode);
74708                 if (iterationTypes !== noIterationTypes) {
74709                     if (use & 2 /* AllowsAsyncIterablesFlag */) {
74710                         return setCachedIterationTypes(type, "iterationTypesOfAsyncIterable", iterationTypes
74711                             ? getAsyncFromSyncIterationTypes(iterationTypes, errorNode)
74712                             : noIterationTypes);
74713                     }
74714                     else {
74715                         return iterationTypes;
74716                     }
74717                 }
74718             }
74719             return noIterationTypes;
74720         }
74721         /**
74722          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or
74723          * `AsyncIterable`-like type from the cache.
74724          *
74725          * NOTE: You probably don't want to call this directly and should be calling
74726          * `getIterationTypesOfIterable` instead.
74727          */
74728         function getIterationTypesOfIterableCached(type, resolver) {
74729             return getCachedIterationTypes(type, resolver.iterableCacheKey);
74730         }
74731         function getIterationTypesOfGlobalIterableType(globalType, resolver) {
74732             var globalIterationTypes = getIterationTypesOfIterableCached(globalType, resolver) ||
74733                 getIterationTypesOfIterableSlow(globalType, resolver, /*errorNode*/ undefined);
74734             return globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes;
74735         }
74736         /**
74737          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
74738          * type from from common heuristics.
74739          *
74740          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
74741          * returned. If we found iteration types, an `IterationTypes` record is returned.
74742          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
74743          * exhaustive analysis.
74744          *
74745          * NOTE: You probably don't want to call this directly and should be calling
74746          * `getIterationTypesOfIterable` instead.
74747          */
74748         function getIterationTypesOfIterableFast(type, resolver) {
74749             // As an optimization, if the type is an instantiation of one of the following global types, then
74750             // just grab its related type argument:
74751             // - `Iterable<T>` or `AsyncIterable<T>`
74752             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
74753             var globalType;
74754             if (isReferenceToType(type, globalType = resolver.getGlobalIterableType(/*reportErrors*/ false)) ||
74755                 isReferenceToType(type, globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false))) {
74756                 var yieldType = getTypeArguments(type)[0];
74757                 // The "return" and "next" types of `Iterable` and `IterableIterator` are defined by the
74758                 // iteration types of their `[Symbol.iterator]()` method. The same is true for their async cousins.
74759                 // While we define these as `any` and `undefined` in our libs by default, a custom lib *could* use
74760                 // different definitions.
74761                 var _a = getIterationTypesOfGlobalIterableType(globalType, resolver), returnType = _a.returnType, nextType = _a.nextType;
74762                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
74763             }
74764             // As an optimization, if the type is an instantiation of the following global type, then
74765             // just grab its related type arguments:
74766             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
74767             if (isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
74768                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
74769                 return setCachedIterationTypes(type, resolver.iterableCacheKey, createIterationTypes(yieldType, returnType, nextType));
74770             }
74771         }
74772         /**
74773          * Gets the *yield*, *return*, and *next* types of an `Iterable`-like or `AsyncIterable`-like
74774          * type from its members.
74775          *
74776          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
74777          * record is returned. Otherwise, `noIterationTypes` is returned.
74778          *
74779          * NOTE: You probably don't want to call this directly and should be calling
74780          * `getIterationTypesOfIterable` instead.
74781          */
74782         function getIterationTypesOfIterableSlow(type, resolver, errorNode) {
74783             var _a;
74784             var method = getPropertyOfType(type, ts.getPropertyNameForKnownSymbolName(resolver.iteratorSymbolName));
74785             var methodType = method && !(method.flags & 16777216 /* Optional */) ? getTypeOfSymbol(method) : undefined;
74786             if (isTypeAny(methodType)) {
74787                 return setCachedIterationTypes(type, resolver.iterableCacheKey, anyIterationTypes);
74788             }
74789             var signatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : undefined;
74790             if (!ts.some(signatures)) {
74791                 return setCachedIterationTypes(type, resolver.iterableCacheKey, noIterationTypes);
74792             }
74793             var iteratorType = getIntersectionType(ts.map(signatures, getReturnTypeOfSignature));
74794             var iterationTypes = (_a = getIterationTypesOfIterator(iteratorType, resolver, errorNode)) !== null && _a !== void 0 ? _a : noIterationTypes;
74795             return setCachedIterationTypes(type, resolver.iterableCacheKey, iterationTypes);
74796         }
74797         function reportTypeNotIterableError(errorNode, type, allowAsyncIterables) {
74798             var message = allowAsyncIterables
74799                 ? ts.Diagnostics.Type_0_must_have_a_Symbol_asyncIterator_method_that_returns_an_async_iterator
74800                 : ts.Diagnostics.Type_0_must_have_a_Symbol_iterator_method_that_returns_an_iterator;
74801             errorAndMaybeSuggestAwait(errorNode, !!getAwaitedTypeOfPromise(type), message, typeToString(type));
74802         }
74803         /**
74804          * Gets the *yield*, *return*, and *next* types from an `Iterator`-like or `AsyncIterator`-like type.
74805          *
74806          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
74807          * record is returned. Otherwise, `undefined` is returned.
74808          */
74809         function getIterationTypesOfIterator(type, resolver, errorNode) {
74810             if (isTypeAny(type)) {
74811                 return anyIterationTypes;
74812             }
74813             var iterationTypes = getIterationTypesOfIteratorCached(type, resolver) ||
74814                 getIterationTypesOfIteratorFast(type, resolver) ||
74815                 getIterationTypesOfIteratorSlow(type, resolver, errorNode);
74816             return iterationTypes === noIterationTypes ? undefined : iterationTypes;
74817         }
74818         /**
74819          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
74820          * cache.
74821          *
74822          * NOTE: You probably don't want to call this directly and should be calling
74823          * `getIterationTypesOfIterator` instead.
74824          */
74825         function getIterationTypesOfIteratorCached(type, resolver) {
74826             return getCachedIterationTypes(type, resolver.iteratorCacheKey);
74827         }
74828         /**
74829          * Gets the iteration types of an `Iterator`-like or `AsyncIterator`-like type from the
74830          * cache or from common heuristics.
74831          *
74832          * If we previously analyzed this type and found no iteration types, `noIterationTypes` is
74833          * returned. If we found iteration types, an `IterationTypes` record is returned.
74834          * Otherwise, we return `undefined` to indicate to the caller it should perform a more
74835          * exhaustive analysis.
74836          *
74837          * NOTE: You probably don't want to call this directly and should be calling
74838          * `getIterationTypesOfIterator` instead.
74839          */
74840         function getIterationTypesOfIteratorFast(type, resolver) {
74841             // As an optimization, if the type is an instantiation of one of the following global types,
74842             // then just grab its related type argument:
74843             // - `IterableIterator<T>` or `AsyncIterableIterator<T>`
74844             // - `Iterator<T, TReturn, TNext>` or `AsyncIterator<T, TReturn, TNext>`
74845             // - `Generator<T, TReturn, TNext>` or `AsyncGenerator<T, TReturn, TNext>`
74846             var globalType = resolver.getGlobalIterableIteratorType(/*reportErrors*/ false);
74847             if (isReferenceToType(type, globalType)) {
74848                 var yieldType = getTypeArguments(type)[0];
74849                 // The "return" and "next" types of `IterableIterator` and `AsyncIterableIterator` are defined by the
74850                 // iteration types of their `next`, `return`, and `throw` methods. While we define these as `any`
74851                 // and `undefined` in our libs by default, a custom lib *could* use different definitions.
74852                 var globalIterationTypes = getIterationTypesOfIteratorCached(globalType, resolver) ||
74853                     getIterationTypesOfIteratorSlow(globalType, resolver, /*errorNode*/ undefined);
74854                 var _a = globalIterationTypes === noIterationTypes ? defaultIterationTypes : globalIterationTypes, returnType = _a.returnType, nextType = _a.nextType;
74855                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
74856             }
74857             if (isReferenceToType(type, resolver.getGlobalIteratorType(/*reportErrors*/ false)) ||
74858                 isReferenceToType(type, resolver.getGlobalGeneratorType(/*reportErrors*/ false))) {
74859                 var _b = getTypeArguments(type), yieldType = _b[0], returnType = _b[1], nextType = _b[2];
74860                 return setCachedIterationTypes(type, resolver.iteratorCacheKey, createIterationTypes(yieldType, returnType, nextType));
74861             }
74862         }
74863         function isIteratorResult(type, kind) {
74864             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface:
74865             // > [done] is the result status of an iterator `next` method call. If the end of the iterator was reached `done` is `true`.
74866             // > If the end was not reached `done` is `false` and a value is available.
74867             // > If a `done` property (either own or inherited) does not exist, it is consider to have the value `false`.
74868             var doneType = getTypeOfPropertyOfType(type, "done") || falseType;
74869             return isTypeAssignableTo(kind === 0 /* Yield */ ? falseType : trueType, doneType);
74870         }
74871         function isYieldIteratorResult(type) {
74872             return isIteratorResult(type, 0 /* Yield */);
74873         }
74874         function isReturnIteratorResult(type) {
74875             return isIteratorResult(type, 1 /* Return */);
74876         }
74877         /**
74878          * Gets the *yield* and *return* types of an `IteratorResult`-like type.
74879          *
74880          * If we are unable to determine a *yield* or a *return* type, `noIterationTypes` is
74881          * returned to indicate to the caller that it should handle the error. Otherwise, an
74882          * `IterationTypes` record is returned.
74883          */
74884         function getIterationTypesOfIteratorResult(type) {
74885             if (isTypeAny(type)) {
74886                 return anyIterationTypes;
74887             }
74888             var cachedTypes = getCachedIterationTypes(type, "iterationTypesOfIteratorResult");
74889             if (cachedTypes) {
74890                 return cachedTypes;
74891             }
74892             // As an optimization, if the type is an instantiation of one of the global `IteratorYieldResult<T>`
74893             // or `IteratorReturnResult<TReturn>` types, then just grab its type argument.
74894             if (isReferenceToType(type, getGlobalIteratorYieldResultType(/*reportErrors*/ false))) {
74895                 var yieldType_1 = getTypeArguments(type)[0];
74896                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType_1, /*returnType*/ undefined, /*nextType*/ undefined));
74897             }
74898             if (isReferenceToType(type, getGlobalIteratorReturnResultType(/*reportErrors*/ false))) {
74899                 var returnType_1 = getTypeArguments(type)[0];
74900                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(/*yieldType*/ undefined, returnType_1, /*nextType*/ undefined));
74901             }
74902             // Choose any constituents that can produce the requested iteration type.
74903             var yieldIteratorResult = filterType(type, isYieldIteratorResult);
74904             var yieldType = yieldIteratorResult !== neverType ? getTypeOfPropertyOfType(yieldIteratorResult, "value") : undefined;
74905             var returnIteratorResult = filterType(type, isReturnIteratorResult);
74906             var returnType = returnIteratorResult !== neverType ? getTypeOfPropertyOfType(returnIteratorResult, "value") : undefined;
74907             if (!yieldType && !returnType) {
74908                 return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", noIterationTypes);
74909             }
74910             // From https://tc39.github.io/ecma262/#sec-iteratorresult-interface
74911             // > ... If the iterator does not have a return value, `value` is `undefined`. In that case, the
74912             // > `value` property may be absent from the conforming object if it does not inherit an explicit
74913             // > `value` property.
74914             return setCachedIterationTypes(type, "iterationTypesOfIteratorResult", createIterationTypes(yieldType, returnType || voidType, /*nextType*/ undefined));
74915         }
74916         /**
74917          * Gets the *yield*, *return*, and *next* types of a the `next()`, `return()`, or
74918          * `throw()` method of an `Iterator`-like or `AsyncIterator`-like type.
74919          *
74920          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
74921          * record is returned. Otherwise, we return `undefined`.
74922          */
74923         function getIterationTypesOfMethod(type, resolver, methodName, errorNode) {
74924             var _a, _b, _c, _d;
74925             var method = getPropertyOfType(type, methodName);
74926             // Ignore 'return' or 'throw' if they are missing.
74927             if (!method && methodName !== "next") {
74928                 return undefined;
74929             }
74930             var methodType = method && !(methodName === "next" && (method.flags & 16777216 /* Optional */))
74931                 ? methodName === "next" ? getTypeOfSymbol(method) : getTypeWithFacts(getTypeOfSymbol(method), 2097152 /* NEUndefinedOrNull */)
74932                 : undefined;
74933             if (isTypeAny(methodType)) {
74934                 // `return()` and `throw()` don't provide a *next* type.
74935                 return methodName === "next" ? anyIterationTypes : anyIterationTypesExceptNext;
74936             }
74937             // Both async and non-async iterators *must* have a `next` method.
74938             var methodSignatures = methodType ? getSignaturesOfType(methodType, 0 /* Call */) : ts.emptyArray;
74939             if (methodSignatures.length === 0) {
74940                 if (errorNode) {
74941                     var diagnostic = methodName === "next"
74942                         ? resolver.mustHaveANextMethodDiagnostic
74943                         : resolver.mustBeAMethodDiagnostic;
74944                     error(errorNode, diagnostic, methodName);
74945                 }
74946                 return methodName === "next" ? anyIterationTypes : undefined;
74947             }
74948             // If the method signature comes exclusively from the global iterator or generator type,
74949             // create iteration types from its type arguments like `getIterationTypesOfIteratorFast`
74950             // does (so as to remove `undefined` from the next and return types). We arrive here when
74951             // a contextual type for a generator was not a direct reference to one of those global types,
74952             // but looking up `methodType` referred to one of them (and nothing else). E.g., in
74953             // `interface SpecialIterator extends Iterator<number> {}`, `SpecialIterator` is not a
74954             // reference to `Iterator`, but its `next` member derives exclusively from `Iterator`.
74955             if ((methodType === null || methodType === void 0 ? void 0 : methodType.symbol) && methodSignatures.length === 1) {
74956                 var globalGeneratorType = resolver.getGlobalGeneratorType(/*reportErrors*/ false);
74957                 var globalIteratorType = resolver.getGlobalIteratorType(/*reportErrors*/ false);
74958                 var isGeneratorMethod = ((_b = (_a = globalGeneratorType.symbol) === null || _a === void 0 ? void 0 : _a.members) === null || _b === void 0 ? void 0 : _b.get(methodName)) === methodType.symbol;
74959                 var isIteratorMethod = !isGeneratorMethod && ((_d = (_c = globalIteratorType.symbol) === null || _c === void 0 ? void 0 : _c.members) === null || _d === void 0 ? void 0 : _d.get(methodName)) === methodType.symbol;
74960                 if (isGeneratorMethod || isIteratorMethod) {
74961                     var globalType = isGeneratorMethod ? globalGeneratorType : globalIteratorType;
74962                     var mapper = methodType.mapper;
74963                     return createIterationTypes(getMappedType(globalType.typeParameters[0], mapper), getMappedType(globalType.typeParameters[1], mapper), methodName === "next" ? getMappedType(globalType.typeParameters[2], mapper) : undefined);
74964                 }
74965             }
74966             // Extract the first parameter and return type of each signature.
74967             var methodParameterTypes;
74968             var methodReturnTypes;
74969             for (var _i = 0, methodSignatures_1 = methodSignatures; _i < methodSignatures_1.length; _i++) {
74970                 var signature = methodSignatures_1[_i];
74971                 if (methodName !== "throw" && ts.some(signature.parameters)) {
74972                     methodParameterTypes = ts.append(methodParameterTypes, getTypeAtPosition(signature, 0));
74973                 }
74974                 methodReturnTypes = ts.append(methodReturnTypes, getReturnTypeOfSignature(signature));
74975             }
74976             // Resolve the *next* or *return* type from the first parameter of a `next()` or
74977             // `return()` method, respectively.
74978             var returnTypes;
74979             var nextType;
74980             if (methodName !== "throw") {
74981                 var methodParameterType = methodParameterTypes ? getUnionType(methodParameterTypes) : unknownType;
74982                 if (methodName === "next") {
74983                     // The value of `next(value)` is *not* awaited by async generators
74984                     nextType = methodParameterType;
74985                 }
74986                 else if (methodName === "return") {
74987                     // The value of `return(value)` *is* awaited by async generators
74988                     var resolvedMethodParameterType = resolver.resolveIterationType(methodParameterType, errorNode) || anyType;
74989                     returnTypes = ts.append(returnTypes, resolvedMethodParameterType);
74990                 }
74991             }
74992             // Resolve the *yield* and *return* types from the return type of the method (i.e. `IteratorResult`)
74993             var yieldType;
74994             var methodReturnType = methodReturnTypes ? getIntersectionType(methodReturnTypes) : neverType;
74995             var resolvedMethodReturnType = resolver.resolveIterationType(methodReturnType, errorNode) || anyType;
74996             var iterationTypes = getIterationTypesOfIteratorResult(resolvedMethodReturnType);
74997             if (iterationTypes === noIterationTypes) {
74998                 if (errorNode) {
74999                     error(errorNode, resolver.mustHaveAValueDiagnostic, methodName);
75000                 }
75001                 yieldType = anyType;
75002                 returnTypes = ts.append(returnTypes, anyType);
75003             }
75004             else {
75005                 yieldType = iterationTypes.yieldType;
75006                 returnTypes = ts.append(returnTypes, iterationTypes.returnType);
75007             }
75008             return createIterationTypes(yieldType, getUnionType(returnTypes), nextType);
75009         }
75010         /**
75011          * Gets the *yield*, *return*, and *next* types of an `Iterator`-like or `AsyncIterator`-like
75012          * type from its members.
75013          *
75014          * If we successfully found the *yield*, *return*, and *next* types, an `IterationTypes`
75015          * record is returned. Otherwise, `noIterationTypes` is returned.
75016          *
75017          * NOTE: You probably don't want to call this directly and should be calling
75018          * `getIterationTypesOfIterator` instead.
75019          */
75020         function getIterationTypesOfIteratorSlow(type, resolver, errorNode) {
75021             var iterationTypes = combineIterationTypes([
75022                 getIterationTypesOfMethod(type, resolver, "next", errorNode),
75023                 getIterationTypesOfMethod(type, resolver, "return", errorNode),
75024                 getIterationTypesOfMethod(type, resolver, "throw", errorNode),
75025             ]);
75026             return setCachedIterationTypes(type, resolver.iteratorCacheKey, iterationTypes);
75027         }
75028         /**
75029          * Gets the requested "iteration type" from a type that is either `Iterable`-like, `Iterator`-like,
75030          * `IterableIterator`-like, or `Generator`-like (for a non-async generator); or `AsyncIterable`-like,
75031          * `AsyncIterator`-like, `AsyncIterableIterator`-like, or `AsyncGenerator`-like (for an async generator).
75032          */
75033         function getIterationTypeOfGeneratorFunctionReturnType(kind, returnType, isAsyncGenerator) {
75034             if (isTypeAny(returnType)) {
75035                 return undefined;
75036             }
75037             var iterationTypes = getIterationTypesOfGeneratorFunctionReturnType(returnType, isAsyncGenerator);
75038             return iterationTypes && iterationTypes[getIterationTypesKeyFromIterationTypeKind(kind)];
75039         }
75040         function getIterationTypesOfGeneratorFunctionReturnType(type, isAsyncGenerator) {
75041             if (isTypeAny(type)) {
75042                 return anyIterationTypes;
75043             }
75044             var use = isAsyncGenerator ? 2 /* AsyncGeneratorReturnType */ : 1 /* GeneratorReturnType */;
75045             var resolver = isAsyncGenerator ? asyncIterationTypesResolver : syncIterationTypesResolver;
75046             return getIterationTypesOfIterable(type, use, /*errorNode*/ undefined) ||
75047                 getIterationTypesOfIterator(type, resolver, /*errorNode*/ undefined);
75048         }
75049         function checkBreakOrContinueStatement(node) {
75050             // Grammar checking
75051             if (!checkGrammarStatementInAmbientContext(node))
75052                 checkGrammarBreakOrContinueStatement(node);
75053             // TODO: Check that target label is valid
75054         }
75055         function unwrapReturnType(returnType, functionFlags) {
75056             var _a, _b;
75057             var isGenerator = !!(functionFlags & 1 /* Generator */);
75058             var isAsync = !!(functionFlags & 2 /* Async */);
75059             return isGenerator ? (_a = getIterationTypeOfGeneratorFunctionReturnType(1 /* Return */, returnType, isAsync)) !== null && _a !== void 0 ? _a : errorType :
75060                 isAsync ? (_b = getAwaitedType(returnType)) !== null && _b !== void 0 ? _b : errorType :
75061                     returnType;
75062         }
75063         function isUnwrappedReturnTypeVoidOrAny(func, returnType) {
75064             var unwrappedReturnType = unwrapReturnType(returnType, ts.getFunctionFlags(func));
75065             return !!unwrappedReturnType && maybeTypeOfKind(unwrappedReturnType, 16384 /* Void */ | 3 /* AnyOrUnknown */);
75066         }
75067         function checkReturnStatement(node) {
75068             var _a;
75069             // Grammar checking
75070             if (checkGrammarStatementInAmbientContext(node)) {
75071                 return;
75072             }
75073             var func = ts.getContainingFunction(node);
75074             if (!func) {
75075                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_return_statement_can_only_be_used_within_a_function_body);
75076                 return;
75077             }
75078             var signature = getSignatureFromDeclaration(func);
75079             var returnType = getReturnTypeOfSignature(signature);
75080             var functionFlags = ts.getFunctionFlags(func);
75081             if (strictNullChecks || node.expression || returnType.flags & 131072 /* Never */) {
75082                 var exprType = node.expression ? checkExpressionCached(node.expression) : undefinedType;
75083                 if (func.kind === 168 /* SetAccessor */) {
75084                     if (node.expression) {
75085                         error(node, ts.Diagnostics.Setters_cannot_return_a_value);
75086                     }
75087                 }
75088                 else if (func.kind === 166 /* Constructor */) {
75089                     if (node.expression && !checkTypeAssignableToAndOptionallyElaborate(exprType, returnType, node, node.expression)) {
75090                         error(node, ts.Diagnostics.Return_type_of_constructor_signature_must_be_assignable_to_the_instance_type_of_the_class);
75091                     }
75092                 }
75093                 else if (getReturnTypeFromAnnotation(func)) {
75094                     var unwrappedReturnType = (_a = unwrapReturnType(returnType, functionFlags)) !== null && _a !== void 0 ? _a : returnType;
75095                     var unwrappedExprType = functionFlags & 2 /* Async */
75096                         ? 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)
75097                         : exprType;
75098                     if (unwrappedReturnType) {
75099                         // If the function has a return type, but promisedType is
75100                         // undefined, an error will be reported in checkAsyncFunctionReturnType
75101                         // so we don't need to report one here.
75102                         checkTypeAssignableToAndOptionallyElaborate(unwrappedExprType, unwrappedReturnType, node, node.expression);
75103                     }
75104                 }
75105             }
75106             else if (func.kind !== 166 /* Constructor */ && compilerOptions.noImplicitReturns && !isUnwrappedReturnTypeVoidOrAny(func, returnType)) {
75107                 // The function has a return type, but the return statement doesn't have an expression.
75108                 error(node, ts.Diagnostics.Not_all_code_paths_return_a_value);
75109             }
75110         }
75111         function checkWithStatement(node) {
75112             // Grammar checking for withStatement
75113             if (!checkGrammarStatementInAmbientContext(node)) {
75114                 if (node.flags & 32768 /* AwaitContext */) {
75115                     grammarErrorOnFirstToken(node, ts.Diagnostics.with_statements_are_not_allowed_in_an_async_function_block);
75116                 }
75117             }
75118             checkExpression(node.expression);
75119             var sourceFile = ts.getSourceFileOfNode(node);
75120             if (!hasParseDiagnostics(sourceFile)) {
75121                 var start = ts.getSpanOfTokenAtPosition(sourceFile, node.pos).start;
75122                 var end = node.statement.pos;
75123                 grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.The_with_statement_is_not_supported_All_symbols_in_a_with_block_will_have_type_any);
75124             }
75125         }
75126         function checkSwitchStatement(node) {
75127             // Grammar checking
75128             checkGrammarStatementInAmbientContext(node);
75129             var firstDefaultClause;
75130             var hasDuplicateDefaultClause = false;
75131             var expressionType = checkExpression(node.expression);
75132             var expressionIsLiteral = isLiteralType(expressionType);
75133             ts.forEach(node.caseBlock.clauses, function (clause) {
75134                 // Grammar check for duplicate default clauses, skip if we already report duplicate default clause
75135                 if (clause.kind === 285 /* DefaultClause */ && !hasDuplicateDefaultClause) {
75136                     if (firstDefaultClause === undefined) {
75137                         firstDefaultClause = clause;
75138                     }
75139                     else {
75140                         grammarErrorOnNode(clause, ts.Diagnostics.A_default_clause_cannot_appear_more_than_once_in_a_switch_statement);
75141                         hasDuplicateDefaultClause = true;
75142                     }
75143                 }
75144                 if (produceDiagnostics && clause.kind === 284 /* CaseClause */) {
75145                     // TypeScript 1.0 spec (April 2014): 5.9
75146                     // In a 'switch' statement, each 'case' expression must be of a type that is comparable
75147                     // to or from the type of the 'switch' expression.
75148                     var caseType = checkExpression(clause.expression);
75149                     var caseIsLiteral = isLiteralType(caseType);
75150                     var comparedExpressionType = expressionType;
75151                     if (!caseIsLiteral || !expressionIsLiteral) {
75152                         caseType = caseIsLiteral ? getBaseTypeOfLiteralType(caseType) : caseType;
75153                         comparedExpressionType = getBaseTypeOfLiteralType(expressionType);
75154                     }
75155                     if (!isTypeEqualityComparableTo(comparedExpressionType, caseType)) {
75156                         // expressionType is not comparable to caseType, try the reversed check and report errors if it fails
75157                         checkTypeComparableTo(caseType, comparedExpressionType, clause.expression, /*headMessage*/ undefined);
75158                     }
75159                 }
75160                 ts.forEach(clause.statements, checkSourceElement);
75161                 if (compilerOptions.noFallthroughCasesInSwitch && clause.fallthroughFlowNode && isReachableFlowNode(clause.fallthroughFlowNode)) {
75162                     error(clause, ts.Diagnostics.Fallthrough_case_in_switch);
75163                 }
75164             });
75165             if (node.caseBlock.locals) {
75166                 registerForUnusedIdentifiersCheck(node.caseBlock);
75167             }
75168         }
75169         function checkLabeledStatement(node) {
75170             // Grammar checking
75171             if (!checkGrammarStatementInAmbientContext(node)) {
75172                 ts.findAncestor(node.parent, function (current) {
75173                     if (ts.isFunctionLike(current)) {
75174                         return "quit";
75175                     }
75176                     if (current.kind === 245 /* LabeledStatement */ && current.label.escapedText === node.label.escapedText) {
75177                         grammarErrorOnNode(node.label, ts.Diagnostics.Duplicate_label_0, ts.getTextOfNode(node.label));
75178                         return true;
75179                     }
75180                     return false;
75181                 });
75182             }
75183             // ensure that label is unique
75184             checkSourceElement(node.statement);
75185         }
75186         function checkThrowStatement(node) {
75187             // Grammar checking
75188             if (!checkGrammarStatementInAmbientContext(node)) {
75189                 if (ts.isIdentifier(node.expression) && !node.expression.escapedText) {
75190                     grammarErrorAfterFirstToken(node, ts.Diagnostics.Line_break_not_permitted_here);
75191                 }
75192             }
75193             if (node.expression) {
75194                 checkExpression(node.expression);
75195             }
75196         }
75197         function checkTryStatement(node) {
75198             // Grammar checking
75199             checkGrammarStatementInAmbientContext(node);
75200             checkBlock(node.tryBlock);
75201             var catchClause = node.catchClause;
75202             if (catchClause) {
75203                 // Grammar checking
75204                 if (catchClause.variableDeclaration) {
75205                     var declaration = catchClause.variableDeclaration;
75206                     if (declaration.type) {
75207                         var type = getTypeForVariableLikeDeclaration(declaration, /*includeOptionality*/ false);
75208                         if (type && !(type.flags & 3 /* AnyOrUnknown */)) {
75209                             grammarErrorOnFirstToken(declaration.type, ts.Diagnostics.Catch_clause_variable_type_annotation_must_be_any_or_unknown_if_specified);
75210                         }
75211                     }
75212                     else if (declaration.initializer) {
75213                         grammarErrorOnFirstToken(declaration.initializer, ts.Diagnostics.Catch_clause_variable_cannot_have_an_initializer);
75214                     }
75215                     else {
75216                         var blockLocals_1 = catchClause.block.locals;
75217                         if (blockLocals_1) {
75218                             ts.forEachKey(catchClause.locals, function (caughtName) {
75219                                 var blockLocal = blockLocals_1.get(caughtName);
75220                                 if (blockLocal && (blockLocal.flags & 2 /* BlockScopedVariable */) !== 0) {
75221                                     grammarErrorOnNode(blockLocal.valueDeclaration, ts.Diagnostics.Cannot_redeclare_identifier_0_in_catch_clause, caughtName);
75222                                 }
75223                             });
75224                         }
75225                     }
75226                 }
75227                 checkBlock(catchClause.block);
75228             }
75229             if (node.finallyBlock) {
75230                 checkBlock(node.finallyBlock);
75231             }
75232         }
75233         function checkIndexConstraints(type) {
75234             var declaredNumberIndexer = getIndexDeclarationOfSymbol(type.symbol, 1 /* Number */);
75235             var declaredStringIndexer = getIndexDeclarationOfSymbol(type.symbol, 0 /* String */);
75236             var stringIndexType = getIndexTypeOfType(type, 0 /* String */);
75237             var numberIndexType = getIndexTypeOfType(type, 1 /* Number */);
75238             if (stringIndexType || numberIndexType) {
75239                 ts.forEach(getPropertiesOfObjectType(type), function (prop) {
75240                     var propType = getTypeOfSymbol(prop);
75241                     checkIndexConstraintForProperty(prop, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
75242                     checkIndexConstraintForProperty(prop, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
75243                 });
75244                 var classDeclaration = type.symbol.valueDeclaration;
75245                 if (ts.getObjectFlags(type) & 1 /* Class */ && ts.isClassLike(classDeclaration)) {
75246                     for (var _i = 0, _a = classDeclaration.members; _i < _a.length; _i++) {
75247                         var member = _a[_i];
75248                         // Only process instance properties with computed names here.
75249                         // Static properties cannot be in conflict with indexers,
75250                         // and properties with literal names were already checked.
75251                         if (!ts.hasSyntacticModifier(member, 32 /* Static */) && hasNonBindableDynamicName(member)) {
75252                             var symbol = getSymbolOfNode(member);
75253                             var propType = getTypeOfSymbol(symbol);
75254                             checkIndexConstraintForProperty(symbol, propType, type, declaredStringIndexer, stringIndexType, 0 /* String */);
75255                             checkIndexConstraintForProperty(symbol, propType, type, declaredNumberIndexer, numberIndexType, 1 /* Number */);
75256                         }
75257                     }
75258                 }
75259             }
75260             var errorNode;
75261             if (stringIndexType && numberIndexType) {
75262                 errorNode = declaredNumberIndexer || declaredStringIndexer;
75263                 // condition 'errorNode === undefined' may appear if types does not declare nor string neither number indexer
75264                 if (!errorNode && (ts.getObjectFlags(type) & 2 /* Interface */)) {
75265                     var someBaseTypeHasBothIndexers = ts.forEach(getBaseTypes(type), function (base) { return getIndexTypeOfType(base, 0 /* String */) && getIndexTypeOfType(base, 1 /* Number */); });
75266                     errorNode = someBaseTypeHasBothIndexers ? undefined : type.symbol.declarations[0];
75267                 }
75268             }
75269             if (errorNode && !isTypeAssignableTo(numberIndexType, stringIndexType)) { // TODO: GH#18217
75270                 error(errorNode, ts.Diagnostics.Numeric_index_type_0_is_not_assignable_to_string_index_type_1, typeToString(numberIndexType), typeToString(stringIndexType));
75271             }
75272             function checkIndexConstraintForProperty(prop, propertyType, containingType, indexDeclaration, indexType, indexKind) {
75273                 // ESSymbol properties apply to neither string nor numeric indexers.
75274                 if (!indexType || ts.isKnownSymbol(prop)) {
75275                     return;
75276                 }
75277                 var propDeclaration = prop.valueDeclaration;
75278                 var name = propDeclaration && ts.getNameOfDeclaration(propDeclaration);
75279                 if (name && ts.isPrivateIdentifier(name)) {
75280                     return;
75281                 }
75282                 // index is numeric and property name is not valid numeric literal
75283                 if (indexKind === 1 /* Number */ && !(name ? isNumericName(name) : isNumericLiteralName(prop.escapedName))) {
75284                     return;
75285                 }
75286                 // perform property check if property or indexer is declared in 'type'
75287                 // this allows us to rule out cases when both property and indexer are inherited from the base class
75288                 var errorNode;
75289                 if (propDeclaration && name &&
75290                     (propDeclaration.kind === 216 /* BinaryExpression */ ||
75291                         name.kind === 158 /* ComputedPropertyName */ ||
75292                         prop.parent === containingType.symbol)) {
75293                     errorNode = propDeclaration;
75294                 }
75295                 else if (indexDeclaration) {
75296                     errorNode = indexDeclaration;
75297                 }
75298                 else if (ts.getObjectFlags(containingType) & 2 /* Interface */) {
75299                     // for interfaces property and indexer might be inherited from different bases
75300                     // check if any base class already has both property and indexer.
75301                     // check should be performed only if 'type' is the first type that brings property\indexer together
75302                     var someBaseClassHasBothPropertyAndIndexer = ts.forEach(getBaseTypes(containingType), function (base) { return getPropertyOfObjectType(base, prop.escapedName) && getIndexTypeOfType(base, indexKind); });
75303                     errorNode = someBaseClassHasBothPropertyAndIndexer ? undefined : containingType.symbol.declarations[0];
75304                 }
75305                 if (errorNode && !isTypeAssignableTo(propertyType, indexType)) {
75306                     var errorMessage = indexKind === 0 /* String */
75307                         ? ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_string_index_type_2
75308                         : ts.Diagnostics.Property_0_of_type_1_is_not_assignable_to_numeric_index_type_2;
75309                     error(errorNode, errorMessage, symbolToString(prop), typeToString(propertyType), typeToString(indexType));
75310                 }
75311             }
75312         }
75313         function checkTypeNameIsReserved(name, message) {
75314             // TS 1.0 spec (April 2014): 3.6.1
75315             // The predefined type keywords are reserved and cannot be used as names of user defined types.
75316             switch (name.escapedText) {
75317                 case "any":
75318                 case "unknown":
75319                 case "number":
75320                 case "bigint":
75321                 case "boolean":
75322                 case "string":
75323                 case "symbol":
75324                 case "void":
75325                 case "object":
75326                     error(name, message, name.escapedText);
75327             }
75328         }
75329         /**
75330          * The name cannot be used as 'Object' of user defined types with special target.
75331          */
75332         function checkClassNameCollisionWithObject(name) {
75333             if (languageVersion === 1 /* ES5 */ && name.escapedText === "Object"
75334                 && moduleKind < ts.ModuleKind.ES2015) {
75335                 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
75336             }
75337         }
75338         /**
75339          * Check each type parameter and check that type parameters have no duplicate type parameter declarations
75340          */
75341         function checkTypeParameters(typeParameterDeclarations) {
75342             if (typeParameterDeclarations) {
75343                 var seenDefault = false;
75344                 for (var i = 0; i < typeParameterDeclarations.length; i++) {
75345                     var node = typeParameterDeclarations[i];
75346                     checkTypeParameter(node);
75347                     if (produceDiagnostics) {
75348                         if (node.default) {
75349                             seenDefault = true;
75350                             checkTypeParametersNotReferenced(node.default, typeParameterDeclarations, i);
75351                         }
75352                         else if (seenDefault) {
75353                             error(node, ts.Diagnostics.Required_type_parameters_may_not_follow_optional_type_parameters);
75354                         }
75355                         for (var j = 0; j < i; j++) {
75356                             if (typeParameterDeclarations[j].symbol === node.symbol) {
75357                                 error(node.name, ts.Diagnostics.Duplicate_identifier_0, ts.declarationNameToString(node.name));
75358                             }
75359                         }
75360                     }
75361                 }
75362             }
75363         }
75364         /** Check that type parameter defaults only reference previously declared type parameters */
75365         function checkTypeParametersNotReferenced(root, typeParameters, index) {
75366             visit(root);
75367             function visit(node) {
75368                 if (node.kind === 173 /* TypeReference */) {
75369                     var type = getTypeFromTypeReference(node);
75370                     if (type.flags & 262144 /* TypeParameter */) {
75371                         for (var i = index; i < typeParameters.length; i++) {
75372                             if (type.symbol === getSymbolOfNode(typeParameters[i])) {
75373                                 error(node, ts.Diagnostics.Type_parameter_defaults_can_only_reference_previously_declared_type_parameters);
75374                             }
75375                         }
75376                     }
75377                 }
75378                 ts.forEachChild(node, visit);
75379             }
75380         }
75381         /** Check that type parameter lists are identical across multiple declarations */
75382         function checkTypeParameterListsIdentical(symbol) {
75383             if (symbol.declarations.length === 1) {
75384                 return;
75385             }
75386             var links = getSymbolLinks(symbol);
75387             if (!links.typeParametersChecked) {
75388                 links.typeParametersChecked = true;
75389                 var declarations = getClassOrInterfaceDeclarationsOfSymbol(symbol);
75390                 if (declarations.length <= 1) {
75391                     return;
75392                 }
75393                 var type = getDeclaredTypeOfSymbol(symbol);
75394                 if (!areTypeParametersIdentical(declarations, type.localTypeParameters)) {
75395                     // Report an error on every conflicting declaration.
75396                     var name = symbolToString(symbol);
75397                     for (var _i = 0, declarations_6 = declarations; _i < declarations_6.length; _i++) {
75398                         var declaration = declarations_6[_i];
75399                         error(declaration.name, ts.Diagnostics.All_declarations_of_0_must_have_identical_type_parameters, name);
75400                     }
75401                 }
75402             }
75403         }
75404         function areTypeParametersIdentical(declarations, targetParameters) {
75405             var maxTypeArgumentCount = ts.length(targetParameters);
75406             var minTypeArgumentCount = getMinTypeArgumentCount(targetParameters);
75407             for (var _i = 0, declarations_7 = declarations; _i < declarations_7.length; _i++) {
75408                 var declaration = declarations_7[_i];
75409                 // If this declaration has too few or too many type parameters, we report an error
75410                 var sourceParameters = ts.getEffectiveTypeParameterDeclarations(declaration);
75411                 var numTypeParameters = sourceParameters.length;
75412                 if (numTypeParameters < minTypeArgumentCount || numTypeParameters > maxTypeArgumentCount) {
75413                     return false;
75414                 }
75415                 for (var i = 0; i < numTypeParameters; i++) {
75416                     var source = sourceParameters[i];
75417                     var target = targetParameters[i];
75418                     // If the type parameter node does not have the same as the resolved type
75419                     // parameter at this position, we report an error.
75420                     if (source.name.escapedText !== target.symbol.escapedName) {
75421                         return false;
75422                     }
75423                     // If the type parameter node does not have an identical constraint as the resolved
75424                     // type parameter at this position, we report an error.
75425                     var constraint = ts.getEffectiveConstraintOfTypeParameter(source);
75426                     var sourceConstraint = constraint && getTypeFromTypeNode(constraint);
75427                     var targetConstraint = getConstraintOfTypeParameter(target);
75428                     // relax check if later interface augmentation has no constraint, it's more broad and is OK to merge with
75429                     // a more constrained interface (this could be generalized to a full hierarchy check, but that's maybe overkill)
75430                     if (sourceConstraint && targetConstraint && !isTypeIdenticalTo(sourceConstraint, targetConstraint)) {
75431                         return false;
75432                     }
75433                     // If the type parameter node has a default and it is not identical to the default
75434                     // for the type parameter at this position, we report an error.
75435                     var sourceDefault = source.default && getTypeFromTypeNode(source.default);
75436                     var targetDefault = getDefaultFromTypeParameter(target);
75437                     if (sourceDefault && targetDefault && !isTypeIdenticalTo(sourceDefault, targetDefault)) {
75438                         return false;
75439                     }
75440                 }
75441             }
75442             return true;
75443         }
75444         function checkClassExpression(node) {
75445             checkClassLikeDeclaration(node);
75446             checkNodeDeferred(node);
75447             return getTypeOfSymbol(getSymbolOfNode(node));
75448         }
75449         function checkClassExpressionDeferred(node) {
75450             ts.forEach(node.members, checkSourceElement);
75451             registerForUnusedIdentifiersCheck(node);
75452         }
75453         function checkClassDeclaration(node) {
75454             if (!node.name && !ts.hasSyntacticModifier(node, 512 /* Default */)) {
75455                 grammarErrorOnFirstToken(node, ts.Diagnostics.A_class_declaration_without_the_default_modifier_must_have_a_name);
75456             }
75457             checkClassLikeDeclaration(node);
75458             ts.forEach(node.members, checkSourceElement);
75459             registerForUnusedIdentifiersCheck(node);
75460         }
75461         function checkClassLikeDeclaration(node) {
75462             checkGrammarClassLikeDeclaration(node);
75463             checkDecorators(node);
75464             if (node.name) {
75465                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Class_name_cannot_be_0);
75466                 checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
75467                 checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
75468                 if (!(node.flags & 8388608 /* Ambient */)) {
75469                     checkClassNameCollisionWithObject(node.name);
75470                 }
75471             }
75472             checkTypeParameters(ts.getEffectiveTypeParameterDeclarations(node));
75473             checkExportsOnMergedDeclarations(node);
75474             var symbol = getSymbolOfNode(node);
75475             var type = getDeclaredTypeOfSymbol(symbol);
75476             var typeWithThis = getTypeWithThisArgument(type);
75477             var staticType = getTypeOfSymbol(symbol);
75478             checkTypeParameterListsIdentical(symbol);
75479             checkFunctionOrConstructorSymbol(symbol);
75480             checkClassForDuplicateDeclarations(node);
75481             // Only check for reserved static identifiers on non-ambient context.
75482             if (!(node.flags & 8388608 /* Ambient */)) {
75483                 checkClassForStaticPropertyNameConflicts(node);
75484             }
75485             var baseTypeNode = ts.getEffectiveBaseTypeNode(node);
75486             if (baseTypeNode) {
75487                 ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
75488                 if (languageVersion < 2 /* ES2015 */) {
75489                     checkExternalEmitHelpers(baseTypeNode.parent, 1 /* Extends */);
75490                 }
75491                 // check both @extends and extends if both are specified.
75492                 var extendsNode = ts.getClassExtendsHeritageElement(node);
75493                 if (extendsNode && extendsNode !== baseTypeNode) {
75494                     checkExpression(extendsNode.expression);
75495                 }
75496                 var baseTypes = getBaseTypes(type);
75497                 if (baseTypes.length && produceDiagnostics) {
75498                     var baseType_1 = baseTypes[0];
75499                     var baseConstructorType = getBaseConstructorTypeOfClass(type);
75500                     var staticBaseType = getApparentType(baseConstructorType);
75501                     checkBaseTypeAccessibility(staticBaseType, baseTypeNode);
75502                     checkSourceElement(baseTypeNode.expression);
75503                     if (ts.some(baseTypeNode.typeArguments)) {
75504                         ts.forEach(baseTypeNode.typeArguments, checkSourceElement);
75505                         for (var _i = 0, _a = getConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode); _i < _a.length; _i++) {
75506                             var constructor = _a[_i];
75507                             if (!checkTypeArgumentConstraints(baseTypeNode, constructor.typeParameters)) {
75508                                 break;
75509                             }
75510                         }
75511                     }
75512                     var baseWithThis = getTypeWithThisArgument(baseType_1, type.thisType);
75513                     if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
75514                         issueMemberSpecificError(node, typeWithThis, baseWithThis, ts.Diagnostics.Class_0_incorrectly_extends_base_class_1);
75515                     }
75516                     else {
75517                         // Report static side error only when instance type is assignable
75518                         checkTypeAssignableTo(staticType, getTypeWithoutSignatures(staticBaseType), node.name || node, ts.Diagnostics.Class_static_side_0_incorrectly_extends_base_class_static_side_1);
75519                     }
75520                     if (baseConstructorType.flags & 8650752 /* TypeVariable */ && !isMixinConstructorType(staticType)) {
75521                         error(node.name || node, ts.Diagnostics.A_mixin_class_must_have_a_constructor_with_a_single_rest_parameter_of_type_any);
75522                     }
75523                     if (!(staticBaseType.symbol && staticBaseType.symbol.flags & 32 /* Class */) && !(baseConstructorType.flags & 8650752 /* TypeVariable */)) {
75524                         // When the static base type is a "class-like" constructor function (but not actually a class), we verify
75525                         // that all instantiated base constructor signatures return the same type.
75526                         var constructors = getInstantiatedConstructorsForTypeArguments(staticBaseType, baseTypeNode.typeArguments, baseTypeNode);
75527                         if (ts.forEach(constructors, function (sig) { return !isJSConstructor(sig.declaration) && !isTypeIdenticalTo(getReturnTypeOfSignature(sig), baseType_1); })) {
75528                             error(baseTypeNode.expression, ts.Diagnostics.Base_constructors_must_all_have_the_same_return_type);
75529                         }
75530                     }
75531                     checkKindsOfPropertyMemberOverrides(type, baseType_1);
75532                 }
75533             }
75534             var implementedTypeNodes = ts.getEffectiveImplementsTypeNodes(node);
75535             if (implementedTypeNodes) {
75536                 for (var _b = 0, implementedTypeNodes_1 = implementedTypeNodes; _b < implementedTypeNodes_1.length; _b++) {
75537                     var typeRefNode = implementedTypeNodes_1[_b];
75538                     if (!ts.isEntityNameExpression(typeRefNode.expression)) {
75539                         error(typeRefNode.expression, ts.Diagnostics.A_class_can_only_implement_an_identifier_Slashqualified_name_with_optional_type_arguments);
75540                     }
75541                     checkTypeReferenceNode(typeRefNode);
75542                     if (produceDiagnostics) {
75543                         var t = getReducedType(getTypeFromTypeNode(typeRefNode));
75544                         if (t !== errorType) {
75545                             if (isValidBaseType(t)) {
75546                                 var genericDiag = t.symbol && t.symbol.flags & 32 /* Class */ ?
75547                                     ts.Diagnostics.Class_0_incorrectly_implements_class_1_Did_you_mean_to_extend_1_and_inherit_its_members_as_a_subclass :
75548                                     ts.Diagnostics.Class_0_incorrectly_implements_interface_1;
75549                                 var baseWithThis = getTypeWithThisArgument(t, type.thisType);
75550                                 if (!checkTypeAssignableTo(typeWithThis, baseWithThis, /*errorNode*/ undefined)) {
75551                                     issueMemberSpecificError(node, typeWithThis, baseWithThis, genericDiag);
75552                                 }
75553                             }
75554                             else {
75555                                 error(typeRefNode, ts.Diagnostics.A_class_can_only_implement_an_object_type_or_intersection_of_object_types_with_statically_known_members);
75556                             }
75557                         }
75558                     }
75559                 }
75560             }
75561             if (produceDiagnostics) {
75562                 checkIndexConstraints(type);
75563                 checkTypeForDuplicateIndexSignatures(node);
75564                 checkPropertyInitialization(node);
75565             }
75566         }
75567         function issueMemberSpecificError(node, typeWithThis, baseWithThis, broadDiag) {
75568             // iterate over all implemented properties and issue errors on each one which isn't compatible, rather than the class as a whole, if possible
75569             var issuedMemberError = false;
75570             var _loop_23 = function (member) {
75571                 if (ts.hasStaticModifier(member)) {
75572                     return "continue";
75573                 }
75574                 var declaredProp = member.name && getSymbolAtLocation(member.name) || getSymbolAtLocation(member);
75575                 if (declaredProp) {
75576                     var prop = getPropertyOfType(typeWithThis, declaredProp.escapedName);
75577                     var baseProp = getPropertyOfType(baseWithThis, declaredProp.escapedName);
75578                     if (prop && baseProp) {
75579                         var rootChain = function () { return ts.chainDiagnosticMessages(
75580                         /*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)); };
75581                         if (!checkTypeAssignableTo(getTypeOfSymbol(prop), getTypeOfSymbol(baseProp), member.name || member, /*message*/ undefined, rootChain)) {
75582                             issuedMemberError = true;
75583                         }
75584                     }
75585                 }
75586             };
75587             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
75588                 var member = _a[_i];
75589                 _loop_23(member);
75590             }
75591             if (!issuedMemberError) {
75592                 // check again with diagnostics to generate a less-specific error
75593                 checkTypeAssignableTo(typeWithThis, baseWithThis, node.name || node, broadDiag);
75594             }
75595         }
75596         function checkBaseTypeAccessibility(type, node) {
75597             var signatures = getSignaturesOfType(type, 1 /* Construct */);
75598             if (signatures.length) {
75599                 var declaration = signatures[0].declaration;
75600                 if (declaration && ts.hasEffectiveModifier(declaration, 8 /* Private */)) {
75601                     var typeClassDeclaration = ts.getClassLikeDeclarationOfSymbol(type.symbol);
75602                     if (!isNodeWithinClass(node, typeClassDeclaration)) {
75603                         error(node, ts.Diagnostics.Cannot_extend_a_class_0_Class_constructor_is_marked_as_private, getFullyQualifiedName(type.symbol));
75604                     }
75605                 }
75606             }
75607         }
75608         function getTargetSymbol(s) {
75609             // if symbol is instantiated its flags are not copied from the 'target'
75610             // so we'll need to get back original 'target' symbol to work with correct set of flags
75611             return ts.getCheckFlags(s) & 1 /* Instantiated */ ? s.target : s;
75612         }
75613         function getClassOrInterfaceDeclarationsOfSymbol(symbol) {
75614             return ts.filter(symbol.declarations, function (d) {
75615                 return d.kind === 252 /* ClassDeclaration */ || d.kind === 253 /* InterfaceDeclaration */;
75616             });
75617         }
75618         function checkKindsOfPropertyMemberOverrides(type, baseType) {
75619             // TypeScript 1.0 spec (April 2014): 8.2.3
75620             // A derived class inherits all members from its base class it doesn't override.
75621             // Inheritance means that a derived class implicitly contains all non - overridden members of the base class.
75622             // Both public and private property members are inherited, but only public property members can be overridden.
75623             // A property member in a derived class is said to override a property member in a base class
75624             // when the derived class property member has the same name and kind(instance or static)
75625             // as the base class property member.
75626             // The type of an overriding property member must be assignable(section 3.8.4)
75627             // to the type of the overridden property member, or otherwise a compile - time error occurs.
75628             // Base class instance member functions can be overridden by derived class instance member functions,
75629             // but not by other kinds of members.
75630             // Base class instance member variables and accessors can be overridden by
75631             // derived class instance member variables and accessors, but not by other kinds of members.
75632             // NOTE: assignability is checked in checkClassDeclaration
75633             var baseProperties = getPropertiesOfType(baseType);
75634             basePropertyCheck: for (var _i = 0, baseProperties_1 = baseProperties; _i < baseProperties_1.length; _i++) {
75635                 var baseProperty = baseProperties_1[_i];
75636                 var base = getTargetSymbol(baseProperty);
75637                 if (base.flags & 4194304 /* Prototype */) {
75638                     continue;
75639                 }
75640                 var baseSymbol = getPropertyOfObjectType(type, base.escapedName);
75641                 if (!baseSymbol) {
75642                     continue;
75643                 }
75644                 var derived = getTargetSymbol(baseSymbol);
75645                 var baseDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(base);
75646                 ts.Debug.assert(!!derived, "derived should point to something, even if it is the base class' declaration.");
75647                 // In order to resolve whether the inherited method was overridden in the base class or not,
75648                 // we compare the Symbols obtained. Since getTargetSymbol returns the symbol on the *uninstantiated*
75649                 // type declaration, derived and base resolve to the same symbol even in the case of generic classes.
75650                 if (derived === base) {
75651                     // derived class inherits base without override/redeclaration
75652                     var derivedClassDecl = ts.getClassLikeDeclarationOfSymbol(type.symbol);
75653                     // It is an error to inherit an abstract member without implementing it or being declared abstract.
75654                     // If there is no declaration for the derived class (as in the case of class expressions),
75655                     // then the class cannot be declared abstract.
75656                     if (baseDeclarationFlags & 128 /* Abstract */ && (!derivedClassDecl || !ts.hasSyntacticModifier(derivedClassDecl, 128 /* Abstract */))) {
75657                         // Searches other base types for a declaration that would satisfy the inherited abstract member.
75658                         // (The class may have more than one base type via declaration merging with an interface with the
75659                         // same name.)
75660                         for (var _a = 0, _b = getBaseTypes(type); _a < _b.length; _a++) {
75661                             var otherBaseType = _b[_a];
75662                             if (otherBaseType === baseType)
75663                                 continue;
75664                             var baseSymbol_1 = getPropertyOfObjectType(otherBaseType, base.escapedName);
75665                             var derivedElsewhere = baseSymbol_1 && getTargetSymbol(baseSymbol_1);
75666                             if (derivedElsewhere && derivedElsewhere !== base) {
75667                                 continue basePropertyCheck;
75668                             }
75669                         }
75670                         if (derivedClassDecl.kind === 221 /* ClassExpression */) {
75671                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_expression_does_not_implement_inherited_abstract_member_0_from_class_1, symbolToString(baseProperty), typeToString(baseType));
75672                         }
75673                         else {
75674                             error(derivedClassDecl, ts.Diagnostics.Non_abstract_class_0_does_not_implement_inherited_abstract_member_1_from_class_2, typeToString(type), symbolToString(baseProperty), typeToString(baseType));
75675                         }
75676                     }
75677                 }
75678                 else {
75679                     // derived overrides base.
75680                     var derivedDeclarationFlags = ts.getDeclarationModifierFlagsFromSymbol(derived);
75681                     if (baseDeclarationFlags & 8 /* Private */ || derivedDeclarationFlags & 8 /* Private */) {
75682                         // either base or derived property is private - not override, skip it
75683                         continue;
75684                     }
75685                     var errorMessage = void 0;
75686                     var basePropertyFlags = base.flags & 98308 /* PropertyOrAccessor */;
75687                     var derivedPropertyFlags = derived.flags & 98308 /* PropertyOrAccessor */;
75688                     if (basePropertyFlags && derivedPropertyFlags) {
75689                         // property/accessor is overridden with property/accessor
75690                         if (baseDeclarationFlags & 128 /* Abstract */ && !(base.valueDeclaration && ts.isPropertyDeclaration(base.valueDeclaration) && base.valueDeclaration.initializer)
75691                             || base.valueDeclaration && base.valueDeclaration.parent.kind === 253 /* InterfaceDeclaration */
75692                             || derived.valueDeclaration && ts.isBinaryExpression(derived.valueDeclaration)) {
75693                             // when the base property is abstract or from an interface, base/derived flags don't need to match
75694                             // same when the derived property is from an assignment
75695                             continue;
75696                         }
75697                         var overriddenInstanceProperty = basePropertyFlags !== 4 /* Property */ && derivedPropertyFlags === 4 /* Property */;
75698                         var overriddenInstanceAccessor = basePropertyFlags === 4 /* Property */ && derivedPropertyFlags !== 4 /* Property */;
75699                         if (overriddenInstanceProperty || overriddenInstanceAccessor) {
75700                             var errorMessage_1 = overriddenInstanceProperty ?
75701                                 ts.Diagnostics._0_is_defined_as_an_accessor_in_class_1_but_is_overridden_here_in_2_as_an_instance_property :
75702                                 ts.Diagnostics._0_is_defined_as_a_property_in_class_1_but_is_overridden_here_in_2_as_an_accessor;
75703                             error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_1, symbolToString(base), typeToString(baseType), typeToString(type));
75704                         }
75705                         else if (compilerOptions.useDefineForClassFields) {
75706                             var uninitialized = ts.find(derived.declarations, function (d) { return d.kind === 163 /* PropertyDeclaration */ && !d.initializer; });
75707                             if (uninitialized
75708                                 && !(derived.flags & 33554432 /* Transient */)
75709                                 && !(baseDeclarationFlags & 128 /* Abstract */)
75710                                 && !(derivedDeclarationFlags & 128 /* Abstract */)
75711                                 && !derived.declarations.some(function (d) { return !!(d.flags & 8388608 /* Ambient */); })) {
75712                                 var constructor = findConstructorDeclaration(ts.getClassLikeDeclarationOfSymbol(type.symbol));
75713                                 var propName = uninitialized.name;
75714                                 if (uninitialized.exclamationToken
75715                                     || !constructor
75716                                     || !ts.isIdentifier(propName)
75717                                     || !strictNullChecks
75718                                     || !isPropertyInitializedInConstructor(propName, type, constructor)) {
75719                                     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;
75720                                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage_2, symbolToString(base), typeToString(baseType));
75721                                 }
75722                             }
75723                         }
75724                         // correct case
75725                         continue;
75726                     }
75727                     else if (isPrototypeProperty(base)) {
75728                         if (isPrototypeProperty(derived) || derived.flags & 4 /* Property */) {
75729                             // method is overridden with method or property -- correct case
75730                             continue;
75731                         }
75732                         else {
75733                             ts.Debug.assert(!!(derived.flags & 98304 /* Accessor */));
75734                             errorMessage = ts.Diagnostics.Class_0_defines_instance_member_function_1_but_extended_class_2_defines_it_as_instance_member_accessor;
75735                         }
75736                     }
75737                     else if (base.flags & 98304 /* Accessor */) {
75738                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_accessor_1_but_extended_class_2_defines_it_as_instance_member_function;
75739                     }
75740                     else {
75741                         errorMessage = ts.Diagnostics.Class_0_defines_instance_member_property_1_but_extended_class_2_defines_it_as_instance_member_function;
75742                     }
75743                     error(ts.getNameOfDeclaration(derived.valueDeclaration) || derived.valueDeclaration, errorMessage, typeToString(baseType), symbolToString(base), typeToString(type));
75744                 }
75745             }
75746         }
75747         function getNonInterhitedProperties(type, baseTypes, properties) {
75748             if (!ts.length(baseTypes)) {
75749                 return properties;
75750             }
75751             var seen = new ts.Map();
75752             ts.forEach(properties, function (p) { seen.set(p.escapedName, p); });
75753             for (var _i = 0, baseTypes_2 = baseTypes; _i < baseTypes_2.length; _i++) {
75754                 var base = baseTypes_2[_i];
75755                 var properties_5 = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
75756                 for (var _a = 0, properties_4 = properties_5; _a < properties_4.length; _a++) {
75757                     var prop = properties_4[_a];
75758                     var existing = seen.get(prop.escapedName);
75759                     if (existing && !isPropertyIdenticalTo(existing, prop)) {
75760                         seen.delete(prop.escapedName);
75761                     }
75762                 }
75763             }
75764             return ts.arrayFrom(seen.values());
75765         }
75766         function checkInheritedPropertiesAreIdentical(type, typeNode) {
75767             var baseTypes = getBaseTypes(type);
75768             if (baseTypes.length < 2) {
75769                 return true;
75770             }
75771             var seen = new ts.Map();
75772             ts.forEach(resolveDeclaredMembers(type).declaredProperties, function (p) { seen.set(p.escapedName, { prop: p, containingType: type }); });
75773             var ok = true;
75774             for (var _i = 0, baseTypes_3 = baseTypes; _i < baseTypes_3.length; _i++) {
75775                 var base = baseTypes_3[_i];
75776                 var properties = getPropertiesOfType(getTypeWithThisArgument(base, type.thisType));
75777                 for (var _a = 0, properties_6 = properties; _a < properties_6.length; _a++) {
75778                     var prop = properties_6[_a];
75779                     var existing = seen.get(prop.escapedName);
75780                     if (!existing) {
75781                         seen.set(prop.escapedName, { prop: prop, containingType: base });
75782                     }
75783                     else {
75784                         var isInheritedProperty = existing.containingType !== type;
75785                         if (isInheritedProperty && !isPropertyIdenticalTo(existing.prop, prop)) {
75786                             ok = false;
75787                             var typeName1 = typeToString(existing.containingType);
75788                             var typeName2 = typeToString(base);
75789                             var errorInfo = ts.chainDiagnosticMessages(/*details*/ undefined, ts.Diagnostics.Named_property_0_of_types_1_and_2_are_not_identical, symbolToString(prop), typeName1, typeName2);
75790                             errorInfo = ts.chainDiagnosticMessages(errorInfo, ts.Diagnostics.Interface_0_cannot_simultaneously_extend_types_1_and_2, typeToString(type), typeName1, typeName2);
75791                             diagnostics.add(ts.createDiagnosticForNodeFromMessageChain(typeNode, errorInfo));
75792                         }
75793                     }
75794                 }
75795             }
75796             return ok;
75797         }
75798         function checkPropertyInitialization(node) {
75799             if (!strictNullChecks || !strictPropertyInitialization || node.flags & 8388608 /* Ambient */) {
75800                 return;
75801             }
75802             var constructor = findConstructorDeclaration(node);
75803             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
75804                 var member = _a[_i];
75805                 if (ts.getEffectiveModifierFlags(member) & 2 /* Ambient */) {
75806                     continue;
75807                 }
75808                 if (isInstancePropertyWithoutInitializer(member)) {
75809                     var propName = member.name;
75810                     if (ts.isIdentifier(propName) || ts.isPrivateIdentifier(propName)) {
75811                         var type = getTypeOfSymbol(getSymbolOfNode(member));
75812                         if (!(type.flags & 3 /* AnyOrUnknown */ || getFalsyFlags(type) & 32768 /* Undefined */)) {
75813                             if (!constructor || !isPropertyInitializedInConstructor(propName, type, constructor)) {
75814                                 error(member.name, ts.Diagnostics.Property_0_has_no_initializer_and_is_not_definitely_assigned_in_the_constructor, ts.declarationNameToString(propName));
75815                             }
75816                         }
75817                     }
75818                 }
75819             }
75820         }
75821         function isInstancePropertyWithoutInitializer(node) {
75822             return node.kind === 163 /* PropertyDeclaration */ &&
75823                 !ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */) &&
75824                 !node.exclamationToken &&
75825                 !node.initializer;
75826         }
75827         function isPropertyInitializedInConstructor(propName, propType, constructor) {
75828             var reference = ts.factory.createPropertyAccessExpression(ts.factory.createThis(), propName);
75829             ts.setParent(reference.expression, reference);
75830             ts.setParent(reference, constructor);
75831             reference.flowNode = constructor.returnFlowNode;
75832             var flowType = getFlowTypeOfReference(reference, propType, getOptionalType(propType));
75833             return !(getFalsyFlags(flowType) & 32768 /* Undefined */);
75834         }
75835         function checkInterfaceDeclaration(node) {
75836             // Grammar checking
75837             if (!checkGrammarDecoratorsAndModifiers(node))
75838                 checkGrammarInterfaceDeclaration(node);
75839             checkTypeParameters(node.typeParameters);
75840             if (produceDiagnostics) {
75841                 checkTypeNameIsReserved(node.name, ts.Diagnostics.Interface_name_cannot_be_0);
75842                 checkExportsOnMergedDeclarations(node);
75843                 var symbol = getSymbolOfNode(node);
75844                 checkTypeParameterListsIdentical(symbol);
75845                 // Only check this symbol once
75846                 var firstInterfaceDecl = ts.getDeclarationOfKind(symbol, 253 /* InterfaceDeclaration */);
75847                 if (node === firstInterfaceDecl) {
75848                     var type = getDeclaredTypeOfSymbol(symbol);
75849                     var typeWithThis = getTypeWithThisArgument(type);
75850                     // run subsequent checks only if first set succeeded
75851                     if (checkInheritedPropertiesAreIdentical(type, node.name)) {
75852                         for (var _i = 0, _a = getBaseTypes(type); _i < _a.length; _i++) {
75853                             var baseType = _a[_i];
75854                             checkTypeAssignableTo(typeWithThis, getTypeWithThisArgument(baseType, type.thisType), node.name, ts.Diagnostics.Interface_0_incorrectly_extends_interface_1);
75855                         }
75856                         checkIndexConstraints(type);
75857                     }
75858                 }
75859                 checkObjectTypeForDuplicateDeclarations(node);
75860             }
75861             ts.forEach(ts.getInterfaceBaseTypeNodes(node), function (heritageElement) {
75862                 if (!ts.isEntityNameExpression(heritageElement.expression)) {
75863                     error(heritageElement.expression, ts.Diagnostics.An_interface_can_only_extend_an_identifier_Slashqualified_name_with_optional_type_arguments);
75864                 }
75865                 checkTypeReferenceNode(heritageElement);
75866             });
75867             ts.forEach(node.members, checkSourceElement);
75868             if (produceDiagnostics) {
75869                 checkTypeForDuplicateIndexSignatures(node);
75870                 registerForUnusedIdentifiersCheck(node);
75871             }
75872         }
75873         function checkTypeAliasDeclaration(node) {
75874             // Grammar checking
75875             checkGrammarDecoratorsAndModifiers(node);
75876             checkTypeNameIsReserved(node.name, ts.Diagnostics.Type_alias_name_cannot_be_0);
75877             checkExportsOnMergedDeclarations(node);
75878             checkTypeParameters(node.typeParameters);
75879             if (node.type.kind === 136 /* IntrinsicKeyword */) {
75880                 if (!intrinsicTypeKinds.has(node.name.escapedText) || ts.length(node.typeParameters) !== 1) {
75881                     error(node.type, ts.Diagnostics.The_intrinsic_keyword_can_only_be_used_to_declare_compiler_provided_intrinsic_types);
75882                 }
75883             }
75884             else {
75885                 checkSourceElement(node.type);
75886                 registerForUnusedIdentifiersCheck(node);
75887             }
75888         }
75889         function computeEnumMemberValues(node) {
75890             var nodeLinks = getNodeLinks(node);
75891             if (!(nodeLinks.flags & 16384 /* EnumValuesComputed */)) {
75892                 nodeLinks.flags |= 16384 /* EnumValuesComputed */;
75893                 var autoValue = 0;
75894                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
75895                     var member = _a[_i];
75896                     var value = computeMemberValue(member, autoValue);
75897                     getNodeLinks(member).enumMemberValue = value;
75898                     autoValue = typeof value === "number" ? value + 1 : undefined;
75899                 }
75900             }
75901         }
75902         function computeMemberValue(member, autoValue) {
75903             if (ts.isComputedNonLiteralName(member.name)) {
75904                 error(member.name, ts.Diagnostics.Computed_property_names_are_not_allowed_in_enums);
75905             }
75906             else {
75907                 var text = ts.getTextOfPropertyName(member.name);
75908                 if (isNumericLiteralName(text) && !isInfinityOrNaNString(text)) {
75909                     error(member.name, ts.Diagnostics.An_enum_member_cannot_have_a_numeric_name);
75910                 }
75911             }
75912             if (member.initializer) {
75913                 return computeConstantValue(member);
75914             }
75915             // In ambient non-const numeric enum declarations, enum members without initializers are
75916             // considered computed members (as opposed to having auto-incremented values).
75917             if (member.parent.flags & 8388608 /* Ambient */ && !ts.isEnumConst(member.parent) && getEnumKind(getSymbolOfNode(member.parent)) === 0 /* Numeric */) {
75918                 return undefined;
75919             }
75920             // If the member declaration specifies no value, the member is considered a constant enum member.
75921             // If the member is the first member in the enum declaration, it is assigned the value zero.
75922             // Otherwise, it is assigned the value of the immediately preceding member plus one, and an error
75923             // occurs if the immediately preceding member is not a constant enum member.
75924             if (autoValue !== undefined) {
75925                 return autoValue;
75926             }
75927             error(member.name, ts.Diagnostics.Enum_member_must_have_initializer);
75928             return undefined;
75929         }
75930         function computeConstantValue(member) {
75931             var enumKind = getEnumKind(getSymbolOfNode(member.parent));
75932             var isConstEnum = ts.isEnumConst(member.parent);
75933             var initializer = member.initializer;
75934             var value = enumKind === 1 /* Literal */ && !isLiteralEnumMember(member) ? undefined : evaluate(initializer);
75935             if (value !== undefined) {
75936                 if (isConstEnum && typeof value === "number" && !isFinite(value)) {
75937                     error(initializer, isNaN(value) ?
75938                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_disallowed_value_NaN :
75939                         ts.Diagnostics.const_enum_member_initializer_was_evaluated_to_a_non_finite_value);
75940                 }
75941             }
75942             else if (enumKind === 1 /* Literal */) {
75943                 error(initializer, ts.Diagnostics.Computed_values_are_not_permitted_in_an_enum_with_string_valued_members);
75944                 return 0;
75945             }
75946             else if (isConstEnum) {
75947                 error(initializer, ts.Diagnostics.const_enum_member_initializers_can_only_contain_literal_values_and_other_computed_enum_values);
75948             }
75949             else if (member.parent.flags & 8388608 /* Ambient */) {
75950                 error(initializer, ts.Diagnostics.In_ambient_enum_declarations_member_initializer_must_be_constant_expression);
75951             }
75952             else {
75953                 // Only here do we need to check that the initializer is assignable to the enum type.
75954                 var source = checkExpression(initializer);
75955                 if (!isTypeAssignableToKind(source, 296 /* NumberLike */)) {
75956                     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));
75957                 }
75958                 else {
75959                     checkTypeAssignableTo(source, getDeclaredTypeOfSymbol(getSymbolOfNode(member.parent)), initializer, /*headMessage*/ undefined);
75960                 }
75961             }
75962             return value;
75963             function evaluate(expr) {
75964                 switch (expr.kind) {
75965                     case 214 /* PrefixUnaryExpression */:
75966                         var value_2 = evaluate(expr.operand);
75967                         if (typeof value_2 === "number") {
75968                             switch (expr.operator) {
75969                                 case 39 /* PlusToken */: return value_2;
75970                                 case 40 /* MinusToken */: return -value_2;
75971                                 case 54 /* TildeToken */: return ~value_2;
75972                             }
75973                         }
75974                         break;
75975                     case 216 /* BinaryExpression */:
75976                         var left = evaluate(expr.left);
75977                         var right = evaluate(expr.right);
75978                         if (typeof left === "number" && typeof right === "number") {
75979                             switch (expr.operatorToken.kind) {
75980                                 case 51 /* BarToken */: return left | right;
75981                                 case 50 /* AmpersandToken */: return left & right;
75982                                 case 48 /* GreaterThanGreaterThanToken */: return left >> right;
75983                                 case 49 /* GreaterThanGreaterThanGreaterThanToken */: return left >>> right;
75984                                 case 47 /* LessThanLessThanToken */: return left << right;
75985                                 case 52 /* CaretToken */: return left ^ right;
75986                                 case 41 /* AsteriskToken */: return left * right;
75987                                 case 43 /* SlashToken */: return left / right;
75988                                 case 39 /* PlusToken */: return left + right;
75989                                 case 40 /* MinusToken */: return left - right;
75990                                 case 44 /* PercentToken */: return left % right;
75991                                 case 42 /* AsteriskAsteriskToken */: return Math.pow(left, right);
75992                             }
75993                         }
75994                         else if (typeof left === "string" && typeof right === "string" && expr.operatorToken.kind === 39 /* PlusToken */) {
75995                             return left + right;
75996                         }
75997                         break;
75998                     case 10 /* StringLiteral */:
75999                     case 14 /* NoSubstitutionTemplateLiteral */:
76000                         return expr.text;
76001                     case 8 /* NumericLiteral */:
76002                         checkGrammarNumericLiteral(expr);
76003                         return +expr.text;
76004                     case 207 /* ParenthesizedExpression */:
76005                         return evaluate(expr.expression);
76006                     case 78 /* Identifier */:
76007                         var identifier = expr;
76008                         if (isInfinityOrNaNString(identifier.escapedText)) {
76009                             return +(identifier.escapedText);
76010                         }
76011                         return ts.nodeIsMissing(expr) ? 0 : evaluateEnumMember(expr, getSymbolOfNode(member.parent), identifier.escapedText);
76012                     case 202 /* ElementAccessExpression */:
76013                     case 201 /* PropertyAccessExpression */:
76014                         var ex = expr;
76015                         if (isConstantMemberAccess(ex)) {
76016                             var type = getTypeOfExpression(ex.expression);
76017                             if (type.symbol && type.symbol.flags & 384 /* Enum */) {
76018                                 var name = void 0;
76019                                 if (ex.kind === 201 /* PropertyAccessExpression */) {
76020                                     name = ex.name.escapedText;
76021                                 }
76022                                 else {
76023                                     name = ts.escapeLeadingUnderscores(ts.cast(ex.argumentExpression, ts.isLiteralExpression).text);
76024                                 }
76025                                 return evaluateEnumMember(expr, type.symbol, name);
76026                             }
76027                         }
76028                         break;
76029                 }
76030                 return undefined;
76031             }
76032             function evaluateEnumMember(expr, enumSymbol, name) {
76033                 var memberSymbol = enumSymbol.exports.get(name);
76034                 if (memberSymbol) {
76035                     var declaration = memberSymbol.valueDeclaration;
76036                     if (declaration !== member) {
76037                         if (isBlockScopedNameDeclaredBeforeUse(declaration, member)) {
76038                             return getEnumMemberValue(declaration);
76039                         }
76040                         error(expr, ts.Diagnostics.A_member_initializer_in_a_enum_declaration_cannot_reference_members_declared_after_it_including_members_defined_in_other_enums);
76041                         return 0;
76042                     }
76043                     else {
76044                         error(expr, ts.Diagnostics.Property_0_is_used_before_being_assigned, symbolToString(memberSymbol));
76045                     }
76046                 }
76047                 return undefined;
76048             }
76049         }
76050         function isConstantMemberAccess(node) {
76051             return node.kind === 78 /* Identifier */ ||
76052                 node.kind === 201 /* PropertyAccessExpression */ && isConstantMemberAccess(node.expression) ||
76053                 node.kind === 202 /* ElementAccessExpression */ && isConstantMemberAccess(node.expression) &&
76054                     ts.isStringLiteralLike(node.argumentExpression);
76055         }
76056         function checkEnumDeclaration(node) {
76057             if (!produceDiagnostics) {
76058                 return;
76059             }
76060             // Grammar checking
76061             checkGrammarDecoratorsAndModifiers(node);
76062             checkTypeNameIsReserved(node.name, ts.Diagnostics.Enum_name_cannot_be_0);
76063             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
76064             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
76065             checkExportsOnMergedDeclarations(node);
76066             node.members.forEach(checkEnumMember);
76067             computeEnumMemberValues(node);
76068             // Spec 2014 - Section 9.3:
76069             // It isn't possible for one enum declaration to continue the automatic numbering sequence of another,
76070             // and when an enum type has multiple declarations, only one declaration is permitted to omit a value
76071             // for the first member.
76072             //
76073             // Only perform this check once per symbol
76074             var enumSymbol = getSymbolOfNode(node);
76075             var firstDeclaration = ts.getDeclarationOfKind(enumSymbol, node.kind);
76076             if (node === firstDeclaration) {
76077                 if (enumSymbol.declarations.length > 1) {
76078                     var enumIsConst_1 = ts.isEnumConst(node);
76079                     // check that const is placed\omitted on all enum declarations
76080                     ts.forEach(enumSymbol.declarations, function (decl) {
76081                         if (ts.isEnumDeclaration(decl) && ts.isEnumConst(decl) !== enumIsConst_1) {
76082                             error(ts.getNameOfDeclaration(decl), ts.Diagnostics.Enum_declarations_must_all_be_const_or_non_const);
76083                         }
76084                     });
76085                 }
76086                 var seenEnumMissingInitialInitializer_1 = false;
76087                 ts.forEach(enumSymbol.declarations, function (declaration) {
76088                     // return true if we hit a violation of the rule, false otherwise
76089                     if (declaration.kind !== 255 /* EnumDeclaration */) {
76090                         return false;
76091                     }
76092                     var enumDeclaration = declaration;
76093                     if (!enumDeclaration.members.length) {
76094                         return false;
76095                     }
76096                     var firstEnumMember = enumDeclaration.members[0];
76097                     if (!firstEnumMember.initializer) {
76098                         if (seenEnumMissingInitialInitializer_1) {
76099                             error(firstEnumMember.name, ts.Diagnostics.In_an_enum_with_multiple_declarations_only_one_declaration_can_omit_an_initializer_for_its_first_enum_element);
76100                         }
76101                         else {
76102                             seenEnumMissingInitialInitializer_1 = true;
76103                         }
76104                     }
76105                 });
76106             }
76107         }
76108         function checkEnumMember(node) {
76109             if (ts.isPrivateIdentifier(node.name)) {
76110                 error(node, ts.Diagnostics.An_enum_member_cannot_be_named_with_a_private_identifier);
76111             }
76112         }
76113         function getFirstNonAmbientClassOrFunctionDeclaration(symbol) {
76114             var declarations = symbol.declarations;
76115             for (var _i = 0, declarations_8 = declarations; _i < declarations_8.length; _i++) {
76116                 var declaration = declarations_8[_i];
76117                 if ((declaration.kind === 252 /* ClassDeclaration */ ||
76118                     (declaration.kind === 251 /* FunctionDeclaration */ && ts.nodeIsPresent(declaration.body))) &&
76119                     !(declaration.flags & 8388608 /* Ambient */)) {
76120                     return declaration;
76121                 }
76122             }
76123             return undefined;
76124         }
76125         function inSameLexicalScope(node1, node2) {
76126             var container1 = ts.getEnclosingBlockScopeContainer(node1);
76127             var container2 = ts.getEnclosingBlockScopeContainer(node2);
76128             if (isGlobalSourceFile(container1)) {
76129                 return isGlobalSourceFile(container2);
76130             }
76131             else if (isGlobalSourceFile(container2)) {
76132                 return false;
76133             }
76134             else {
76135                 return container1 === container2;
76136             }
76137         }
76138         function checkModuleDeclaration(node) {
76139             if (produceDiagnostics) {
76140                 // Grammar checking
76141                 var isGlobalAugmentation = ts.isGlobalScopeAugmentation(node);
76142                 var inAmbientContext = node.flags & 8388608 /* Ambient */;
76143                 if (isGlobalAugmentation && !inAmbientContext) {
76144                     error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_should_have_declare_modifier_unless_they_appear_in_already_ambient_context);
76145                 }
76146                 var isAmbientExternalModule = ts.isAmbientModule(node);
76147                 var contextErrorMessage = isAmbientExternalModule
76148                     ? ts.Diagnostics.An_ambient_module_declaration_is_only_allowed_at_the_top_level_in_a_file
76149                     : ts.Diagnostics.A_namespace_declaration_is_only_allowed_in_a_namespace_or_module;
76150                 if (checkGrammarModuleElementContext(node, contextErrorMessage)) {
76151                     // If we hit a module declaration in an illegal context, just bail out to avoid cascading errors.
76152                     return;
76153                 }
76154                 if (!checkGrammarDecoratorsAndModifiers(node)) {
76155                     if (!inAmbientContext && node.name.kind === 10 /* StringLiteral */) {
76156                         grammarErrorOnNode(node.name, ts.Diagnostics.Only_ambient_modules_can_use_quoted_names);
76157                     }
76158                 }
76159                 if (ts.isIdentifier(node.name)) {
76160                     checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
76161                     checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
76162                 }
76163                 checkExportsOnMergedDeclarations(node);
76164                 var symbol = getSymbolOfNode(node);
76165                 // The following checks only apply on a non-ambient instantiated module declaration.
76166                 if (symbol.flags & 512 /* ValueModule */
76167                     && !inAmbientContext
76168                     && symbol.declarations.length > 1
76169                     && isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules)) {
76170                     var firstNonAmbientClassOrFunc = getFirstNonAmbientClassOrFunctionDeclaration(symbol);
76171                     if (firstNonAmbientClassOrFunc) {
76172                         if (ts.getSourceFileOfNode(node) !== ts.getSourceFileOfNode(firstNonAmbientClassOrFunc)) {
76173                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_in_a_different_file_from_a_class_or_function_with_which_it_is_merged);
76174                         }
76175                         else if (node.pos < firstNonAmbientClassOrFunc.pos) {
76176                             error(node.name, ts.Diagnostics.A_namespace_declaration_cannot_be_located_prior_to_a_class_or_function_with_which_it_is_merged);
76177                         }
76178                     }
76179                     // if the module merges with a class declaration in the same lexical scope,
76180                     // we need to track this to ensure the correct emit.
76181                     var mergedClass = ts.getDeclarationOfKind(symbol, 252 /* ClassDeclaration */);
76182                     if (mergedClass &&
76183                         inSameLexicalScope(node, mergedClass)) {
76184                         getNodeLinks(node).flags |= 32768 /* LexicalModuleMergesWithClass */;
76185                     }
76186                 }
76187                 if (isAmbientExternalModule) {
76188                     if (ts.isExternalModuleAugmentation(node)) {
76189                         // body of the augmentation should be checked for consistency only if augmentation was applied to its target (either global scope or module)
76190                         // otherwise we'll be swamped in cascading errors.
76191                         // We can detect if augmentation was applied using following rules:
76192                         // - augmentation for a global scope is always applied
76193                         // - augmentation for some external module is applied if symbol for augmentation is merged (it was combined with target module).
76194                         var checkBody = isGlobalAugmentation || (getSymbolOfNode(node).flags & 33554432 /* Transient */);
76195                         if (checkBody && node.body) {
76196                             for (var _i = 0, _a = node.body.statements; _i < _a.length; _i++) {
76197                                 var statement = _a[_i];
76198                                 checkModuleAugmentationElement(statement, isGlobalAugmentation);
76199                             }
76200                         }
76201                     }
76202                     else if (isGlobalSourceFile(node.parent)) {
76203                         if (isGlobalAugmentation) {
76204                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
76205                         }
76206                         else if (ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(node.name))) {
76207                             error(node.name, ts.Diagnostics.Ambient_module_declaration_cannot_specify_relative_module_name);
76208                         }
76209                     }
76210                     else {
76211                         if (isGlobalAugmentation) {
76212                             error(node.name, ts.Diagnostics.Augmentations_for_the_global_scope_can_only_be_directly_nested_in_external_modules_or_ambient_module_declarations);
76213                         }
76214                         else {
76215                             // Node is not an augmentation and is not located on the script level.
76216                             // This means that this is declaration of ambient module that is located in other module or namespace which is prohibited.
76217                             error(node.name, ts.Diagnostics.Ambient_modules_cannot_be_nested_in_other_modules_or_namespaces);
76218                         }
76219                     }
76220                 }
76221             }
76222             if (node.body) {
76223                 checkSourceElement(node.body);
76224                 if (!ts.isGlobalScopeAugmentation(node)) {
76225                     registerForUnusedIdentifiersCheck(node);
76226                 }
76227             }
76228         }
76229         function checkModuleAugmentationElement(node, isGlobalAugmentation) {
76230             switch (node.kind) {
76231                 case 232 /* VariableStatement */:
76232                     // error each individual name in variable statement instead of marking the entire variable statement
76233                     for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
76234                         var decl = _a[_i];
76235                         checkModuleAugmentationElement(decl, isGlobalAugmentation);
76236                     }
76237                     break;
76238                 case 266 /* ExportAssignment */:
76239                 case 267 /* ExportDeclaration */:
76240                     grammarErrorOnFirstToken(node, ts.Diagnostics.Exports_and_export_assignments_are_not_permitted_in_module_augmentations);
76241                     break;
76242                 case 260 /* ImportEqualsDeclaration */:
76243                 case 261 /* ImportDeclaration */:
76244                     grammarErrorOnFirstToken(node, ts.Diagnostics.Imports_are_not_permitted_in_module_augmentations_Consider_moving_them_to_the_enclosing_external_module);
76245                     break;
76246                 case 198 /* BindingElement */:
76247                 case 249 /* VariableDeclaration */:
76248                     var name = node.name;
76249                     if (ts.isBindingPattern(name)) {
76250                         for (var _b = 0, _c = name.elements; _b < _c.length; _b++) {
76251                             var el = _c[_b];
76252                             // mark individual names in binding pattern
76253                             checkModuleAugmentationElement(el, isGlobalAugmentation);
76254                         }
76255                         break;
76256                     }
76257                 // falls through
76258                 case 252 /* ClassDeclaration */:
76259                 case 255 /* EnumDeclaration */:
76260                 case 251 /* FunctionDeclaration */:
76261                 case 253 /* InterfaceDeclaration */:
76262                 case 256 /* ModuleDeclaration */:
76263                 case 254 /* TypeAliasDeclaration */:
76264                     if (isGlobalAugmentation) {
76265                         return;
76266                     }
76267                     var symbol = getSymbolOfNode(node);
76268                     if (symbol) {
76269                         // module augmentations cannot introduce new names on the top level scope of the module
76270                         // this is done it two steps
76271                         // 1. quick check - if symbol for node is not merged - this is local symbol to this augmentation - report error
76272                         // 2. main check - report error if value declaration of the parent symbol is module augmentation)
76273                         var reportError = !(symbol.flags & 33554432 /* Transient */);
76274                         if (!reportError) {
76275                             // symbol should not originate in augmentation
76276                             reportError = !!symbol.parent && ts.isExternalModuleAugmentation(symbol.parent.declarations[0]);
76277                         }
76278                     }
76279                     break;
76280             }
76281         }
76282         function getFirstNonModuleExportsIdentifier(node) {
76283             switch (node.kind) {
76284                 case 78 /* Identifier */:
76285                     return node;
76286                 case 157 /* QualifiedName */:
76287                     do {
76288                         node = node.left;
76289                     } while (node.kind !== 78 /* Identifier */);
76290                     return node;
76291                 case 201 /* PropertyAccessExpression */:
76292                     do {
76293                         if (ts.isModuleExportsAccessExpression(node.expression) && !ts.isPrivateIdentifier(node.name)) {
76294                             return node.name;
76295                         }
76296                         node = node.expression;
76297                     } while (node.kind !== 78 /* Identifier */);
76298                     return node;
76299             }
76300         }
76301         function checkExternalImportOrExportDeclaration(node) {
76302             var moduleName = ts.getExternalModuleName(node);
76303             if (!moduleName || ts.nodeIsMissing(moduleName)) {
76304                 // Should be a parse error.
76305                 return false;
76306             }
76307             if (!ts.isStringLiteral(moduleName)) {
76308                 error(moduleName, ts.Diagnostics.String_literal_expected);
76309                 return false;
76310             }
76311             var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
76312             if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule) {
76313                 error(moduleName, node.kind === 267 /* ExportDeclaration */ ?
76314                     ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace :
76315                     ts.Diagnostics.Import_declarations_in_a_namespace_cannot_reference_a_module);
76316                 return false;
76317             }
76318             if (inAmbientExternalModule && ts.isExternalModuleNameRelative(moduleName.text)) {
76319                 // we have already reported errors on top level imports/exports in external module augmentations in checkModuleDeclaration
76320                 // no need to do this again.
76321                 if (!isTopLevelInExternalModuleAugmentation(node)) {
76322                     // TypeScript 1.0 spec (April 2013): 12.1.6
76323                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference
76324                     // other external modules only through top - level external module names.
76325                     // Relative external module names are not permitted.
76326                     error(node, ts.Diagnostics.Import_or_export_declaration_in_an_ambient_module_declaration_cannot_reference_module_through_relative_module_name);
76327                     return false;
76328                 }
76329             }
76330             return true;
76331         }
76332         function checkAliasSymbol(node) {
76333             var symbol = getSymbolOfNode(node);
76334             var target = resolveAlias(symbol);
76335             if (target !== unknownSymbol) {
76336                 // For external modules, `symbol` represents the local symbol for an alias.
76337                 // This local symbol will merge any other local declarations (excluding other aliases)
76338                 // and symbol.flags will contains combined representation for all merged declaration.
76339                 // Based on symbol.flags we can compute a set of excluded meanings (meaning that resolved alias should not have,
76340                 // otherwise it will conflict with some local declaration). Note that in addition to normal flags we include matching SymbolFlags.Export*
76341                 // in order to prevent collisions with declarations that were exported from the current module (they still contribute to local names).
76342                 symbol = getMergedSymbol(symbol.exportSymbol || symbol);
76343                 var excludedMeanings = (symbol.flags & (111551 /* Value */ | 1048576 /* ExportValue */) ? 111551 /* Value */ : 0) |
76344                     (symbol.flags & 788968 /* Type */ ? 788968 /* Type */ : 0) |
76345                     (symbol.flags & 1920 /* Namespace */ ? 1920 /* Namespace */ : 0);
76346                 if (target.flags & excludedMeanings) {
76347                     var message = node.kind === 270 /* ExportSpecifier */ ?
76348                         ts.Diagnostics.Export_declaration_conflicts_with_exported_declaration_of_0 :
76349                         ts.Diagnostics.Import_declaration_conflicts_with_local_declaration_of_0;
76350                     error(node, message, symbolToString(symbol));
76351                 }
76352                 // Don't allow to re-export something with no value side when `--isolatedModules` is set.
76353                 if (compilerOptions.isolatedModules
76354                     && node.kind === 270 /* ExportSpecifier */
76355                     && !node.parent.parent.isTypeOnly
76356                     && !(target.flags & 111551 /* Value */)
76357                     && !(node.flags & 8388608 /* Ambient */)) {
76358                     error(node, ts.Diagnostics.Re_exporting_a_type_when_the_isolatedModules_flag_is_provided_requires_using_export_type);
76359                 }
76360                 if (ts.isImportSpecifier(node) && ts.every(target.declarations, function (d) { return !!(ts.getCombinedNodeFlags(d) & 134217728 /* Deprecated */); })) {
76361                     errorOrSuggestion(/* isError */ false, node.name, ts.Diagnostics._0_is_deprecated, symbol.escapedName);
76362                 }
76363             }
76364         }
76365         function checkImportBinding(node) {
76366             checkCollisionWithRequireExportsInGeneratedCode(node, node.name);
76367             checkCollisionWithGlobalPromiseInGeneratedCode(node, node.name);
76368             checkAliasSymbol(node);
76369             if (node.kind === 265 /* ImportSpecifier */ &&
76370                 ts.idText(node.propertyName || node.name) === "default" &&
76371                 compilerOptions.esModuleInterop &&
76372                 moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
76373                 checkExternalEmitHelpers(node, 262144 /* ImportDefault */);
76374             }
76375         }
76376         function checkImportDeclaration(node) {
76377             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
76378                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
76379                 return;
76380             }
76381             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
76382                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_import_declaration_cannot_have_modifiers);
76383             }
76384             if (checkExternalImportOrExportDeclaration(node)) {
76385                 var importClause = node.importClause;
76386                 if (importClause && !checkGrammarImportClause(importClause)) {
76387                     if (importClause.name) {
76388                         checkImportBinding(importClause);
76389                     }
76390                     if (importClause.namedBindings) {
76391                         if (importClause.namedBindings.kind === 263 /* NamespaceImport */) {
76392                             checkImportBinding(importClause.namedBindings);
76393                             if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015 && compilerOptions.esModuleInterop) {
76394                                 // import * as ns from "foo";
76395                                 checkExternalEmitHelpers(node, 131072 /* ImportStar */);
76396                             }
76397                         }
76398                         else {
76399                             var moduleExisted = resolveExternalModuleName(node, node.moduleSpecifier);
76400                             if (moduleExisted) {
76401                                 ts.forEach(importClause.namedBindings.elements, checkImportBinding);
76402                             }
76403                         }
76404                     }
76405                 }
76406             }
76407         }
76408         function checkImportEqualsDeclaration(node) {
76409             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_import_declaration_can_only_be_used_in_a_namespace_or_module)) {
76410                 // If we hit an import declaration in an illegal context, just bail out to avoid cascading errors.
76411                 return;
76412             }
76413             checkGrammarDecoratorsAndModifiers(node);
76414             if (ts.isInternalModuleImportEqualsDeclaration(node) || checkExternalImportOrExportDeclaration(node)) {
76415                 checkImportBinding(node);
76416                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
76417                     markExportAsReferenced(node);
76418                 }
76419                 if (node.moduleReference.kind !== 272 /* ExternalModuleReference */) {
76420                     var target = resolveAlias(getSymbolOfNode(node));
76421                     if (target !== unknownSymbol) {
76422                         if (target.flags & 111551 /* Value */) {
76423                             // Target is a value symbol, check that it is not hidden by a local declaration with the same name
76424                             var moduleName = ts.getFirstIdentifier(node.moduleReference);
76425                             if (!(resolveEntityName(moduleName, 111551 /* Value */ | 1920 /* Namespace */).flags & 1920 /* Namespace */)) {
76426                                 error(moduleName, ts.Diagnostics.Module_0_is_hidden_by_a_local_declaration_with_the_same_name, ts.declarationNameToString(moduleName));
76427                             }
76428                         }
76429                         if (target.flags & 788968 /* Type */) {
76430                             checkTypeNameIsReserved(node.name, ts.Diagnostics.Import_name_cannot_be_0);
76431                         }
76432                     }
76433                 }
76434                 else {
76435                     if (moduleKind >= ts.ModuleKind.ES2015 && !(node.flags & 8388608 /* Ambient */)) {
76436                         // Import equals declaration is deprecated in es6 or above
76437                         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);
76438                     }
76439                 }
76440             }
76441         }
76442         function checkExportDeclaration(node) {
76443             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_declaration_can_only_be_used_in_a_module)) {
76444                 // If we hit an export in an illegal context, just bail out to avoid cascading errors.
76445                 return;
76446             }
76447             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
76448                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_declaration_cannot_have_modifiers);
76449             }
76450             if (node.moduleSpecifier && node.exportClause && ts.isNamedExports(node.exportClause) && ts.length(node.exportClause.elements) && languageVersion === 0 /* ES3 */) {
76451                 checkExternalEmitHelpers(node, 4194304 /* CreateBinding */);
76452             }
76453             checkGrammarExportDeclaration(node);
76454             if (!node.moduleSpecifier || checkExternalImportOrExportDeclaration(node)) {
76455                 if (node.exportClause && !ts.isNamespaceExport(node.exportClause)) {
76456                     // export { x, y }
76457                     // export { x, y } from "foo"
76458                     ts.forEach(node.exportClause.elements, checkExportSpecifier);
76459                     var inAmbientExternalModule = node.parent.kind === 257 /* ModuleBlock */ && ts.isAmbientModule(node.parent.parent);
76460                     var inAmbientNamespaceDeclaration = !inAmbientExternalModule && node.parent.kind === 257 /* ModuleBlock */ &&
76461                         !node.moduleSpecifier && node.flags & 8388608 /* Ambient */;
76462                     if (node.parent.kind !== 297 /* SourceFile */ && !inAmbientExternalModule && !inAmbientNamespaceDeclaration) {
76463                         error(node, ts.Diagnostics.Export_declarations_are_not_permitted_in_a_namespace);
76464                     }
76465                 }
76466                 else {
76467                     // export * from "foo"
76468                     // export * as ns from "foo";
76469                     var moduleSymbol = resolveExternalModuleName(node, node.moduleSpecifier);
76470                     if (moduleSymbol && hasExportAssignmentSymbol(moduleSymbol)) {
76471                         error(node.moduleSpecifier, ts.Diagnostics.Module_0_uses_export_and_cannot_be_used_with_export_Asterisk, symbolToString(moduleSymbol));
76472                     }
76473                     else if (node.exportClause) {
76474                         checkAliasSymbol(node.exportClause);
76475                     }
76476                     if (moduleKind !== ts.ModuleKind.System && moduleKind < ts.ModuleKind.ES2015) {
76477                         if (node.exportClause) {
76478                             // export * as ns from "foo";
76479                             // For ES2015 modules, we emit it as a pair of `import * as a_1 ...; export { a_1 as ns }` and don't need the helper.
76480                             // We only use the helper here when in esModuleInterop
76481                             if (compilerOptions.esModuleInterop) {
76482                                 checkExternalEmitHelpers(node, 131072 /* ImportStar */);
76483                             }
76484                         }
76485                         else {
76486                             // export * from "foo"
76487                             checkExternalEmitHelpers(node, 65536 /* ExportStar */);
76488                         }
76489                     }
76490                 }
76491             }
76492         }
76493         function checkGrammarExportDeclaration(node) {
76494             var _a;
76495             var isTypeOnlyExportStar = node.isTypeOnly && ((_a = node.exportClause) === null || _a === void 0 ? void 0 : _a.kind) !== 268 /* NamedExports */;
76496             if (isTypeOnlyExportStar) {
76497                 grammarErrorOnNode(node, ts.Diagnostics.Only_named_exports_may_use_export_type);
76498             }
76499             return !isTypeOnlyExportStar;
76500         }
76501         function checkGrammarModuleElementContext(node, errorMessage) {
76502             var isInAppropriateContext = node.parent.kind === 297 /* SourceFile */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 256 /* ModuleDeclaration */;
76503             if (!isInAppropriateContext) {
76504                 grammarErrorOnFirstToken(node, errorMessage);
76505             }
76506             return !isInAppropriateContext;
76507         }
76508         function importClauseContainsReferencedImport(importClause) {
76509             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
76510                 return !!getSymbolOfNode(declaration).isReferenced;
76511             });
76512         }
76513         function importClauseContainsConstEnumUsedAsValue(importClause) {
76514             return ts.forEachImportClauseDeclaration(importClause, function (declaration) {
76515                 return !!getSymbolLinks(getSymbolOfNode(declaration)).constEnumReferenced;
76516             });
76517         }
76518         function checkImportsForTypeOnlyConversion(sourceFile) {
76519             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
76520                 var statement = _a[_i];
76521                 if (ts.isImportDeclaration(statement) &&
76522                     statement.importClause &&
76523                     !statement.importClause.isTypeOnly &&
76524                     importClauseContainsReferencedImport(statement.importClause) &&
76525                     !isReferencedAliasDeclaration(statement.importClause, /*checkChildren*/ true) &&
76526                     !importClauseContainsConstEnumUsedAsValue(statement.importClause)) {
76527                     error(statement, ts.Diagnostics.This_import_is_never_used_as_a_value_and_must_use_import_type_because_the_importsNotUsedAsValues_is_set_to_error);
76528                 }
76529             }
76530         }
76531         function checkExportSpecifier(node) {
76532             checkAliasSymbol(node);
76533             if (ts.getEmitDeclarations(compilerOptions)) {
76534                 collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
76535             }
76536             if (!node.parent.parent.moduleSpecifier) {
76537                 var exportedName = node.propertyName || node.name;
76538                 // find immediate value referenced by exported name (SymbolFlags.Alias is set so we don't chase down aliases)
76539                 var symbol = resolveName(exportedName, exportedName.escapedText, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, 
76540                 /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
76541                 if (symbol && (symbol === undefinedSymbol || symbol === globalThisSymbol || isGlobalSourceFile(getDeclarationContainer(symbol.declarations[0])))) {
76542                     error(exportedName, ts.Diagnostics.Cannot_export_0_Only_local_declarations_can_be_exported_from_a_module, ts.idText(exportedName));
76543                 }
76544                 else {
76545                     markExportAsReferenced(node);
76546                     var target = symbol && (symbol.flags & 2097152 /* Alias */ ? resolveAlias(symbol) : symbol);
76547                     if (!target || target === unknownSymbol || target.flags & 111551 /* Value */) {
76548                         checkExpressionCached(node.propertyName || node.name);
76549                     }
76550                 }
76551             }
76552             else {
76553                 if (compilerOptions.esModuleInterop &&
76554                     moduleKind !== ts.ModuleKind.System &&
76555                     moduleKind < ts.ModuleKind.ES2015 &&
76556                     ts.idText(node.propertyName || node.name) === "default") {
76557                     checkExternalEmitHelpers(node, 262144 /* ImportDefault */);
76558                 }
76559             }
76560         }
76561         function checkExportAssignment(node) {
76562             if (checkGrammarModuleElementContext(node, ts.Diagnostics.An_export_assignment_can_only_be_used_in_a_module)) {
76563                 // If we hit an export assignment in an illegal context, just bail out to avoid cascading errors.
76564                 return;
76565             }
76566             var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent;
76567             if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
76568                 if (node.isExportEquals) {
76569                     error(node, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_namespace);
76570                 }
76571                 else {
76572                     error(node, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
76573                 }
76574                 return;
76575             }
76576             // Grammar checking
76577             if (!checkGrammarDecoratorsAndModifiers(node) && ts.hasEffectiveModifiers(node)) {
76578                 grammarErrorOnFirstToken(node, ts.Diagnostics.An_export_assignment_cannot_have_modifiers);
76579             }
76580             if (node.expression.kind === 78 /* Identifier */) {
76581                 var id = node.expression;
76582                 var sym = resolveEntityName(id, 67108863 /* All */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, node);
76583                 if (sym) {
76584                     markAliasReferenced(sym, id);
76585                     // If not a value, we're interpreting the identifier as a type export, along the lines of (`export { Id as default }`)
76586                     var target = sym.flags & 2097152 /* Alias */ ? resolveAlias(sym) : sym;
76587                     if (target === unknownSymbol || target.flags & 111551 /* Value */) {
76588                         // However if it is a value, we need to check it's being used correctly
76589                         checkExpressionCached(node.expression);
76590                     }
76591                 }
76592                 else {
76593                     checkExpressionCached(node.expression); // doesn't resolve, check as expression to mark as error
76594                 }
76595                 if (ts.getEmitDeclarations(compilerOptions)) {
76596                     collectLinkedAliases(node.expression, /*setVisibility*/ true);
76597                 }
76598             }
76599             else {
76600                 checkExpressionCached(node.expression);
76601             }
76602             checkExternalModuleExports(container);
76603             if ((node.flags & 8388608 /* Ambient */) && !ts.isEntityNameExpression(node.expression)) {
76604                 grammarErrorOnNode(node.expression, ts.Diagnostics.The_expression_of_an_export_assignment_must_be_an_identifier_or_qualified_name_in_an_ambient_context);
76605             }
76606             if (node.isExportEquals && !(node.flags & 8388608 /* Ambient */)) {
76607                 if (moduleKind >= ts.ModuleKind.ES2015) {
76608                     // export assignment is not supported in es6 modules
76609                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_cannot_be_used_when_targeting_ECMAScript_modules_Consider_using_export_default_or_another_module_format_instead);
76610                 }
76611                 else if (moduleKind === ts.ModuleKind.System) {
76612                     // system modules does not support export assignment
76613                     grammarErrorOnNode(node, ts.Diagnostics.Export_assignment_is_not_supported_when_module_flag_is_system);
76614                 }
76615             }
76616         }
76617         function hasExportedMembers(moduleSymbol) {
76618             return ts.forEachEntry(moduleSymbol.exports, function (_, id) { return id !== "export="; });
76619         }
76620         function checkExternalModuleExports(node) {
76621             var moduleSymbol = getSymbolOfNode(node);
76622             var links = getSymbolLinks(moduleSymbol);
76623             if (!links.exportsChecked) {
76624                 var exportEqualsSymbol = moduleSymbol.exports.get("export=");
76625                 if (exportEqualsSymbol && hasExportedMembers(moduleSymbol)) {
76626                     var declaration = getDeclarationOfAliasSymbol(exportEqualsSymbol) || exportEqualsSymbol.valueDeclaration;
76627                     if (!isTopLevelInExternalModuleAugmentation(declaration) && !ts.isInJSFile(declaration)) {
76628                         error(declaration, ts.Diagnostics.An_export_assignment_cannot_be_used_in_a_module_with_other_exported_elements);
76629                     }
76630                 }
76631                 // Checks for export * conflicts
76632                 var exports_2 = getExportsOfModule(moduleSymbol);
76633                 if (exports_2) {
76634                     exports_2.forEach(function (_a, id) {
76635                         var declarations = _a.declarations, flags = _a.flags;
76636                         if (id === "__export") {
76637                             return;
76638                         }
76639                         // ECMA262: 15.2.1.1 It is a Syntax Error if the ExportedNames of ModuleItemList contains any duplicate entries.
76640                         // (TS Exceptions: namespaces, function overloads, enums, and interfaces)
76641                         if (flags & (1920 /* Namespace */ | 64 /* Interface */ | 384 /* Enum */)) {
76642                             return;
76643                         }
76644                         var exportedDeclarationsCount = ts.countWhere(declarations, isNotOverloadAndNotAccessor);
76645                         if (flags & 524288 /* TypeAlias */ && exportedDeclarationsCount <= 2) {
76646                             // it is legal to merge type alias with other values
76647                             // so count should be either 1 (just type alias) or 2 (type alias + merged value)
76648                             return;
76649                         }
76650                         if (exportedDeclarationsCount > 1) {
76651                             for (var _i = 0, declarations_9 = declarations; _i < declarations_9.length; _i++) {
76652                                 var declaration = declarations_9[_i];
76653                                 if (isNotOverload(declaration)) {
76654                                     diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Cannot_redeclare_exported_variable_0, ts.unescapeLeadingUnderscores(id)));
76655                                 }
76656                             }
76657                         }
76658                     });
76659                 }
76660                 links.exportsChecked = true;
76661             }
76662         }
76663         function checkSourceElement(node) {
76664             if (node) {
76665                 var saveCurrentNode = currentNode;
76666                 currentNode = node;
76667                 instantiationCount = 0;
76668                 checkSourceElementWorker(node);
76669                 currentNode = saveCurrentNode;
76670             }
76671         }
76672         function checkSourceElementWorker(node) {
76673             if (ts.isInJSFile(node)) {
76674                 ts.forEach(node.jsDoc, function (_a) {
76675                     var tags = _a.tags;
76676                     return ts.forEach(tags, checkSourceElement);
76677                 });
76678             }
76679             var kind = node.kind;
76680             if (cancellationToken) {
76681                 // Only bother checking on a few construct kinds.  We don't want to be excessively
76682                 // hitting the cancellation token on every node we check.
76683                 switch (kind) {
76684                     case 256 /* ModuleDeclaration */:
76685                     case 252 /* ClassDeclaration */:
76686                     case 253 /* InterfaceDeclaration */:
76687                     case 251 /* FunctionDeclaration */:
76688                         cancellationToken.throwIfCancellationRequested();
76689                 }
76690             }
76691             if (kind >= 232 /* FirstStatement */ && kind <= 248 /* LastStatement */ && node.flowNode && !isReachableFlowNode(node.flowNode)) {
76692                 errorOrSuggestion(compilerOptions.allowUnreachableCode === false, node, ts.Diagnostics.Unreachable_code_detected);
76693             }
76694             switch (kind) {
76695                 case 159 /* TypeParameter */:
76696                     return checkTypeParameter(node);
76697                 case 160 /* Parameter */:
76698                     return checkParameter(node);
76699                 case 163 /* PropertyDeclaration */:
76700                     return checkPropertyDeclaration(node);
76701                 case 162 /* PropertySignature */:
76702                     return checkPropertySignature(node);
76703                 case 174 /* FunctionType */:
76704                 case 175 /* ConstructorType */:
76705                 case 169 /* CallSignature */:
76706                 case 170 /* ConstructSignature */:
76707                 case 171 /* IndexSignature */:
76708                     return checkSignatureDeclaration(node);
76709                 case 165 /* MethodDeclaration */:
76710                 case 164 /* MethodSignature */:
76711                     return checkMethodDeclaration(node);
76712                 case 166 /* Constructor */:
76713                     return checkConstructorDeclaration(node);
76714                 case 167 /* GetAccessor */:
76715                 case 168 /* SetAccessor */:
76716                     return checkAccessorDeclaration(node);
76717                 case 173 /* TypeReference */:
76718                     return checkTypeReferenceNode(node);
76719                 case 172 /* TypePredicate */:
76720                     return checkTypePredicate(node);
76721                 case 176 /* TypeQuery */:
76722                     return checkTypeQuery(node);
76723                 case 177 /* TypeLiteral */:
76724                     return checkTypeLiteral(node);
76725                 case 178 /* ArrayType */:
76726                     return checkArrayType(node);
76727                 case 179 /* TupleType */:
76728                     return checkTupleType(node);
76729                 case 182 /* UnionType */:
76730                 case 183 /* IntersectionType */:
76731                     return checkUnionOrIntersectionType(node);
76732                 case 186 /* ParenthesizedType */:
76733                 case 180 /* OptionalType */:
76734                 case 181 /* RestType */:
76735                     return checkSourceElement(node.type);
76736                 case 187 /* ThisType */:
76737                     return checkThisType(node);
76738                 case 188 /* TypeOperator */:
76739                     return checkTypeOperator(node);
76740                 case 184 /* ConditionalType */:
76741                     return checkConditionalType(node);
76742                 case 185 /* InferType */:
76743                     return checkInferType(node);
76744                 case 193 /* TemplateLiteralType */:
76745                     return checkTemplateLiteralType(node);
76746                 case 195 /* ImportType */:
76747                     return checkImportType(node);
76748                 case 192 /* NamedTupleMember */:
76749                     return checkNamedTupleMember(node);
76750                 case 315 /* JSDocAugmentsTag */:
76751                     return checkJSDocAugmentsTag(node);
76752                 case 316 /* JSDocImplementsTag */:
76753                     return checkJSDocImplementsTag(node);
76754                 case 331 /* JSDocTypedefTag */:
76755                 case 324 /* JSDocCallbackTag */:
76756                 case 325 /* JSDocEnumTag */:
76757                     return checkJSDocTypeAliasTag(node);
76758                 case 330 /* JSDocTemplateTag */:
76759                     return checkJSDocTemplateTag(node);
76760                 case 329 /* JSDocTypeTag */:
76761                     return checkJSDocTypeTag(node);
76762                 case 326 /* JSDocParameterTag */:
76763                     return checkJSDocParameterTag(node);
76764                 case 333 /* JSDocPropertyTag */:
76765                     return checkJSDocPropertyTag(node);
76766                 case 308 /* JSDocFunctionType */:
76767                     checkJSDocFunctionType(node);
76768                 // falls through
76769                 case 306 /* JSDocNonNullableType */:
76770                 case 305 /* JSDocNullableType */:
76771                 case 303 /* JSDocAllType */:
76772                 case 304 /* JSDocUnknownType */:
76773                 case 312 /* JSDocTypeLiteral */:
76774                     checkJSDocTypeIsInJsFile(node);
76775                     ts.forEachChild(node, checkSourceElement);
76776                     return;
76777                 case 309 /* JSDocVariadicType */:
76778                     checkJSDocVariadicType(node);
76779                     return;
76780                 case 301 /* JSDocTypeExpression */:
76781                     return checkSourceElement(node.type);
76782                 case 189 /* IndexedAccessType */:
76783                     return checkIndexedAccessType(node);
76784                 case 190 /* MappedType */:
76785                     return checkMappedType(node);
76786                 case 251 /* FunctionDeclaration */:
76787                     return checkFunctionDeclaration(node);
76788                 case 230 /* Block */:
76789                 case 257 /* ModuleBlock */:
76790                     return checkBlock(node);
76791                 case 232 /* VariableStatement */:
76792                     return checkVariableStatement(node);
76793                 case 233 /* ExpressionStatement */:
76794                     return checkExpressionStatement(node);
76795                 case 234 /* IfStatement */:
76796                     return checkIfStatement(node);
76797                 case 235 /* DoStatement */:
76798                     return checkDoStatement(node);
76799                 case 236 /* WhileStatement */:
76800                     return checkWhileStatement(node);
76801                 case 237 /* ForStatement */:
76802                     return checkForStatement(node);
76803                 case 238 /* ForInStatement */:
76804                     return checkForInStatement(node);
76805                 case 239 /* ForOfStatement */:
76806                     return checkForOfStatement(node);
76807                 case 240 /* ContinueStatement */:
76808                 case 241 /* BreakStatement */:
76809                     return checkBreakOrContinueStatement(node);
76810                 case 242 /* ReturnStatement */:
76811                     return checkReturnStatement(node);
76812                 case 243 /* WithStatement */:
76813                     return checkWithStatement(node);
76814                 case 244 /* SwitchStatement */:
76815                     return checkSwitchStatement(node);
76816                 case 245 /* LabeledStatement */:
76817                     return checkLabeledStatement(node);
76818                 case 246 /* ThrowStatement */:
76819                     return checkThrowStatement(node);
76820                 case 247 /* TryStatement */:
76821                     return checkTryStatement(node);
76822                 case 249 /* VariableDeclaration */:
76823                     return checkVariableDeclaration(node);
76824                 case 198 /* BindingElement */:
76825                     return checkBindingElement(node);
76826                 case 252 /* ClassDeclaration */:
76827                     return checkClassDeclaration(node);
76828                 case 253 /* InterfaceDeclaration */:
76829                     return checkInterfaceDeclaration(node);
76830                 case 254 /* TypeAliasDeclaration */:
76831                     return checkTypeAliasDeclaration(node);
76832                 case 255 /* EnumDeclaration */:
76833                     return checkEnumDeclaration(node);
76834                 case 256 /* ModuleDeclaration */:
76835                     return checkModuleDeclaration(node);
76836                 case 261 /* ImportDeclaration */:
76837                     return checkImportDeclaration(node);
76838                 case 260 /* ImportEqualsDeclaration */:
76839                     return checkImportEqualsDeclaration(node);
76840                 case 267 /* ExportDeclaration */:
76841                     return checkExportDeclaration(node);
76842                 case 266 /* ExportAssignment */:
76843                     return checkExportAssignment(node);
76844                 case 231 /* EmptyStatement */:
76845                 case 248 /* DebuggerStatement */:
76846                     checkGrammarStatementInAmbientContext(node);
76847                     return;
76848                 case 271 /* MissingDeclaration */:
76849                     return checkMissingDeclaration(node);
76850             }
76851         }
76852         function checkJSDocTypeIsInJsFile(node) {
76853             if (!ts.isInJSFile(node)) {
76854                 grammarErrorOnNode(node, ts.Diagnostics.JSDoc_types_can_only_be_used_inside_documentation_comments);
76855             }
76856         }
76857         function checkJSDocVariadicType(node) {
76858             checkJSDocTypeIsInJsFile(node);
76859             checkSourceElement(node.type);
76860             // Only legal location is in the *last* parameter tag or last parameter of a JSDoc function.
76861             var parent = node.parent;
76862             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
76863                 if (ts.last(parent.parent.parameters) !== parent) {
76864                     error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
76865                 }
76866                 return;
76867             }
76868             if (!ts.isJSDocTypeExpression(parent)) {
76869                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
76870             }
76871             var paramTag = node.parent.parent;
76872             if (!ts.isJSDocParameterTag(paramTag)) {
76873                 error(node, ts.Diagnostics.JSDoc_may_only_appear_in_the_last_parameter_of_a_signature);
76874                 return;
76875             }
76876             var param = ts.getParameterSymbolFromJSDoc(paramTag);
76877             if (!param) {
76878                 // We will error in `checkJSDocParameterTag`.
76879                 return;
76880             }
76881             var host = ts.getHostSignatureFromJSDoc(paramTag);
76882             if (!host || ts.last(host.parameters).symbol !== param) {
76883                 error(node, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
76884             }
76885         }
76886         function getTypeFromJSDocVariadicType(node) {
76887             var type = getTypeFromTypeNode(node.type);
76888             var parent = node.parent;
76889             var paramTag = node.parent.parent;
76890             if (ts.isJSDocTypeExpression(node.parent) && ts.isJSDocParameterTag(paramTag)) {
76891                 // Else we will add a diagnostic, see `checkJSDocVariadicType`.
76892                 var host_1 = ts.getHostSignatureFromJSDoc(paramTag);
76893                 if (host_1) {
76894                     /*
76895                     Only return an array type if the corresponding parameter is marked as a rest parameter, or if there are no parameters.
76896                     So in the following situation we will not create an array type:
76897                         /** @param {...number} a * /
76898                         function f(a) {}
76899                     Because `a` will just be of type `number | undefined`. A synthetic `...args` will also be added, which *will* get an array type.
76900                     */
76901                     var lastParamDeclaration = ts.lastOrUndefined(host_1.parameters);
76902                     var symbol = ts.getParameterSymbolFromJSDoc(paramTag);
76903                     if (!lastParamDeclaration ||
76904                         symbol && lastParamDeclaration.symbol === symbol && ts.isRestParameter(lastParamDeclaration)) {
76905                         return createArrayType(type);
76906                     }
76907                 }
76908             }
76909             if (ts.isParameter(parent) && ts.isJSDocFunctionType(parent.parent)) {
76910                 return createArrayType(type);
76911             }
76912             return addOptionality(type);
76913         }
76914         // Function and class expression bodies are checked after all statements in the enclosing body. This is
76915         // to ensure constructs like the following are permitted:
76916         //     const foo = function () {
76917         //        const s = foo();
76918         //        return "hello";
76919         //     }
76920         // Here, performing a full type check of the body of the function expression whilst in the process of
76921         // determining the type of foo would cause foo to be given type any because of the recursive reference.
76922         // Delaying the type check of the body ensures foo has been assigned a type.
76923         function checkNodeDeferred(node) {
76924             var enclosingFile = ts.getSourceFileOfNode(node);
76925             var links = getNodeLinks(enclosingFile);
76926             if (!(links.flags & 1 /* TypeChecked */)) {
76927                 links.deferredNodes = links.deferredNodes || new ts.Map();
76928                 var id = getNodeId(node);
76929                 links.deferredNodes.set(id, node);
76930             }
76931         }
76932         function checkDeferredNodes(context) {
76933             var links = getNodeLinks(context);
76934             if (links.deferredNodes) {
76935                 links.deferredNodes.forEach(checkDeferredNode);
76936             }
76937         }
76938         function checkDeferredNode(node) {
76939             var saveCurrentNode = currentNode;
76940             currentNode = node;
76941             instantiationCount = 0;
76942             switch (node.kind) {
76943                 case 203 /* CallExpression */:
76944                 case 204 /* NewExpression */:
76945                 case 205 /* TaggedTemplateExpression */:
76946                 case 161 /* Decorator */:
76947                 case 275 /* JsxOpeningElement */:
76948                     // These node kinds are deferred checked when overload resolution fails
76949                     // To save on work, we ensure the arguments are checked just once, in
76950                     // a deferred way
76951                     resolveUntypedCall(node);
76952                     break;
76953                 case 208 /* FunctionExpression */:
76954                 case 209 /* ArrowFunction */:
76955                 case 165 /* MethodDeclaration */:
76956                 case 164 /* MethodSignature */:
76957                     checkFunctionExpressionOrObjectLiteralMethodDeferred(node);
76958                     break;
76959                 case 167 /* GetAccessor */:
76960                 case 168 /* SetAccessor */:
76961                     checkAccessorDeclaration(node);
76962                     break;
76963                 case 221 /* ClassExpression */:
76964                     checkClassExpressionDeferred(node);
76965                     break;
76966                 case 274 /* JsxSelfClosingElement */:
76967                     checkJsxSelfClosingElementDeferred(node);
76968                     break;
76969                 case 273 /* JsxElement */:
76970                     checkJsxElementDeferred(node);
76971                     break;
76972             }
76973             currentNode = saveCurrentNode;
76974         }
76975         function checkSourceFile(node) {
76976             var tracingData = ["check" /* Check */, "checkSourceFile", { path: node.path }];
76977             ts.tracing.begin.apply(ts.tracing, tracingData);
76978             ts.performance.mark("beforeCheck");
76979             checkSourceFileWorker(node);
76980             ts.performance.mark("afterCheck");
76981             ts.performance.measure("Check", "beforeCheck", "afterCheck");
76982             ts.tracing.end.apply(ts.tracing, tracingData);
76983         }
76984         function unusedIsError(kind, isAmbient) {
76985             if (isAmbient) {
76986                 return false;
76987             }
76988             switch (kind) {
76989                 case 0 /* Local */:
76990                     return !!compilerOptions.noUnusedLocals;
76991                 case 1 /* Parameter */:
76992                     return !!compilerOptions.noUnusedParameters;
76993                 default:
76994                     return ts.Debug.assertNever(kind);
76995             }
76996         }
76997         function getPotentiallyUnusedIdentifiers(sourceFile) {
76998             return allPotentiallyUnusedIdentifiers.get(sourceFile.path) || ts.emptyArray;
76999         }
77000         // Fully type check a source file and collect the relevant diagnostics.
77001         function checkSourceFileWorker(node) {
77002             var links = getNodeLinks(node);
77003             if (!(links.flags & 1 /* TypeChecked */)) {
77004                 if (ts.skipTypeChecking(node, compilerOptions, host)) {
77005                     return;
77006                 }
77007                 // Grammar checking
77008                 checkGrammarSourceFile(node);
77009                 ts.clear(potentialThisCollisions);
77010                 ts.clear(potentialNewTargetCollisions);
77011                 ts.clear(potentialWeakMapCollisions);
77012                 ts.forEach(node.statements, checkSourceElement);
77013                 checkSourceElement(node.endOfFileToken);
77014                 checkDeferredNodes(node);
77015                 if (ts.isExternalOrCommonJsModule(node)) {
77016                     registerForUnusedIdentifiersCheck(node);
77017                 }
77018                 if (!node.isDeclarationFile && (compilerOptions.noUnusedLocals || compilerOptions.noUnusedParameters)) {
77019                     checkUnusedIdentifiers(getPotentiallyUnusedIdentifiers(node), function (containingNode, kind, diag) {
77020                         if (!ts.containsParseError(containingNode) && unusedIsError(kind, !!(containingNode.flags & 8388608 /* Ambient */))) {
77021                             diagnostics.add(diag);
77022                         }
77023                     });
77024                 }
77025                 if (compilerOptions.importsNotUsedAsValues === 2 /* Error */ &&
77026                     !node.isDeclarationFile &&
77027                     ts.isExternalModule(node)) {
77028                     checkImportsForTypeOnlyConversion(node);
77029                 }
77030                 if (ts.isExternalOrCommonJsModule(node)) {
77031                     checkExternalModuleExports(node);
77032                 }
77033                 if (potentialThisCollisions.length) {
77034                     ts.forEach(potentialThisCollisions, checkIfThisIsCapturedInEnclosingScope);
77035                     ts.clear(potentialThisCollisions);
77036                 }
77037                 if (potentialNewTargetCollisions.length) {
77038                     ts.forEach(potentialNewTargetCollisions, checkIfNewTargetIsCapturedInEnclosingScope);
77039                     ts.clear(potentialNewTargetCollisions);
77040                 }
77041                 if (potentialWeakMapCollisions.length) {
77042                     ts.forEach(potentialWeakMapCollisions, checkWeakMapCollision);
77043                     ts.clear(potentialWeakMapCollisions);
77044                 }
77045                 links.flags |= 1 /* TypeChecked */;
77046             }
77047         }
77048         function getDiagnostics(sourceFile, ct) {
77049             try {
77050                 // Record the cancellation token so it can be checked later on during checkSourceElement.
77051                 // Do this in a finally block so we can ensure that it gets reset back to nothing after
77052                 // this call is done.
77053                 cancellationToken = ct;
77054                 return getDiagnosticsWorker(sourceFile);
77055             }
77056             finally {
77057                 cancellationToken = undefined;
77058             }
77059         }
77060         function getDiagnosticsWorker(sourceFile) {
77061             throwIfNonDiagnosticsProducing();
77062             if (sourceFile) {
77063                 // Some global diagnostics are deferred until they are needed and
77064                 // may not be reported in the first call to getGlobalDiagnostics.
77065                 // We should catch these changes and report them.
77066                 var previousGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
77067                 var previousGlobalDiagnosticsSize = previousGlobalDiagnostics.length;
77068                 checkSourceFile(sourceFile);
77069                 var semanticDiagnostics = diagnostics.getDiagnostics(sourceFile.fileName);
77070                 var currentGlobalDiagnostics = diagnostics.getGlobalDiagnostics();
77071                 if (currentGlobalDiagnostics !== previousGlobalDiagnostics) {
77072                     // If the arrays are not the same reference, new diagnostics were added.
77073                     var deferredGlobalDiagnostics = ts.relativeComplement(previousGlobalDiagnostics, currentGlobalDiagnostics, ts.compareDiagnostics);
77074                     return ts.concatenate(deferredGlobalDiagnostics, semanticDiagnostics);
77075                 }
77076                 else if (previousGlobalDiagnosticsSize === 0 && currentGlobalDiagnostics.length > 0) {
77077                     // If the arrays are the same reference, but the length has changed, a single
77078                     // new diagnostic was added as DiagnosticCollection attempts to reuse the
77079                     // same array.
77080                     return ts.concatenate(currentGlobalDiagnostics, semanticDiagnostics);
77081                 }
77082                 return semanticDiagnostics;
77083             }
77084             // Global diagnostics are always added when a file is not provided to
77085             // getDiagnostics
77086             ts.forEach(host.getSourceFiles(), checkSourceFile);
77087             return diagnostics.getDiagnostics();
77088         }
77089         function getGlobalDiagnostics() {
77090             throwIfNonDiagnosticsProducing();
77091             return diagnostics.getGlobalDiagnostics();
77092         }
77093         function throwIfNonDiagnosticsProducing() {
77094             if (!produceDiagnostics) {
77095                 throw new Error("Trying to get diagnostics from a type checker that does not produce them.");
77096             }
77097         }
77098         // Language service support
77099         function getSymbolsInScope(location, meaning) {
77100             if (location.flags & 16777216 /* InWithStatement */) {
77101                 // We cannot answer semantic questions within a with block, do not proceed any further
77102                 return [];
77103             }
77104             var symbols = ts.createSymbolTable();
77105             var isStatic = false;
77106             populateSymbols();
77107             symbols.delete("this" /* This */); // Not a symbol, a keyword
77108             return symbolsToArray(symbols);
77109             function populateSymbols() {
77110                 while (location) {
77111                     if (location.locals && !isGlobalSourceFile(location)) {
77112                         copySymbols(location.locals, meaning);
77113                     }
77114                     switch (location.kind) {
77115                         case 297 /* SourceFile */:
77116                             if (!ts.isExternalOrCommonJsModule(location))
77117                                 break;
77118                         // falls through
77119                         case 256 /* ModuleDeclaration */:
77120                             copySymbols(getSymbolOfNode(location).exports, meaning & 2623475 /* ModuleMember */);
77121                             break;
77122                         case 255 /* EnumDeclaration */:
77123                             copySymbols(getSymbolOfNode(location).exports, meaning & 8 /* EnumMember */);
77124                             break;
77125                         case 221 /* ClassExpression */:
77126                             var className = location.name;
77127                             if (className) {
77128                                 copySymbol(location.symbol, meaning);
77129                             }
77130                         // this fall-through is necessary because we would like to handle
77131                         // type parameter inside class expression similar to how we handle it in classDeclaration and interface Declaration.
77132                         // falls through
77133                         case 252 /* ClassDeclaration */:
77134                         case 253 /* InterfaceDeclaration */:
77135                             // If we didn't come from static member of class or interface,
77136                             // add the type parameters into the symbol table
77137                             // (type parameters of classDeclaration/classExpression and interface are in member property of the symbol.
77138                             // Note: that the memberFlags come from previous iteration.
77139                             if (!isStatic) {
77140                                 copySymbols(getMembersOfSymbol(getSymbolOfNode(location)), meaning & 788968 /* Type */);
77141                             }
77142                             break;
77143                         case 208 /* FunctionExpression */:
77144                             var funcName = location.name;
77145                             if (funcName) {
77146                                 copySymbol(location.symbol, meaning);
77147                             }
77148                             break;
77149                     }
77150                     if (ts.introducesArgumentsExoticObject(location)) {
77151                         copySymbol(argumentsSymbol, meaning);
77152                     }
77153                     isStatic = ts.hasSyntacticModifier(location, 32 /* Static */);
77154                     location = location.parent;
77155                 }
77156                 copySymbols(globals, meaning);
77157             }
77158             /**
77159              * Copy the given symbol into symbol tables if the symbol has the given meaning
77160              * and it doesn't already existed in the symbol table
77161              * @param key a key for storing in symbol table; if undefined, use symbol.name
77162              * @param symbol the symbol to be added into symbol table
77163              * @param meaning meaning of symbol to filter by before adding to symbol table
77164              */
77165             function copySymbol(symbol, meaning) {
77166                 if (ts.getCombinedLocalAndExportSymbolFlags(symbol) & meaning) {
77167                     var id = symbol.escapedName;
77168                     // We will copy all symbol regardless of its reserved name because
77169                     // symbolsToArray will check whether the key is a reserved name and
77170                     // it will not copy symbol with reserved name to the array
77171                     if (!symbols.has(id)) {
77172                         symbols.set(id, symbol);
77173                     }
77174                 }
77175             }
77176             function copySymbols(source, meaning) {
77177                 if (meaning) {
77178                     source.forEach(function (symbol) {
77179                         copySymbol(symbol, meaning);
77180                     });
77181                 }
77182             }
77183         }
77184         function isTypeDeclarationName(name) {
77185             return name.kind === 78 /* Identifier */ &&
77186                 isTypeDeclaration(name.parent) &&
77187                 ts.getNameOfDeclaration(name.parent) === name;
77188         }
77189         function isTypeDeclaration(node) {
77190             switch (node.kind) {
77191                 case 159 /* TypeParameter */:
77192                 case 252 /* ClassDeclaration */:
77193                 case 253 /* InterfaceDeclaration */:
77194                 case 254 /* TypeAliasDeclaration */:
77195                 case 255 /* EnumDeclaration */:
77196                 case 331 /* JSDocTypedefTag */:
77197                 case 324 /* JSDocCallbackTag */:
77198                 case 325 /* JSDocEnumTag */:
77199                     return true;
77200                 case 262 /* ImportClause */:
77201                     return node.isTypeOnly;
77202                 case 265 /* ImportSpecifier */:
77203                 case 270 /* ExportSpecifier */:
77204                     return node.parent.parent.isTypeOnly;
77205                 default:
77206                     return false;
77207             }
77208         }
77209         // True if the given identifier is part of a type reference
77210         function isTypeReferenceIdentifier(node) {
77211             while (node.parent.kind === 157 /* QualifiedName */) {
77212                 node = node.parent;
77213             }
77214             return node.parent.kind === 173 /* TypeReference */;
77215         }
77216         function isHeritageClauseElementIdentifier(node) {
77217             while (node.parent.kind === 201 /* PropertyAccessExpression */) {
77218                 node = node.parent;
77219             }
77220             return node.parent.kind === 223 /* ExpressionWithTypeArguments */;
77221         }
77222         function isJSDocEntryNameReference(node) {
77223             while (node.parent.kind === 157 /* QualifiedName */) {
77224                 node = node.parent;
77225             }
77226             while (node.parent.kind === 201 /* PropertyAccessExpression */) {
77227                 node = node.parent;
77228             }
77229             return node.parent.kind === 302 /* JSDocNameReference */;
77230         }
77231         function forEachEnclosingClass(node, callback) {
77232             var result;
77233             while (true) {
77234                 node = ts.getContainingClass(node);
77235                 if (!node)
77236                     break;
77237                 if (result = callback(node))
77238                     break;
77239             }
77240             return result;
77241         }
77242         function isNodeUsedDuringClassInitialization(node) {
77243             return !!ts.findAncestor(node, function (element) {
77244                 if (ts.isConstructorDeclaration(element) && ts.nodeIsPresent(element.body) || ts.isPropertyDeclaration(element)) {
77245                     return true;
77246                 }
77247                 else if (ts.isClassLike(element) || ts.isFunctionLikeDeclaration(element)) {
77248                     return "quit";
77249                 }
77250                 return false;
77251             });
77252         }
77253         function isNodeWithinClass(node, classDeclaration) {
77254             return !!forEachEnclosingClass(node, function (n) { return n === classDeclaration; });
77255         }
77256         function getLeftSideOfImportEqualsOrExportAssignment(nodeOnRightSide) {
77257             while (nodeOnRightSide.parent.kind === 157 /* QualifiedName */) {
77258                 nodeOnRightSide = nodeOnRightSide.parent;
77259             }
77260             if (nodeOnRightSide.parent.kind === 260 /* ImportEqualsDeclaration */) {
77261                 return nodeOnRightSide.parent.moduleReference === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
77262             }
77263             if (nodeOnRightSide.parent.kind === 266 /* ExportAssignment */) {
77264                 return nodeOnRightSide.parent.expression === nodeOnRightSide ? nodeOnRightSide.parent : undefined;
77265             }
77266             return undefined;
77267         }
77268         function isInRightSideOfImportOrExportAssignment(node) {
77269             return getLeftSideOfImportEqualsOrExportAssignment(node) !== undefined;
77270         }
77271         function getSpecialPropertyAssignmentSymbolFromEntityName(entityName) {
77272             var specialPropertyAssignmentKind = ts.getAssignmentDeclarationKind(entityName.parent.parent);
77273             switch (specialPropertyAssignmentKind) {
77274                 case 1 /* ExportsProperty */:
77275                 case 3 /* PrototypeProperty */:
77276                     return getSymbolOfNode(entityName.parent);
77277                 case 4 /* ThisProperty */:
77278                 case 2 /* ModuleExports */:
77279                 case 5 /* Property */:
77280                     return getSymbolOfNode(entityName.parent.parent);
77281             }
77282         }
77283         function isImportTypeQualifierPart(node) {
77284             var parent = node.parent;
77285             while (ts.isQualifiedName(parent)) {
77286                 node = parent;
77287                 parent = parent.parent;
77288             }
77289             if (parent && parent.kind === 195 /* ImportType */ && parent.qualifier === node) {
77290                 return parent;
77291             }
77292             return undefined;
77293         }
77294         function getSymbolOfNameOrPropertyAccessExpression(name) {
77295             if (ts.isDeclarationName(name)) {
77296                 return getSymbolOfNode(name.parent);
77297             }
77298             if (ts.isInJSFile(name) &&
77299                 name.parent.kind === 201 /* PropertyAccessExpression */ &&
77300                 name.parent === name.parent.parent.left) {
77301                 // Check if this is a special property assignment
77302                 if (!ts.isPrivateIdentifier(name)) {
77303                     var specialPropertyAssignmentSymbol = getSpecialPropertyAssignmentSymbolFromEntityName(name);
77304                     if (specialPropertyAssignmentSymbol) {
77305                         return specialPropertyAssignmentSymbol;
77306                     }
77307                 }
77308             }
77309             if (name.parent.kind === 266 /* ExportAssignment */ && ts.isEntityNameExpression(name)) {
77310                 // Even an entity name expression that doesn't resolve as an entityname may still typecheck as a property access expression
77311                 var success = resolveEntityName(name, 
77312                 /*all meanings*/ 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */, /*ignoreErrors*/ true);
77313                 if (success && success !== unknownSymbol) {
77314                     return success;
77315                 }
77316             }
77317             else if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name) && isInRightSideOfImportOrExportAssignment(name)) {
77318                 // Since we already checked for ExportAssignment, this really could only be an Import
77319                 var importEqualsDeclaration = ts.getAncestor(name, 260 /* ImportEqualsDeclaration */);
77320                 ts.Debug.assert(importEqualsDeclaration !== undefined);
77321                 return getSymbolOfPartOfRightHandSideOfImportEquals(name, /*dontResolveAlias*/ true);
77322             }
77323             if (!ts.isPropertyAccessExpression(name) && !ts.isPrivateIdentifier(name)) {
77324                 var possibleImportNode = isImportTypeQualifierPart(name);
77325                 if (possibleImportNode) {
77326                     getTypeFromTypeNode(possibleImportNode);
77327                     var sym = getNodeLinks(name).resolvedSymbol;
77328                     return sym === unknownSymbol ? undefined : sym;
77329                 }
77330             }
77331             while (ts.isRightSideOfQualifiedNameOrPropertyAccess(name)) {
77332                 name = name.parent;
77333             }
77334             if (isHeritageClauseElementIdentifier(name)) {
77335                 var meaning = 0 /* None */;
77336                 // In an interface or class, we're definitely interested in a type.
77337                 if (name.parent.kind === 223 /* ExpressionWithTypeArguments */) {
77338                     meaning = 788968 /* Type */;
77339                     // In a class 'extends' clause we are also looking for a value.
77340                     if (ts.isExpressionWithTypeArgumentsInClassExtendsClause(name.parent)) {
77341                         meaning |= 111551 /* Value */;
77342                     }
77343                 }
77344                 else {
77345                     meaning = 1920 /* Namespace */;
77346                 }
77347                 meaning |= 2097152 /* Alias */;
77348                 var entityNameSymbol = ts.isEntityNameExpression(name) ? resolveEntityName(name, meaning) : undefined;
77349                 if (entityNameSymbol) {
77350                     return entityNameSymbol;
77351                 }
77352             }
77353             if (name.parent.kind === 326 /* JSDocParameterTag */) {
77354                 return ts.getParameterSymbolFromJSDoc(name.parent);
77355             }
77356             if (name.parent.kind === 159 /* TypeParameter */ && name.parent.parent.kind === 330 /* JSDocTemplateTag */) {
77357                 ts.Debug.assert(!ts.isInJSFile(name)); // Otherwise `isDeclarationName` would have been true.
77358                 var typeParameter = ts.getTypeParameterFromJsDoc(name.parent);
77359                 return typeParameter && typeParameter.symbol;
77360             }
77361             if (ts.isExpressionNode(name)) {
77362                 if (ts.nodeIsMissing(name)) {
77363                     // Missing entity name.
77364                     return undefined;
77365                 }
77366                 if (name.kind === 78 /* Identifier */) {
77367                     if (ts.isJSXTagName(name) && isJsxIntrinsicIdentifier(name)) {
77368                         var symbol = getIntrinsicTagSymbol(name.parent);
77369                         return symbol === unknownSymbol ? undefined : symbol;
77370                     }
77371                     return resolveEntityName(name, 111551 /* Value */, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
77372                 }
77373                 else if (name.kind === 201 /* PropertyAccessExpression */ || name.kind === 157 /* QualifiedName */) {
77374                     var links = getNodeLinks(name);
77375                     if (links.resolvedSymbol) {
77376                         return links.resolvedSymbol;
77377                     }
77378                     if (name.kind === 201 /* PropertyAccessExpression */) {
77379                         checkPropertyAccessExpression(name);
77380                     }
77381                     else {
77382                         checkQualifiedName(name);
77383                     }
77384                     return links.resolvedSymbol;
77385                 }
77386             }
77387             else if (isTypeReferenceIdentifier(name)) {
77388                 var meaning = name.parent.kind === 173 /* TypeReference */ ? 788968 /* Type */ : 1920 /* Namespace */;
77389                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true);
77390             }
77391             else if (isJSDocEntryNameReference(name)) {
77392                 var meaning = 788968 /* Type */ | 1920 /* Namespace */ | 111551 /* Value */;
77393                 return resolveEntityName(name, meaning, /*ignoreErrors*/ false, /*dontResolveAlias*/ true, ts.getHostSignatureFromJSDoc(name));
77394             }
77395             if (name.parent.kind === 172 /* TypePredicate */) {
77396                 return resolveEntityName(name, /*meaning*/ 1 /* FunctionScopedVariable */);
77397             }
77398             // Do we want to return undefined here?
77399             return undefined;
77400         }
77401         function getSymbolAtLocation(node, ignoreErrors) {
77402             if (node.kind === 297 /* SourceFile */) {
77403                 return ts.isExternalModule(node) ? getMergedSymbol(node.symbol) : undefined;
77404             }
77405             var parent = node.parent;
77406             var grandParent = parent.parent;
77407             if (node.flags & 16777216 /* InWithStatement */) {
77408                 // We cannot answer semantic questions within a with block, do not proceed any further
77409                 return undefined;
77410             }
77411             if (isDeclarationNameOrImportPropertyName(node)) {
77412                 // This is a declaration, call getSymbolOfNode
77413                 var parentSymbol = getSymbolOfNode(parent);
77414                 return ts.isImportOrExportSpecifier(node.parent) && node.parent.propertyName === node
77415                     ? getImmediateAliasedSymbol(parentSymbol)
77416                     : parentSymbol;
77417             }
77418             else if (ts.isLiteralComputedPropertyDeclarationName(node)) {
77419                 return getSymbolOfNode(parent.parent);
77420             }
77421             if (node.kind === 78 /* Identifier */) {
77422                 if (isInRightSideOfImportOrExportAssignment(node)) {
77423                     return getSymbolOfNameOrPropertyAccessExpression(node);
77424                 }
77425                 else if (parent.kind === 198 /* BindingElement */ &&
77426                     grandParent.kind === 196 /* ObjectBindingPattern */ &&
77427                     node === parent.propertyName) {
77428                     var typeOfPattern = getTypeOfNode(grandParent);
77429                     var propertyDeclaration = getPropertyOfType(typeOfPattern, node.escapedText);
77430                     if (propertyDeclaration) {
77431                         return propertyDeclaration;
77432                     }
77433                 }
77434             }
77435             switch (node.kind) {
77436                 case 78 /* Identifier */:
77437                 case 79 /* PrivateIdentifier */:
77438                 case 201 /* PropertyAccessExpression */:
77439                 case 157 /* QualifiedName */:
77440                     return getSymbolOfNameOrPropertyAccessExpression(node);
77441                 case 107 /* ThisKeyword */:
77442                     var container = ts.getThisContainer(node, /*includeArrowFunctions*/ false);
77443                     if (ts.isFunctionLike(container)) {
77444                         var sig = getSignatureFromDeclaration(container);
77445                         if (sig.thisParameter) {
77446                             return sig.thisParameter;
77447                         }
77448                     }
77449                     if (ts.isInExpressionContext(node)) {
77450                         return checkExpression(node).symbol;
77451                     }
77452                 // falls through
77453                 case 187 /* ThisType */:
77454                     return getTypeFromThisTypeNode(node).symbol;
77455                 case 105 /* SuperKeyword */:
77456                     return checkExpression(node).symbol;
77457                 case 132 /* ConstructorKeyword */:
77458                     // constructor keyword for an overload, should take us to the definition if it exist
77459                     var constructorDeclaration = node.parent;
77460                     if (constructorDeclaration && constructorDeclaration.kind === 166 /* Constructor */) {
77461                         return constructorDeclaration.parent.symbol;
77462                     }
77463                     return undefined;
77464                 case 10 /* StringLiteral */:
77465                 case 14 /* NoSubstitutionTemplateLiteral */:
77466                     // 1). import x = require("./mo/*gotToDefinitionHere*/d")
77467                     // 2). External module name in an import declaration
77468                     // 3). Dynamic import call or require in javascript
77469                     // 4). type A = import("./f/*gotToDefinitionHere*/oo")
77470                     if ((ts.isExternalModuleImportEqualsDeclaration(node.parent.parent) && ts.getExternalModuleImportEqualsDeclarationExpression(node.parent.parent) === node) ||
77471                         ((node.parent.kind === 261 /* ImportDeclaration */ || node.parent.kind === 267 /* ExportDeclaration */) && node.parent.moduleSpecifier === node) ||
77472                         ((ts.isInJSFile(node) && ts.isRequireCall(node.parent, /*checkArgumentIsStringLiteralLike*/ false)) || ts.isImportCall(node.parent)) ||
77473                         (ts.isLiteralTypeNode(node.parent) && ts.isLiteralImportTypeNode(node.parent.parent) && node.parent.parent.argument === node.parent)) {
77474                         return resolveExternalModuleName(node, node, ignoreErrors);
77475                     }
77476                     if (ts.isCallExpression(parent) && ts.isBindableObjectDefinePropertyCall(parent) && parent.arguments[1] === node) {
77477                         return getSymbolOfNode(parent);
77478                     }
77479                 // falls through
77480                 case 8 /* NumericLiteral */:
77481                     // index access
77482                     var objectType = ts.isElementAccessExpression(parent)
77483                         ? parent.argumentExpression === node ? getTypeOfExpression(parent.expression) : undefined
77484                         : ts.isLiteralTypeNode(parent) && ts.isIndexedAccessTypeNode(grandParent)
77485                             ? getTypeFromTypeNode(grandParent.objectType)
77486                             : undefined;
77487                     return objectType && getPropertyOfType(objectType, ts.escapeLeadingUnderscores(node.text));
77488                 case 87 /* DefaultKeyword */:
77489                 case 97 /* FunctionKeyword */:
77490                 case 38 /* EqualsGreaterThanToken */:
77491                 case 83 /* ClassKeyword */:
77492                     return getSymbolOfNode(node.parent);
77493                 case 195 /* ImportType */:
77494                     return ts.isLiteralImportTypeNode(node) ? getSymbolAtLocation(node.argument.literal, ignoreErrors) : undefined;
77495                 case 92 /* ExportKeyword */:
77496                     return ts.isExportAssignment(node.parent) ? ts.Debug.checkDefined(node.parent.symbol) : undefined;
77497                 default:
77498                     return undefined;
77499             }
77500         }
77501         function getShorthandAssignmentValueSymbol(location) {
77502             if (location && location.kind === 289 /* ShorthandPropertyAssignment */) {
77503                 return resolveEntityName(location.name, 111551 /* Value */ | 2097152 /* Alias */);
77504             }
77505             return undefined;
77506         }
77507         /** Returns the target of an export specifier without following aliases */
77508         function getExportSpecifierLocalTargetSymbol(node) {
77509             if (ts.isExportSpecifier(node)) {
77510                 return node.parent.parent.moduleSpecifier ?
77511                     getExternalModuleMember(node.parent.parent, node) :
77512                     resolveEntityName(node.propertyName || node.name, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
77513             }
77514             else {
77515                 return resolveEntityName(node, 111551 /* Value */ | 788968 /* Type */ | 1920 /* Namespace */ | 2097152 /* Alias */);
77516             }
77517         }
77518         function getTypeOfNode(node) {
77519             if (ts.isSourceFile(node) && !ts.isExternalModule(node)) {
77520                 return errorType;
77521             }
77522             if (node.flags & 16777216 /* InWithStatement */) {
77523                 // We cannot answer semantic questions within a with block, do not proceed any further
77524                 return errorType;
77525             }
77526             var classDecl = ts.tryGetClassImplementingOrExtendingExpressionWithTypeArguments(node);
77527             var classType = classDecl && getDeclaredTypeOfClassOrInterface(getSymbolOfNode(classDecl.class));
77528             if (ts.isPartOfTypeNode(node)) {
77529                 var typeFromTypeNode = getTypeFromTypeNode(node);
77530                 return classType ? getTypeWithThisArgument(typeFromTypeNode, classType.thisType) : typeFromTypeNode;
77531             }
77532             if (ts.isExpressionNode(node)) {
77533                 return getRegularTypeOfExpression(node);
77534             }
77535             if (classType && !classDecl.isImplements) {
77536                 // A SyntaxKind.ExpressionWithTypeArguments is considered a type node, except when it occurs in the
77537                 // extends clause of a class. We handle that case here.
77538                 var baseType = ts.firstOrUndefined(getBaseTypes(classType));
77539                 return baseType ? getTypeWithThisArgument(baseType, classType.thisType) : errorType;
77540             }
77541             if (isTypeDeclaration(node)) {
77542                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
77543                 var symbol = getSymbolOfNode(node);
77544                 return getDeclaredTypeOfSymbol(symbol);
77545             }
77546             if (isTypeDeclarationName(node)) {
77547                 var symbol = getSymbolAtLocation(node);
77548                 return symbol ? getDeclaredTypeOfSymbol(symbol) : errorType;
77549             }
77550             if (ts.isDeclaration(node)) {
77551                 // In this case, we call getSymbolOfNode instead of getSymbolAtLocation because it is a declaration
77552                 var symbol = getSymbolOfNode(node);
77553                 return getTypeOfSymbol(symbol);
77554             }
77555             if (isDeclarationNameOrImportPropertyName(node)) {
77556                 var symbol = getSymbolAtLocation(node);
77557                 if (symbol) {
77558                     return getTypeOfSymbol(symbol);
77559                 }
77560                 return errorType;
77561             }
77562             if (ts.isBindingPattern(node)) {
77563                 return getTypeForVariableLikeDeclaration(node.parent, /*includeOptionality*/ true) || errorType;
77564             }
77565             if (isInRightSideOfImportOrExportAssignment(node)) {
77566                 var symbol = getSymbolAtLocation(node);
77567                 if (symbol) {
77568                     var declaredType = getDeclaredTypeOfSymbol(symbol);
77569                     return declaredType !== errorType ? declaredType : getTypeOfSymbol(symbol);
77570                 }
77571             }
77572             return errorType;
77573         }
77574         // Gets the type of object literal or array literal of destructuring assignment.
77575         // { a } from
77576         //     for ( { a } of elems) {
77577         //     }
77578         // [ a ] from
77579         //     [a] = [ some array ...]
77580         function getTypeOfAssignmentPattern(expr) {
77581             ts.Debug.assert(expr.kind === 200 /* ObjectLiteralExpression */ || expr.kind === 199 /* ArrayLiteralExpression */);
77582             // If this is from "for of"
77583             //     for ( { a } of elems) {
77584             //     }
77585             if (expr.parent.kind === 239 /* ForOfStatement */) {
77586                 var iteratedType = checkRightHandSideOfForOf(expr.parent);
77587                 return checkDestructuringAssignment(expr, iteratedType || errorType);
77588             }
77589             // If this is from "for" initializer
77590             //     for ({a } = elems[0];.....) { }
77591             if (expr.parent.kind === 216 /* BinaryExpression */) {
77592                 var iteratedType = getTypeOfExpression(expr.parent.right);
77593                 return checkDestructuringAssignment(expr, iteratedType || errorType);
77594             }
77595             // If this is from nested object binding pattern
77596             //     for ({ skills: { primary, secondary } } = multiRobot, i = 0; i < 1; i++) {
77597             if (expr.parent.kind === 288 /* PropertyAssignment */) {
77598                 var node_2 = ts.cast(expr.parent.parent, ts.isObjectLiteralExpression);
77599                 var typeOfParentObjectLiteral = getTypeOfAssignmentPattern(node_2) || errorType;
77600                 var propertyIndex = ts.indexOfNode(node_2.properties, expr.parent);
77601                 return checkObjectLiteralDestructuringPropertyAssignment(node_2, typeOfParentObjectLiteral, propertyIndex);
77602             }
77603             // Array literal assignment - array destructuring pattern
77604             var node = ts.cast(expr.parent, ts.isArrayLiteralExpression);
77605             //    [{ property1: p1, property2 }] = elems;
77606             var typeOfArrayLiteral = getTypeOfAssignmentPattern(node) || errorType;
77607             var elementType = checkIteratedTypeOrElementType(65 /* Destructuring */, typeOfArrayLiteral, undefinedType, expr.parent) || errorType;
77608             return checkArrayLiteralDestructuringElementAssignment(node, typeOfArrayLiteral, node.elements.indexOf(expr), elementType);
77609         }
77610         // Gets the property symbol corresponding to the property in destructuring assignment
77611         // 'property1' from
77612         //     for ( { property1: a } of elems) {
77613         //     }
77614         // 'property1' at location 'a' from:
77615         //     [a] = [ property1, property2 ]
77616         function getPropertySymbolOfDestructuringAssignment(location) {
77617             // Get the type of the object or array literal and then look for property of given name in the type
77618             var typeOfObjectLiteral = getTypeOfAssignmentPattern(ts.cast(location.parent.parent, ts.isAssignmentPattern));
77619             return typeOfObjectLiteral && getPropertyOfType(typeOfObjectLiteral, location.escapedText);
77620         }
77621         function getRegularTypeOfExpression(expr) {
77622             if (ts.isRightSideOfQualifiedNameOrPropertyAccess(expr)) {
77623                 expr = expr.parent;
77624             }
77625             return getRegularTypeOfLiteralType(getTypeOfExpression(expr));
77626         }
77627         /**
77628          * Gets either the static or instance type of a class element, based on
77629          * whether the element is declared as "static".
77630          */
77631         function getParentTypeOfClassElement(node) {
77632             var classSymbol = getSymbolOfNode(node.parent);
77633             return ts.hasSyntacticModifier(node, 32 /* Static */)
77634                 ? getTypeOfSymbol(classSymbol)
77635                 : getDeclaredTypeOfSymbol(classSymbol);
77636         }
77637         function getClassElementPropertyKeyType(element) {
77638             var name = element.name;
77639             switch (name.kind) {
77640                 case 78 /* Identifier */:
77641                     return getLiteralType(ts.idText(name));
77642                 case 8 /* NumericLiteral */:
77643                 case 10 /* StringLiteral */:
77644                     return getLiteralType(name.text);
77645                 case 158 /* ComputedPropertyName */:
77646                     var nameType = checkComputedPropertyName(name);
77647                     return isTypeAssignableToKind(nameType, 12288 /* ESSymbolLike */) ? nameType : stringType;
77648                 default:
77649                     return ts.Debug.fail("Unsupported property name.");
77650             }
77651         }
77652         // Return the list of properties of the given type, augmented with properties from Function
77653         // if the type has call or construct signatures
77654         function getAugmentedPropertiesOfType(type) {
77655             type = getApparentType(type);
77656             var propsByName = ts.createSymbolTable(getPropertiesOfType(type));
77657             var functionType = getSignaturesOfType(type, 0 /* Call */).length ? globalCallableFunctionType :
77658                 getSignaturesOfType(type, 1 /* Construct */).length ? globalNewableFunctionType :
77659                     undefined;
77660             if (functionType) {
77661                 ts.forEach(getPropertiesOfType(functionType), function (p) {
77662                     if (!propsByName.has(p.escapedName)) {
77663                         propsByName.set(p.escapedName, p);
77664                     }
77665                 });
77666             }
77667             return getNamedMembers(propsByName);
77668         }
77669         function typeHasCallOrConstructSignatures(type) {
77670             return ts.typeHasCallOrConstructSignatures(type, checker);
77671         }
77672         function getRootSymbols(symbol) {
77673             var roots = getImmediateRootSymbols(symbol);
77674             return roots ? ts.flatMap(roots, getRootSymbols) : [symbol];
77675         }
77676         function getImmediateRootSymbols(symbol) {
77677             if (ts.getCheckFlags(symbol) & 6 /* Synthetic */) {
77678                 return ts.mapDefined(getSymbolLinks(symbol).containingType.types, function (type) { return getPropertyOfType(type, symbol.escapedName); });
77679             }
77680             else if (symbol.flags & 33554432 /* Transient */) {
77681                 var _a = symbol, leftSpread = _a.leftSpread, rightSpread = _a.rightSpread, syntheticOrigin = _a.syntheticOrigin;
77682                 return leftSpread ? [leftSpread, rightSpread]
77683                     : syntheticOrigin ? [syntheticOrigin]
77684                         : ts.singleElementArray(tryGetAliasTarget(symbol));
77685             }
77686             return undefined;
77687         }
77688         function tryGetAliasTarget(symbol) {
77689             var target;
77690             var next = symbol;
77691             while (next = getSymbolLinks(next).target) {
77692                 target = next;
77693             }
77694             return target;
77695         }
77696         // Emitter support
77697         function isArgumentsLocalBinding(nodeIn) {
77698             // Note: does not handle isShorthandPropertyAssignment (and probably a few more)
77699             if (ts.isGeneratedIdentifier(nodeIn))
77700                 return false;
77701             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
77702             if (!node)
77703                 return false;
77704             var parent = node.parent;
77705             if (!parent)
77706                 return false;
77707             var isPropertyName = ((ts.isPropertyAccessExpression(parent)
77708                 || ts.isPropertyAssignment(parent))
77709                 && parent.name === node);
77710             return !isPropertyName && getReferencedValueSymbol(node) === argumentsSymbol;
77711         }
77712         function moduleExportsSomeValue(moduleReferenceExpression) {
77713             var moduleSymbol = resolveExternalModuleName(moduleReferenceExpression.parent, moduleReferenceExpression);
77714             if (!moduleSymbol || ts.isShorthandAmbientModuleSymbol(moduleSymbol)) {
77715                 // If the module is not found or is shorthand, assume that it may export a value.
77716                 return true;
77717             }
77718             var hasExportAssignment = hasExportAssignmentSymbol(moduleSymbol);
77719             // if module has export assignment then 'resolveExternalModuleSymbol' will return resolved symbol for export assignment
77720             // otherwise it will return moduleSymbol itself
77721             moduleSymbol = resolveExternalModuleSymbol(moduleSymbol);
77722             var symbolLinks = getSymbolLinks(moduleSymbol);
77723             if (symbolLinks.exportsSomeValue === undefined) {
77724                 // for export assignments - check if resolved symbol for RHS is itself a value
77725                 // otherwise - check if at least one export is value
77726                 symbolLinks.exportsSomeValue = hasExportAssignment
77727                     ? !!(moduleSymbol.flags & 111551 /* Value */)
77728                     : ts.forEachEntry(getExportsOfModule(moduleSymbol), isValue);
77729             }
77730             return symbolLinks.exportsSomeValue;
77731             function isValue(s) {
77732                 s = resolveSymbol(s);
77733                 return s && !!(s.flags & 111551 /* Value */);
77734             }
77735         }
77736         function isNameOfModuleOrEnumDeclaration(node) {
77737             return ts.isModuleOrEnumDeclaration(node.parent) && node === node.parent.name;
77738         }
77739         // When resolved as an expression identifier, if the given node references an exported entity, return the declaration
77740         // node of the exported entity's container. Otherwise, return undefined.
77741         function getReferencedExportContainer(nodeIn, prefixLocals) {
77742             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
77743             if (node) {
77744                 // When resolving the export container for the name of a module or enum
77745                 // declaration, we need to start resolution at the declaration's container.
77746                 // Otherwise, we could incorrectly resolve the export container as the
77747                 // declaration if it contains an exported member with the same name.
77748                 var symbol = getReferencedValueSymbol(node, /*startInDeclarationContainer*/ isNameOfModuleOrEnumDeclaration(node));
77749                 if (symbol) {
77750                     if (symbol.flags & 1048576 /* ExportValue */) {
77751                         // If we reference an exported entity within the same module declaration, then whether
77752                         // we prefix depends on the kind of entity. SymbolFlags.ExportHasLocal encompasses all the
77753                         // kinds that we do NOT prefix.
77754                         var exportSymbol = getMergedSymbol(symbol.exportSymbol);
77755                         if (!prefixLocals && exportSymbol.flags & 944 /* ExportHasLocal */ && !(exportSymbol.flags & 3 /* Variable */)) {
77756                             return undefined;
77757                         }
77758                         symbol = exportSymbol;
77759                     }
77760                     var parentSymbol_1 = getParentOfSymbol(symbol);
77761                     if (parentSymbol_1) {
77762                         if (parentSymbol_1.flags & 512 /* ValueModule */ && parentSymbol_1.valueDeclaration.kind === 297 /* SourceFile */) {
77763                             var symbolFile = parentSymbol_1.valueDeclaration;
77764                             var referenceFile = ts.getSourceFileOfNode(node);
77765                             // If `node` accesses an export and that export isn't in the same file, then symbol is a namespace export, so return undefined.
77766                             var symbolIsUmdExport = symbolFile !== referenceFile;
77767                             return symbolIsUmdExport ? undefined : symbolFile;
77768                         }
77769                         return ts.findAncestor(node.parent, function (n) { return ts.isModuleOrEnumDeclaration(n) && getSymbolOfNode(n) === parentSymbol_1; });
77770                     }
77771                 }
77772             }
77773         }
77774         // When resolved as an expression identifier, if the given node references an import, return the declaration of
77775         // that import. Otherwise, return undefined.
77776         function getReferencedImportDeclaration(nodeIn) {
77777             if (nodeIn.generatedImportReference) {
77778                 return nodeIn.generatedImportReference;
77779             }
77780             var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
77781             if (node) {
77782                 var symbol = getReferencedValueSymbol(node);
77783                 // We should only get the declaration of an alias if there isn't a local value
77784                 // declaration for the symbol
77785                 if (isNonLocalAlias(symbol, /*excludes*/ 111551 /* Value */) && !getTypeOnlyAliasDeclaration(symbol)) {
77786                     return getDeclarationOfAliasSymbol(symbol);
77787                 }
77788             }
77789             return undefined;
77790         }
77791         function isSymbolOfDestructuredElementOfCatchBinding(symbol) {
77792             return ts.isBindingElement(symbol.valueDeclaration)
77793                 && ts.walkUpBindingElementsAndPatterns(symbol.valueDeclaration).parent.kind === 287 /* CatchClause */;
77794         }
77795         function isSymbolOfDeclarationWithCollidingName(symbol) {
77796             if (symbol.flags & 418 /* BlockScoped */ && !ts.isSourceFile(symbol.valueDeclaration)) {
77797                 var links = getSymbolLinks(symbol);
77798                 if (links.isDeclarationWithCollidingName === undefined) {
77799                     var container = ts.getEnclosingBlockScopeContainer(symbol.valueDeclaration);
77800                     if (ts.isStatementWithLocals(container) || isSymbolOfDestructuredElementOfCatchBinding(symbol)) {
77801                         var nodeLinks_1 = getNodeLinks(symbol.valueDeclaration);
77802                         if (resolveName(container.parent, symbol.escapedName, 111551 /* Value */, /*nameNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ false)) {
77803                             // redeclaration - always should be renamed
77804                             links.isDeclarationWithCollidingName = true;
77805                         }
77806                         else if (nodeLinks_1.flags & 262144 /* CapturedBlockScopedBinding */) {
77807                             // binding is captured in the function
77808                             // should be renamed if:
77809                             // - binding is not top level - top level bindings never collide with anything
77810                             // AND
77811                             //   - binding is not declared in loop, should be renamed to avoid name reuse across siblings
77812                             //     let a, b
77813                             //     { let x = 1; a = () => x; }
77814                             //     { let x = 100; b = () => x; }
77815                             //     console.log(a()); // should print '1'
77816                             //     console.log(b()); // should print '100'
77817                             //     OR
77818                             //   - binding is declared inside loop but not in inside initializer of iteration statement or directly inside loop body
77819                             //     * variables from initializer are passed to rewritten loop body as parameters so they are not captured directly
77820                             //     * variables that are declared immediately in loop body will become top level variable after loop is rewritten and thus
77821                             //       they will not collide with anything
77822                             var isDeclaredInLoop = nodeLinks_1.flags & 524288 /* BlockScopedBindingInLoop */;
77823                             var inLoopInitializer = ts.isIterationStatement(container, /*lookInLabeledStatements*/ false);
77824                             var inLoopBodyBlock = container.kind === 230 /* Block */ && ts.isIterationStatement(container.parent, /*lookInLabeledStatements*/ false);
77825                             links.isDeclarationWithCollidingName = !ts.isBlockScopedContainerTopLevel(container) && (!isDeclaredInLoop || (!inLoopInitializer && !inLoopBodyBlock));
77826                         }
77827                         else {
77828                             links.isDeclarationWithCollidingName = false;
77829                         }
77830                     }
77831                 }
77832                 return links.isDeclarationWithCollidingName;
77833             }
77834             return false;
77835         }
77836         // When resolved as an expression identifier, if the given node references a nested block scoped entity with
77837         // a name that either hides an existing name or might hide it when compiled downlevel,
77838         // return the declaration of that entity. Otherwise, return undefined.
77839         function getReferencedDeclarationWithCollidingName(nodeIn) {
77840             if (!ts.isGeneratedIdentifier(nodeIn)) {
77841                 var node = ts.getParseTreeNode(nodeIn, ts.isIdentifier);
77842                 if (node) {
77843                     var symbol = getReferencedValueSymbol(node);
77844                     if (symbol && isSymbolOfDeclarationWithCollidingName(symbol)) {
77845                         return symbol.valueDeclaration;
77846                     }
77847                 }
77848             }
77849             return undefined;
77850         }
77851         // Return true if the given node is a declaration of a nested block scoped entity with a name that either hides an
77852         // existing name or might hide a name when compiled downlevel
77853         function isDeclarationWithCollidingName(nodeIn) {
77854             var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
77855             if (node) {
77856                 var symbol = getSymbolOfNode(node);
77857                 if (symbol) {
77858                     return isSymbolOfDeclarationWithCollidingName(symbol);
77859                 }
77860             }
77861             return false;
77862         }
77863         function isValueAliasDeclaration(node) {
77864             switch (node.kind) {
77865                 case 260 /* ImportEqualsDeclaration */:
77866                     return isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol);
77867                 case 262 /* ImportClause */:
77868                 case 263 /* NamespaceImport */:
77869                 case 265 /* ImportSpecifier */:
77870                 case 270 /* ExportSpecifier */:
77871                     var symbol = getSymbolOfNode(node) || unknownSymbol;
77872                     return isAliasResolvedToValue(symbol) && !getTypeOnlyAliasDeclaration(symbol);
77873                 case 267 /* ExportDeclaration */:
77874                     var exportClause = node.exportClause;
77875                     return !!exportClause && (ts.isNamespaceExport(exportClause) ||
77876                         ts.some(exportClause.elements, isValueAliasDeclaration));
77877                 case 266 /* ExportAssignment */:
77878                     return node.expression && node.expression.kind === 78 /* Identifier */ ?
77879                         isAliasResolvedToValue(getSymbolOfNode(node) || unknownSymbol) :
77880                         true;
77881             }
77882             return false;
77883         }
77884         function isTopLevelValueImportEqualsWithEntityName(nodeIn) {
77885             var node = ts.getParseTreeNode(nodeIn, ts.isImportEqualsDeclaration);
77886             if (node === undefined || node.parent.kind !== 297 /* SourceFile */ || !ts.isInternalModuleImportEqualsDeclaration(node)) {
77887                 // parent is not source file or it is not reference to internal module
77888                 return false;
77889             }
77890             var isValue = isAliasResolvedToValue(getSymbolOfNode(node));
77891             return isValue && node.moduleReference && !ts.nodeIsMissing(node.moduleReference);
77892         }
77893         function isAliasResolvedToValue(symbol) {
77894             var target = resolveAlias(symbol);
77895             if (target === unknownSymbol) {
77896                 return true;
77897             }
77898             // const enums and modules that contain only const enums are not considered values from the emit perspective
77899             // unless 'preserveConstEnums' option is set to true
77900             return !!(target.flags & 111551 /* Value */) &&
77901                 (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target));
77902         }
77903         function isConstEnumOrConstEnumOnlyModule(s) {
77904             return isConstEnumSymbol(s) || !!s.constEnumOnlyModule;
77905         }
77906         function isReferencedAliasDeclaration(node, checkChildren) {
77907             if (isAliasSymbolDeclaration(node)) {
77908                 var symbol = getSymbolOfNode(node);
77909                 if (symbol && getSymbolLinks(symbol).referenced) {
77910                     return true;
77911                 }
77912                 var target = getSymbolLinks(symbol).target; // TODO: GH#18217
77913                 if (target && ts.getEffectiveModifierFlags(node) & 1 /* Export */ &&
77914                     target.flags & 111551 /* Value */ &&
77915                     (compilerOptions.preserveConstEnums || !isConstEnumOrConstEnumOnlyModule(target))) {
77916                     // An `export import ... =` of a value symbol is always considered referenced
77917                     return true;
77918                 }
77919             }
77920             if (checkChildren) {
77921                 return !!ts.forEachChild(node, function (node) { return isReferencedAliasDeclaration(node, checkChildren); });
77922             }
77923             return false;
77924         }
77925         function isImplementationOfOverload(node) {
77926             if (ts.nodeIsPresent(node.body)) {
77927                 if (ts.isGetAccessor(node) || ts.isSetAccessor(node))
77928                     return false; // Get or set accessors can never be overload implementations, but can have up to 2 signatures
77929                 var symbol = getSymbolOfNode(node);
77930                 var signaturesOfSymbol = getSignaturesOfSymbol(symbol);
77931                 // If this function body corresponds to function with multiple signature, it is implementation of overload
77932                 // e.g.: function foo(a: string): string;
77933                 //       function foo(a: number): number;
77934                 //       function foo(a: any) { // This is implementation of the overloads
77935                 //           return a;
77936                 //       }
77937                 return signaturesOfSymbol.length > 1 ||
77938                     // If there is single signature for the symbol, it is overload if that signature isn't coming from the node
77939                     // e.g.: function foo(a: string): string;
77940                     //       function foo(a: any) { // This is implementation of the overloads
77941                     //           return a;
77942                     //       }
77943                     (signaturesOfSymbol.length === 1 && signaturesOfSymbol[0].declaration !== node);
77944             }
77945             return false;
77946         }
77947         function isRequiredInitializedParameter(parameter) {
77948             return !!strictNullChecks &&
77949                 !isOptionalParameter(parameter) &&
77950                 !ts.isJSDocParameterTag(parameter) &&
77951                 !!parameter.initializer &&
77952                 !ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */);
77953         }
77954         function isOptionalUninitializedParameterProperty(parameter) {
77955             return strictNullChecks &&
77956                 isOptionalParameter(parameter) &&
77957                 !parameter.initializer &&
77958                 ts.hasSyntacticModifier(parameter, 92 /* ParameterPropertyModifier */);
77959         }
77960         function isOptionalUninitializedParameter(parameter) {
77961             return !!strictNullChecks &&
77962                 isOptionalParameter(parameter) &&
77963                 !parameter.initializer;
77964         }
77965         function isExpandoFunctionDeclaration(node) {
77966             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
77967             if (!declaration) {
77968                 return false;
77969             }
77970             var symbol = getSymbolOfNode(declaration);
77971             if (!symbol || !(symbol.flags & 16 /* Function */)) {
77972                 return false;
77973             }
77974             return !!ts.forEachEntry(getExportsOfSymbol(symbol), function (p) { return p.flags & 111551 /* Value */ && p.valueDeclaration && ts.isPropertyAccessExpression(p.valueDeclaration); });
77975         }
77976         function getPropertiesOfContainerFunction(node) {
77977             var declaration = ts.getParseTreeNode(node, ts.isFunctionDeclaration);
77978             if (!declaration) {
77979                 return ts.emptyArray;
77980             }
77981             var symbol = getSymbolOfNode(declaration);
77982             return symbol && getPropertiesOfType(getTypeOfSymbol(symbol)) || ts.emptyArray;
77983         }
77984         function getNodeCheckFlags(node) {
77985             return getNodeLinks(node).flags || 0;
77986         }
77987         function getEnumMemberValue(node) {
77988             computeEnumMemberValues(node.parent);
77989             return getNodeLinks(node).enumMemberValue;
77990         }
77991         function canHaveConstantValue(node) {
77992             switch (node.kind) {
77993                 case 291 /* EnumMember */:
77994                 case 201 /* PropertyAccessExpression */:
77995                 case 202 /* ElementAccessExpression */:
77996                     return true;
77997             }
77998             return false;
77999         }
78000         function getConstantValue(node) {
78001             if (node.kind === 291 /* EnumMember */) {
78002                 return getEnumMemberValue(node);
78003             }
78004             var symbol = getNodeLinks(node).resolvedSymbol;
78005             if (symbol && (symbol.flags & 8 /* EnumMember */)) {
78006                 // inline property\index accesses only for const enums
78007                 var member = symbol.valueDeclaration;
78008                 if (ts.isEnumConst(member.parent)) {
78009                     return getEnumMemberValue(member);
78010                 }
78011             }
78012             return undefined;
78013         }
78014         function isFunctionType(type) {
78015             return !!(type.flags & 524288 /* Object */) && getSignaturesOfType(type, 0 /* Call */).length > 0;
78016         }
78017         function getTypeReferenceSerializationKind(typeNameIn, location) {
78018             var _a;
78019             // ensure both `typeName` and `location` are parse tree nodes.
78020             var typeName = ts.getParseTreeNode(typeNameIn, ts.isEntityName);
78021             if (!typeName)
78022                 return ts.TypeReferenceSerializationKind.Unknown;
78023             if (location) {
78024                 location = ts.getParseTreeNode(location);
78025                 if (!location)
78026                     return ts.TypeReferenceSerializationKind.Unknown;
78027             }
78028             // Resolve the symbol as a value to ensure the type can be reached at runtime during emit.
78029             var valueSymbol = resolveEntityName(typeName, 111551 /* Value */, /*ignoreErrors*/ true, /*dontResolveAlias*/ true, location);
78030             var isTypeOnly = ((_a = valueSymbol === null || valueSymbol === void 0 ? void 0 : valueSymbol.declarations) === null || _a === void 0 ? void 0 : _a.every(ts.isTypeOnlyImportOrExportDeclaration)) || false;
78031             var resolvedSymbol = valueSymbol && valueSymbol.flags & 2097152 /* Alias */ ? resolveAlias(valueSymbol) : valueSymbol;
78032             // Resolve the symbol as a type so that we can provide a more useful hint for the type serializer.
78033             var typeSymbol = resolveEntityName(typeName, 788968 /* Type */, /*ignoreErrors*/ true, /*dontResolveAlias*/ false, location);
78034             if (resolvedSymbol && resolvedSymbol === typeSymbol) {
78035                 var globalPromiseSymbol = getGlobalPromiseConstructorSymbol(/*reportErrors*/ false);
78036                 if (globalPromiseSymbol && resolvedSymbol === globalPromiseSymbol) {
78037                     return ts.TypeReferenceSerializationKind.Promise;
78038                 }
78039                 var constructorType = getTypeOfSymbol(resolvedSymbol);
78040                 if (constructorType && isConstructorType(constructorType)) {
78041                     return isTypeOnly ? ts.TypeReferenceSerializationKind.TypeWithCallSignature : ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue;
78042                 }
78043             }
78044             // We might not be able to resolve type symbol so use unknown type in that case (eg error case)
78045             if (!typeSymbol) {
78046                 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
78047             }
78048             var type = getDeclaredTypeOfSymbol(typeSymbol);
78049             if (type === errorType) {
78050                 return isTypeOnly ? ts.TypeReferenceSerializationKind.ObjectType : ts.TypeReferenceSerializationKind.Unknown;
78051             }
78052             else if (type.flags & 3 /* AnyOrUnknown */) {
78053                 return ts.TypeReferenceSerializationKind.ObjectType;
78054             }
78055             else if (isTypeAssignableToKind(type, 16384 /* Void */ | 98304 /* Nullable */ | 131072 /* Never */)) {
78056                 return ts.TypeReferenceSerializationKind.VoidNullableOrNeverType;
78057             }
78058             else if (isTypeAssignableToKind(type, 528 /* BooleanLike */)) {
78059                 return ts.TypeReferenceSerializationKind.BooleanType;
78060             }
78061             else if (isTypeAssignableToKind(type, 296 /* NumberLike */)) {
78062                 return ts.TypeReferenceSerializationKind.NumberLikeType;
78063             }
78064             else if (isTypeAssignableToKind(type, 2112 /* BigIntLike */)) {
78065                 return ts.TypeReferenceSerializationKind.BigIntLikeType;
78066             }
78067             else if (isTypeAssignableToKind(type, 402653316 /* StringLike */)) {
78068                 return ts.TypeReferenceSerializationKind.StringLikeType;
78069             }
78070             else if (isTupleType(type)) {
78071                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
78072             }
78073             else if (isTypeAssignableToKind(type, 12288 /* ESSymbolLike */)) {
78074                 return ts.TypeReferenceSerializationKind.ESSymbolType;
78075             }
78076             else if (isFunctionType(type)) {
78077                 return ts.TypeReferenceSerializationKind.TypeWithCallSignature;
78078             }
78079             else if (isArrayType(type)) {
78080                 return ts.TypeReferenceSerializationKind.ArrayLikeType;
78081             }
78082             else {
78083                 return ts.TypeReferenceSerializationKind.ObjectType;
78084             }
78085         }
78086         function createTypeOfDeclaration(declarationIn, enclosingDeclaration, flags, tracker, addUndefined) {
78087             var declaration = ts.getParseTreeNode(declarationIn, ts.isVariableLikeOrAccessor);
78088             if (!declaration) {
78089                 return ts.factory.createToken(128 /* AnyKeyword */);
78090             }
78091             // Get type of the symbol if this is the valid symbol otherwise get type at location
78092             var symbol = getSymbolOfNode(declaration);
78093             var type = symbol && !(symbol.flags & (2048 /* TypeLiteral */ | 131072 /* Signature */))
78094                 ? getWidenedLiteralType(getTypeOfSymbol(symbol))
78095                 : errorType;
78096             if (type.flags & 8192 /* UniqueESSymbol */ &&
78097                 type.symbol === symbol) {
78098                 flags |= 1048576 /* AllowUniqueESSymbolType */;
78099             }
78100             if (addUndefined) {
78101                 type = getOptionalType(type);
78102             }
78103             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
78104         }
78105         function createReturnTypeOfSignatureDeclaration(signatureDeclarationIn, enclosingDeclaration, flags, tracker) {
78106             var signatureDeclaration = ts.getParseTreeNode(signatureDeclarationIn, ts.isFunctionLike);
78107             if (!signatureDeclaration) {
78108                 return ts.factory.createToken(128 /* AnyKeyword */);
78109             }
78110             var signature = getSignatureFromDeclaration(signatureDeclaration);
78111             return nodeBuilder.typeToTypeNode(getReturnTypeOfSignature(signature), enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
78112         }
78113         function createTypeOfExpression(exprIn, enclosingDeclaration, flags, tracker) {
78114             var expr = ts.getParseTreeNode(exprIn, ts.isExpression);
78115             if (!expr) {
78116                 return ts.factory.createToken(128 /* AnyKeyword */);
78117             }
78118             var type = getWidenedType(getRegularTypeOfExpression(expr));
78119             return nodeBuilder.typeToTypeNode(type, enclosingDeclaration, flags | 1024 /* MultilineObjectLiterals */, tracker);
78120         }
78121         function hasGlobalName(name) {
78122             return globals.has(ts.escapeLeadingUnderscores(name));
78123         }
78124         function getReferencedValueSymbol(reference, startInDeclarationContainer) {
78125             var resolvedSymbol = getNodeLinks(reference).resolvedSymbol;
78126             if (resolvedSymbol) {
78127                 return resolvedSymbol;
78128             }
78129             var location = reference;
78130             if (startInDeclarationContainer) {
78131                 // When resolving the name of a declaration as a value, we need to start resolution
78132                 // at a point outside of the declaration.
78133                 var parent = reference.parent;
78134                 if (ts.isDeclaration(parent) && reference === parent.name) {
78135                     location = getDeclarationContainer(parent);
78136                 }
78137             }
78138             return resolveName(location, reference.escapedText, 111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */, /*nodeNotFoundMessage*/ undefined, /*nameArg*/ undefined, /*isUse*/ true);
78139         }
78140         function getReferencedValueDeclaration(referenceIn) {
78141             if (!ts.isGeneratedIdentifier(referenceIn)) {
78142                 var reference = ts.getParseTreeNode(referenceIn, ts.isIdentifier);
78143                 if (reference) {
78144                     var symbol = getReferencedValueSymbol(reference);
78145                     if (symbol) {
78146                         return getExportSymbolOfValueSymbolIfExported(symbol).valueDeclaration;
78147                     }
78148                 }
78149             }
78150             return undefined;
78151         }
78152         function isLiteralConstDeclaration(node) {
78153             if (ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node)) {
78154                 return isFreshLiteralType(getTypeOfSymbol(getSymbolOfNode(node)));
78155             }
78156             return false;
78157         }
78158         function literalTypeToNode(type, enclosing, tracker) {
78159             var enumResult = type.flags & 1024 /* EnumLiteral */ ? nodeBuilder.symbolToExpression(type.symbol, 111551 /* Value */, enclosing, /*flags*/ undefined, tracker)
78160                 : type === trueType ? ts.factory.createTrue() : type === falseType && ts.factory.createFalse();
78161             if (enumResult)
78162                 return enumResult;
78163             var literalValue = type.value;
78164             return typeof literalValue === "object" ? ts.factory.createBigIntLiteral(literalValue) :
78165                 typeof literalValue === "number" ? ts.factory.createNumericLiteral(literalValue) :
78166                     ts.factory.createStringLiteral(literalValue);
78167         }
78168         function createLiteralConstValue(node, tracker) {
78169             var type = getTypeOfSymbol(getSymbolOfNode(node));
78170             return literalTypeToNode(type, node, tracker);
78171         }
78172         function getJsxFactoryEntity(location) {
78173             return location ? (getJsxNamespace(location), (ts.getSourceFileOfNode(location).localJsxFactory || _jsxFactoryEntity)) : _jsxFactoryEntity;
78174         }
78175         function getJsxFragmentFactoryEntity(location) {
78176             if (location) {
78177                 var file = ts.getSourceFileOfNode(location);
78178                 if (file) {
78179                     if (file.localJsxFragmentFactory) {
78180                         return file.localJsxFragmentFactory;
78181                     }
78182                     var jsxFragPragmas = file.pragmas.get("jsxfrag");
78183                     var jsxFragPragma = ts.isArray(jsxFragPragmas) ? jsxFragPragmas[0] : jsxFragPragmas;
78184                     if (jsxFragPragma) {
78185                         file.localJsxFragmentFactory = ts.parseIsolatedEntityName(jsxFragPragma.arguments.factory, languageVersion);
78186                         return file.localJsxFragmentFactory;
78187                     }
78188                 }
78189             }
78190             if (compilerOptions.jsxFragmentFactory) {
78191                 return ts.parseIsolatedEntityName(compilerOptions.jsxFragmentFactory, languageVersion);
78192             }
78193         }
78194         function createResolver() {
78195             // this variable and functions that use it are deliberately moved here from the outer scope
78196             // to avoid scope pollution
78197             var resolvedTypeReferenceDirectives = host.getResolvedTypeReferenceDirectives();
78198             var fileToDirective;
78199             if (resolvedTypeReferenceDirectives) {
78200                 // populate reverse mapping: file path -> type reference directive that was resolved to this file
78201                 fileToDirective = new ts.Map();
78202                 resolvedTypeReferenceDirectives.forEach(function (resolvedDirective, key) {
78203                     if (!resolvedDirective || !resolvedDirective.resolvedFileName) {
78204                         return;
78205                     }
78206                     var file = host.getSourceFile(resolvedDirective.resolvedFileName);
78207                     if (file) {
78208                         // Add the transitive closure of path references loaded by this file (as long as they are not)
78209                         // part of an existing type reference.
78210                         addReferencedFilesToTypeDirective(file, key);
78211                     }
78212                 });
78213             }
78214             return {
78215                 getReferencedExportContainer: getReferencedExportContainer,
78216                 getReferencedImportDeclaration: getReferencedImportDeclaration,
78217                 getReferencedDeclarationWithCollidingName: getReferencedDeclarationWithCollidingName,
78218                 isDeclarationWithCollidingName: isDeclarationWithCollidingName,
78219                 isValueAliasDeclaration: function (nodeIn) {
78220                     var node = ts.getParseTreeNode(nodeIn);
78221                     // Synthesized nodes are always treated like values.
78222                     return node ? isValueAliasDeclaration(node) : true;
78223                 },
78224                 hasGlobalName: hasGlobalName,
78225                 isReferencedAliasDeclaration: function (nodeIn, checkChildren) {
78226                     var node = ts.getParseTreeNode(nodeIn);
78227                     // Synthesized nodes are always treated as referenced.
78228                     return node ? isReferencedAliasDeclaration(node, checkChildren) : true;
78229                 },
78230                 getNodeCheckFlags: function (nodeIn) {
78231                     var node = ts.getParseTreeNode(nodeIn);
78232                     return node ? getNodeCheckFlags(node) : 0;
78233                 },
78234                 isTopLevelValueImportEqualsWithEntityName: isTopLevelValueImportEqualsWithEntityName,
78235                 isDeclarationVisible: isDeclarationVisible,
78236                 isImplementationOfOverload: isImplementationOfOverload,
78237                 isRequiredInitializedParameter: isRequiredInitializedParameter,
78238                 isOptionalUninitializedParameterProperty: isOptionalUninitializedParameterProperty,
78239                 isExpandoFunctionDeclaration: isExpandoFunctionDeclaration,
78240                 getPropertiesOfContainerFunction: getPropertiesOfContainerFunction,
78241                 createTypeOfDeclaration: createTypeOfDeclaration,
78242                 createReturnTypeOfSignatureDeclaration: createReturnTypeOfSignatureDeclaration,
78243                 createTypeOfExpression: createTypeOfExpression,
78244                 createLiteralConstValue: createLiteralConstValue,
78245                 isSymbolAccessible: isSymbolAccessible,
78246                 isEntityNameVisible: isEntityNameVisible,
78247                 getConstantValue: function (nodeIn) {
78248                     var node = ts.getParseTreeNode(nodeIn, canHaveConstantValue);
78249                     return node ? getConstantValue(node) : undefined;
78250                 },
78251                 collectLinkedAliases: collectLinkedAliases,
78252                 getReferencedValueDeclaration: getReferencedValueDeclaration,
78253                 getTypeReferenceSerializationKind: getTypeReferenceSerializationKind,
78254                 isOptionalParameter: isOptionalParameter,
78255                 moduleExportsSomeValue: moduleExportsSomeValue,
78256                 isArgumentsLocalBinding: isArgumentsLocalBinding,
78257                 getExternalModuleFileFromDeclaration: getExternalModuleFileFromDeclaration,
78258                 getTypeReferenceDirectivesForEntityName: getTypeReferenceDirectivesForEntityName,
78259                 getTypeReferenceDirectivesForSymbol: getTypeReferenceDirectivesForSymbol,
78260                 isLiteralConstDeclaration: isLiteralConstDeclaration,
78261                 isLateBound: function (nodeIn) {
78262                     var node = ts.getParseTreeNode(nodeIn, ts.isDeclaration);
78263                     var symbol = node && getSymbolOfNode(node);
78264                     return !!(symbol && ts.getCheckFlags(symbol) & 4096 /* Late */);
78265                 },
78266                 getJsxFactoryEntity: getJsxFactoryEntity,
78267                 getJsxFragmentFactoryEntity: getJsxFragmentFactoryEntity,
78268                 getAllAccessorDeclarations: function (accessor) {
78269                     accessor = ts.getParseTreeNode(accessor, ts.isGetOrSetAccessorDeclaration); // TODO: GH#18217
78270                     var otherKind = accessor.kind === 168 /* SetAccessor */ ? 167 /* GetAccessor */ : 168 /* SetAccessor */;
78271                     var otherAccessor = ts.getDeclarationOfKind(getSymbolOfNode(accessor), otherKind);
78272                     var firstAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? otherAccessor : accessor;
78273                     var secondAccessor = otherAccessor && (otherAccessor.pos < accessor.pos) ? accessor : otherAccessor;
78274                     var setAccessor = accessor.kind === 168 /* SetAccessor */ ? accessor : otherAccessor;
78275                     var getAccessor = accessor.kind === 167 /* GetAccessor */ ? accessor : otherAccessor;
78276                     return {
78277                         firstAccessor: firstAccessor,
78278                         secondAccessor: secondAccessor,
78279                         setAccessor: setAccessor,
78280                         getAccessor: getAccessor
78281                     };
78282                 },
78283                 getSymbolOfExternalModuleSpecifier: function (moduleName) { return resolveExternalModuleNameWorker(moduleName, moduleName, /*moduleNotFoundError*/ undefined); },
78284                 isBindingCapturedByNode: function (node, decl) {
78285                     var parseNode = ts.getParseTreeNode(node);
78286                     var parseDecl = ts.getParseTreeNode(decl);
78287                     return !!parseNode && !!parseDecl && (ts.isVariableDeclaration(parseDecl) || ts.isBindingElement(parseDecl)) && isBindingCapturedByNode(parseNode, parseDecl);
78288                 },
78289                 getDeclarationStatementsForSourceFile: function (node, flags, tracker, bundled) {
78290                     var n = ts.getParseTreeNode(node);
78291                     ts.Debug.assert(n && n.kind === 297 /* SourceFile */, "Non-sourcefile node passed into getDeclarationsForSourceFile");
78292                     var sym = getSymbolOfNode(node);
78293                     if (!sym) {
78294                         return !node.locals ? [] : nodeBuilder.symbolTableToDeclarationStatements(node.locals, node, flags, tracker, bundled);
78295                     }
78296                     return !sym.exports ? [] : nodeBuilder.symbolTableToDeclarationStatements(sym.exports, node, flags, tracker, bundled);
78297                 },
78298                 isImportRequiredByAugmentation: isImportRequiredByAugmentation,
78299             };
78300             function isImportRequiredByAugmentation(node) {
78301                 var file = ts.getSourceFileOfNode(node);
78302                 if (!file.symbol)
78303                     return false;
78304                 var importTarget = getExternalModuleFileFromDeclaration(node);
78305                 if (!importTarget)
78306                     return false;
78307                 if (importTarget === file)
78308                     return false;
78309                 var exports = getExportsOfModule(file.symbol);
78310                 for (var _i = 0, _a = ts.arrayFrom(exports.values()); _i < _a.length; _i++) {
78311                     var s = _a[_i];
78312                     if (s.mergeId) {
78313                         var merged = getMergedSymbol(s);
78314                         for (var _b = 0, _c = merged.declarations; _b < _c.length; _b++) {
78315                             var d = _c[_b];
78316                             var declFile = ts.getSourceFileOfNode(d);
78317                             if (declFile === importTarget) {
78318                                 return true;
78319                             }
78320                         }
78321                     }
78322                 }
78323                 return false;
78324             }
78325             function isInHeritageClause(node) {
78326                 return node.parent && node.parent.kind === 223 /* ExpressionWithTypeArguments */ && node.parent.parent && node.parent.parent.kind === 286 /* HeritageClause */;
78327             }
78328             // defined here to avoid outer scope pollution
78329             function getTypeReferenceDirectivesForEntityName(node) {
78330                 // program does not have any files with type reference directives - bail out
78331                 if (!fileToDirective) {
78332                     return undefined;
78333                 }
78334                 // property access can only be used as values, or types when within an expression with type arguments inside a heritage clause
78335                 // qualified names can only be used as types\namespaces
78336                 // identifiers are treated as values only if they appear in type queries
78337                 var meaning = 788968 /* Type */ | 1920 /* Namespace */;
78338                 if ((node.kind === 78 /* Identifier */ && isInTypeQuery(node)) || (node.kind === 201 /* PropertyAccessExpression */ && !isInHeritageClause(node))) {
78339                     meaning = 111551 /* Value */ | 1048576 /* ExportValue */;
78340                 }
78341                 var symbol = resolveEntityName(node, meaning, /*ignoreErrors*/ true);
78342                 return symbol && symbol !== unknownSymbol ? getTypeReferenceDirectivesForSymbol(symbol, meaning) : undefined;
78343             }
78344             // defined here to avoid outer scope pollution
78345             function getTypeReferenceDirectivesForSymbol(symbol, meaning) {
78346                 // program does not have any files with type reference directives - bail out
78347                 if (!fileToDirective) {
78348                     return undefined;
78349                 }
78350                 if (!isSymbolFromTypeDeclarationFile(symbol)) {
78351                     return undefined;
78352                 }
78353                 // check what declarations in the symbol can contribute to the target meaning
78354                 var typeReferenceDirectives;
78355                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
78356                     var decl = _a[_i];
78357                     // check meaning of the local symbol to see if declaration needs to be analyzed further
78358                     if (decl.symbol && decl.symbol.flags & meaning) {
78359                         var file = ts.getSourceFileOfNode(decl);
78360                         var typeReferenceDirective = fileToDirective.get(file.path);
78361                         if (typeReferenceDirective) {
78362                             (typeReferenceDirectives || (typeReferenceDirectives = [])).push(typeReferenceDirective);
78363                         }
78364                         else {
78365                             // found at least one entry that does not originate from type reference directive
78366                             return undefined;
78367                         }
78368                     }
78369                 }
78370                 return typeReferenceDirectives;
78371             }
78372             function isSymbolFromTypeDeclarationFile(symbol) {
78373                 // bail out if symbol does not have associated declarations (i.e. this is transient symbol created for property in binding pattern)
78374                 if (!symbol.declarations) {
78375                     return false;
78376                 }
78377                 // walk the parent chain for symbols to make sure that top level parent symbol is in the global scope
78378                 // external modules cannot define or contribute to type declaration files
78379                 var current = symbol;
78380                 while (true) {
78381                     var parent = getParentOfSymbol(current);
78382                     if (parent) {
78383                         current = parent;
78384                     }
78385                     else {
78386                         break;
78387                     }
78388                 }
78389                 if (current.valueDeclaration && current.valueDeclaration.kind === 297 /* SourceFile */ && current.flags & 512 /* ValueModule */) {
78390                     return false;
78391                 }
78392                 // check that at least one declaration of top level symbol originates from type declaration file
78393                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
78394                     var decl = _a[_i];
78395                     var file = ts.getSourceFileOfNode(decl);
78396                     if (fileToDirective.has(file.path)) {
78397                         return true;
78398                     }
78399                 }
78400                 return false;
78401             }
78402             function addReferencedFilesToTypeDirective(file, key) {
78403                 if (fileToDirective.has(file.path))
78404                     return;
78405                 fileToDirective.set(file.path, key);
78406                 for (var _i = 0, _a = file.referencedFiles; _i < _a.length; _i++) {
78407                     var fileName = _a[_i].fileName;
78408                     var resolvedFile = ts.resolveTripleslashReference(fileName, file.fileName);
78409                     var referencedFile = host.getSourceFile(resolvedFile);
78410                     if (referencedFile) {
78411                         addReferencedFilesToTypeDirective(referencedFile, key);
78412                     }
78413                 }
78414             }
78415         }
78416         function getExternalModuleFileFromDeclaration(declaration) {
78417             var specifier = declaration.kind === 256 /* ModuleDeclaration */ ? ts.tryCast(declaration.name, ts.isStringLiteral) : ts.getExternalModuleName(declaration);
78418             var moduleSymbol = resolveExternalModuleNameWorker(specifier, specifier, /*moduleNotFoundError*/ undefined); // TODO: GH#18217
78419             if (!moduleSymbol) {
78420                 return undefined;
78421             }
78422             return ts.getDeclarationOfKind(moduleSymbol, 297 /* SourceFile */);
78423         }
78424         function initializeTypeChecker() {
78425             // Bind all source files and propagate errors
78426             for (var _i = 0, _a = host.getSourceFiles(); _i < _a.length; _i++) {
78427                 var file = _a[_i];
78428                 ts.bindSourceFile(file, compilerOptions);
78429             }
78430             amalgamatedDuplicates = new ts.Map();
78431             // Initialize global symbol table
78432             var augmentations;
78433             for (var _b = 0, _c = host.getSourceFiles(); _b < _c.length; _b++) {
78434                 var file = _c[_b];
78435                 if (file.redirectInfo) {
78436                     continue;
78437                 }
78438                 if (!ts.isExternalOrCommonJsModule(file)) {
78439                     // It is an error for a non-external-module (i.e. script) to declare its own `globalThis`.
78440                     // We can't use `builtinGlobals` for this due to synthetic expando-namespace generation in JS files.
78441                     var fileGlobalThisSymbol = file.locals.get("globalThis");
78442                     if (fileGlobalThisSymbol) {
78443                         for (var _d = 0, _e = fileGlobalThisSymbol.declarations; _d < _e.length; _d++) {
78444                             var declaration = _e[_d];
78445                             diagnostics.add(ts.createDiagnosticForNode(declaration, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0, "globalThis"));
78446                         }
78447                     }
78448                     mergeSymbolTable(globals, file.locals);
78449                 }
78450                 if (file.jsGlobalAugmentations) {
78451                     mergeSymbolTable(globals, file.jsGlobalAugmentations);
78452                 }
78453                 if (file.patternAmbientModules && file.patternAmbientModules.length) {
78454                     patternAmbientModules = ts.concatenate(patternAmbientModules, file.patternAmbientModules);
78455                 }
78456                 if (file.moduleAugmentations.length) {
78457                     (augmentations || (augmentations = [])).push(file.moduleAugmentations);
78458                 }
78459                 if (file.symbol && file.symbol.globalExports) {
78460                     // Merge in UMD exports with first-in-wins semantics (see #9771)
78461                     var source = file.symbol.globalExports;
78462                     source.forEach(function (sourceSymbol, id) {
78463                         if (!globals.has(id)) {
78464                             globals.set(id, sourceSymbol);
78465                         }
78466                     });
78467                 }
78468             }
78469             // We do global augmentations separately from module augmentations (and before creating global types) because they
78470             //  1. Affect global types. We won't have the correct global types until global augmentations are merged. Also,
78471             //  2. Module augmentation instantiation requires creating the type of a module, which, in turn, can require
78472             //       checking for an export or property on the module (if export=) which, in turn, can fall back to the
78473             //       apparent type of the module - either globalObjectType or globalFunctionType - which wouldn't exist if we
78474             //       did module augmentations prior to finalizing the global types.
78475             if (augmentations) {
78476                 // merge _global_ module augmentations.
78477                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
78478                 for (var _f = 0, augmentations_1 = augmentations; _f < augmentations_1.length; _f++) {
78479                     var list = augmentations_1[_f];
78480                     for (var _g = 0, list_1 = list; _g < list_1.length; _g++) {
78481                         var augmentation = list_1[_g];
78482                         if (!ts.isGlobalScopeAugmentation(augmentation.parent))
78483                             continue;
78484                         mergeModuleAugmentation(augmentation);
78485                     }
78486                 }
78487             }
78488             // Setup global builtins
78489             addToSymbolTable(globals, builtinGlobals, ts.Diagnostics.Declaration_name_conflicts_with_built_in_global_identifier_0);
78490             getSymbolLinks(undefinedSymbol).type = undefinedWideningType;
78491             getSymbolLinks(argumentsSymbol).type = getGlobalType("IArguments", /*arity*/ 0, /*reportErrors*/ true);
78492             getSymbolLinks(unknownSymbol).type = errorType;
78493             getSymbolLinks(globalThisSymbol).type = createObjectType(16 /* Anonymous */, globalThisSymbol);
78494             // Initialize special types
78495             globalArrayType = getGlobalType("Array", /*arity*/ 1, /*reportErrors*/ true);
78496             globalObjectType = getGlobalType("Object", /*arity*/ 0, /*reportErrors*/ true);
78497             globalFunctionType = getGlobalType("Function", /*arity*/ 0, /*reportErrors*/ true);
78498             globalCallableFunctionType = strictBindCallApply && getGlobalType("CallableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
78499             globalNewableFunctionType = strictBindCallApply && getGlobalType("NewableFunction", /*arity*/ 0, /*reportErrors*/ true) || globalFunctionType;
78500             globalStringType = getGlobalType("String", /*arity*/ 0, /*reportErrors*/ true);
78501             globalNumberType = getGlobalType("Number", /*arity*/ 0, /*reportErrors*/ true);
78502             globalBooleanType = getGlobalType("Boolean", /*arity*/ 0, /*reportErrors*/ true);
78503             globalRegExpType = getGlobalType("RegExp", /*arity*/ 0, /*reportErrors*/ true);
78504             anyArrayType = createArrayType(anyType);
78505             autoArrayType = createArrayType(autoType);
78506             if (autoArrayType === emptyObjectType) {
78507                 // autoArrayType is used as a marker, so even if global Array type is not defined, it needs to be a unique type
78508                 autoArrayType = createAnonymousType(undefined, emptySymbols, ts.emptyArray, ts.emptyArray, undefined, undefined);
78509             }
78510             globalReadonlyArrayType = getGlobalTypeOrUndefined("ReadonlyArray", /*arity*/ 1) || globalArrayType;
78511             anyReadonlyArrayType = globalReadonlyArrayType ? createTypeFromGenericGlobalType(globalReadonlyArrayType, [anyType]) : anyArrayType;
78512             globalThisType = getGlobalTypeOrUndefined("ThisType", /*arity*/ 1);
78513             if (augmentations) {
78514                 // merge _nonglobal_ module augmentations.
78515                 // this needs to be done after global symbol table is initialized to make sure that all ambient modules are indexed
78516                 for (var _h = 0, augmentations_2 = augmentations; _h < augmentations_2.length; _h++) {
78517                     var list = augmentations_2[_h];
78518                     for (var _j = 0, list_2 = list; _j < list_2.length; _j++) {
78519                         var augmentation = list_2[_j];
78520                         if (ts.isGlobalScopeAugmentation(augmentation.parent))
78521                             continue;
78522                         mergeModuleAugmentation(augmentation);
78523                     }
78524                 }
78525             }
78526             amalgamatedDuplicates.forEach(function (_a) {
78527                 var firstFile = _a.firstFile, secondFile = _a.secondFile, conflictingSymbols = _a.conflictingSymbols;
78528                 // If not many things conflict, issue individual errors
78529                 if (conflictingSymbols.size < 8) {
78530                     conflictingSymbols.forEach(function (_a, symbolName) {
78531                         var isBlockScoped = _a.isBlockScoped, firstFileLocations = _a.firstFileLocations, secondFileLocations = _a.secondFileLocations;
78532                         var message = isBlockScoped ? ts.Diagnostics.Cannot_redeclare_block_scoped_variable_0 : ts.Diagnostics.Duplicate_identifier_0;
78533                         for (var _i = 0, firstFileLocations_1 = firstFileLocations; _i < firstFileLocations_1.length; _i++) {
78534                             var node = firstFileLocations_1[_i];
78535                             addDuplicateDeclarationError(node, message, symbolName, secondFileLocations);
78536                         }
78537                         for (var _b = 0, secondFileLocations_1 = secondFileLocations; _b < secondFileLocations_1.length; _b++) {
78538                             var node = secondFileLocations_1[_b];
78539                             addDuplicateDeclarationError(node, message, symbolName, firstFileLocations);
78540                         }
78541                     });
78542                 }
78543                 else {
78544                     // Otherwise issue top-level error since the files appear very identical in terms of what they contain
78545                     var list = ts.arrayFrom(conflictingSymbols.keys()).join(", ");
78546                     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)));
78547                     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)));
78548                 }
78549             });
78550             amalgamatedDuplicates = undefined;
78551         }
78552         function checkExternalEmitHelpers(location, helpers) {
78553             if ((requestedExternalEmitHelpers & helpers) !== helpers && compilerOptions.importHelpers) {
78554                 var sourceFile = ts.getSourceFileOfNode(location);
78555                 if (ts.isEffectiveExternalModule(sourceFile, compilerOptions) && !(location.flags & 8388608 /* Ambient */)) {
78556                     var helpersModule = resolveHelpersModule(sourceFile, location);
78557                     if (helpersModule !== unknownSymbol) {
78558                         var uncheckedHelpers = helpers & ~requestedExternalEmitHelpers;
78559                         for (var helper = 1 /* FirstEmitHelper */; helper <= 4194304 /* LastEmitHelper */; helper <<= 1) {
78560                             if (uncheckedHelpers & helper) {
78561                                 var name = getHelperName(helper);
78562                                 var symbol = getSymbol(helpersModule.exports, ts.escapeLeadingUnderscores(name), 111551 /* Value */);
78563                                 if (!symbol) {
78564                                     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);
78565                                 }
78566                             }
78567                         }
78568                     }
78569                     requestedExternalEmitHelpers |= helpers;
78570                 }
78571             }
78572         }
78573         function getHelperName(helper) {
78574             switch (helper) {
78575                 case 1 /* Extends */: return "__extends";
78576                 case 2 /* Assign */: return "__assign";
78577                 case 4 /* Rest */: return "__rest";
78578                 case 8 /* Decorate */: return "__decorate";
78579                 case 16 /* Metadata */: return "__metadata";
78580                 case 32 /* Param */: return "__param";
78581                 case 64 /* Awaiter */: return "__awaiter";
78582                 case 128 /* Generator */: return "__generator";
78583                 case 256 /* Values */: return "__values";
78584                 case 512 /* Read */: return "__read";
78585                 case 1024 /* Spread */: return "__spread";
78586                 case 2048 /* SpreadArrays */: return "__spreadArrays";
78587                 case 4096 /* Await */: return "__await";
78588                 case 8192 /* AsyncGenerator */: return "__asyncGenerator";
78589                 case 16384 /* AsyncDelegator */: return "__asyncDelegator";
78590                 case 32768 /* AsyncValues */: return "__asyncValues";
78591                 case 65536 /* ExportStar */: return "__exportStar";
78592                 case 131072 /* ImportStar */: return "__importStar";
78593                 case 262144 /* ImportDefault */: return "__importDefault";
78594                 case 524288 /* MakeTemplateObject */: return "__makeTemplateObject";
78595                 case 1048576 /* ClassPrivateFieldGet */: return "__classPrivateFieldGet";
78596                 case 2097152 /* ClassPrivateFieldSet */: return "__classPrivateFieldSet";
78597                 case 4194304 /* CreateBinding */: return "__createBinding";
78598                 default: return ts.Debug.fail("Unrecognized helper");
78599             }
78600         }
78601         function resolveHelpersModule(node, errorNode) {
78602             if (!externalHelpersModule) {
78603                 externalHelpersModule = resolveExternalModule(node, ts.externalHelpersModuleNameText, ts.Diagnostics.This_syntax_requires_an_imported_helper_but_module_0_cannot_be_found, errorNode) || unknownSymbol;
78604             }
78605             return externalHelpersModule;
78606         }
78607         // GRAMMAR CHECKING
78608         function checkGrammarDecoratorsAndModifiers(node) {
78609             return checkGrammarDecorators(node) || checkGrammarModifiers(node);
78610         }
78611         function checkGrammarDecorators(node) {
78612             if (!node.decorators) {
78613                 return false;
78614             }
78615             if (!ts.nodeCanBeDecorated(node, node.parent, node.parent.parent)) {
78616                 if (node.kind === 165 /* MethodDeclaration */ && !ts.nodeIsPresent(node.body)) {
78617                     return grammarErrorOnFirstToken(node, ts.Diagnostics.A_decorator_can_only_decorate_a_method_implementation_not_an_overload);
78618                 }
78619                 else {
78620                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_are_not_valid_here);
78621                 }
78622             }
78623             else if (node.kind === 167 /* GetAccessor */ || node.kind === 168 /* SetAccessor */) {
78624                 var accessors = ts.getAllAccessorDeclarations(node.parent.members, node);
78625                 if (accessors.firstAccessor.decorators && node === accessors.secondAccessor) {
78626                     return grammarErrorOnFirstToken(node, ts.Diagnostics.Decorators_cannot_be_applied_to_multiple_get_Slashset_accessors_of_the_same_name);
78627                 }
78628             }
78629             return false;
78630         }
78631         function checkGrammarModifiers(node) {
78632             var quickResult = reportObviousModifierErrors(node);
78633             if (quickResult !== undefined) {
78634                 return quickResult;
78635             }
78636             var lastStatic, lastDeclare, lastAsync, lastReadonly;
78637             var flags = 0 /* None */;
78638             for (var _i = 0, _a = node.modifiers; _i < _a.length; _i++) {
78639                 var modifier = _a[_i];
78640                 if (modifier.kind !== 142 /* ReadonlyKeyword */) {
78641                     if (node.kind === 162 /* PropertySignature */ || node.kind === 164 /* MethodSignature */) {
78642                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_type_member, ts.tokenToString(modifier.kind));
78643                     }
78644                     if (node.kind === 171 /* IndexSignature */) {
78645                         return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_an_index_signature, ts.tokenToString(modifier.kind));
78646                     }
78647                 }
78648                 switch (modifier.kind) {
78649                     case 84 /* ConstKeyword */:
78650                         if (node.kind !== 255 /* EnumDeclaration */) {
78651                             return grammarErrorOnNode(node, ts.Diagnostics.A_class_member_cannot_have_the_0_keyword, ts.tokenToString(84 /* ConstKeyword */));
78652                         }
78653                         break;
78654                     case 122 /* PublicKeyword */:
78655                     case 121 /* ProtectedKeyword */:
78656                     case 120 /* PrivateKeyword */:
78657                         var text = visibilityToString(ts.modifierToFlag(modifier.kind));
78658                         if (flags & 28 /* AccessibilityModifier */) {
78659                             return grammarErrorOnNode(modifier, ts.Diagnostics.Accessibility_modifier_already_seen);
78660                         }
78661                         else if (flags & 32 /* Static */) {
78662                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "static");
78663                         }
78664                         else if (flags & 64 /* Readonly */) {
78665                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "readonly");
78666                         }
78667                         else if (flags & 256 /* Async */) {
78668                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "async");
78669                         }
78670                         else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
78671                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, text);
78672                         }
78673                         else if (flags & 128 /* Abstract */) {
78674                             if (modifier.kind === 120 /* PrivateKeyword */) {
78675                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, text, "abstract");
78676                             }
78677                             else {
78678                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, text, "abstract");
78679                             }
78680                         }
78681                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
78682                             return grammarErrorOnNode(modifier, ts.Diagnostics.An_accessibility_modifier_cannot_be_used_with_a_private_identifier);
78683                         }
78684                         flags |= ts.modifierToFlag(modifier.kind);
78685                         break;
78686                     case 123 /* StaticKeyword */:
78687                         if (flags & 32 /* Static */) {
78688                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "static");
78689                         }
78690                         else if (flags & 64 /* Readonly */) {
78691                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "readonly");
78692                         }
78693                         else if (flags & 256 /* Async */) {
78694                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "static", "async");
78695                         }
78696                         else if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
78697                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_module_or_namespace_element, "static");
78698                         }
78699                         else if (node.kind === 160 /* Parameter */) {
78700                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "static");
78701                         }
78702                         else if (flags & 128 /* Abstract */) {
78703                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
78704                         }
78705                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
78706                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "static");
78707                         }
78708                         flags |= 32 /* Static */;
78709                         lastStatic = modifier;
78710                         break;
78711                     case 142 /* ReadonlyKeyword */:
78712                         if (flags & 64 /* Readonly */) {
78713                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "readonly");
78714                         }
78715                         else if (node.kind !== 163 /* PropertyDeclaration */ && node.kind !== 162 /* PropertySignature */ && node.kind !== 171 /* IndexSignature */ && node.kind !== 160 /* Parameter */) {
78716                             // If node.kind === SyntaxKind.Parameter, checkParameter report an error if it's not a parameter property.
78717                             return grammarErrorOnNode(modifier, ts.Diagnostics.readonly_modifier_can_only_appear_on_a_property_declaration_or_index_signature);
78718                         }
78719                         flags |= 64 /* Readonly */;
78720                         lastReadonly = modifier;
78721                         break;
78722                     case 92 /* ExportKeyword */:
78723                         if (flags & 1 /* Export */) {
78724                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "export");
78725                         }
78726                         else if (flags & 2 /* Ambient */) {
78727                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "declare");
78728                         }
78729                         else if (flags & 128 /* Abstract */) {
78730                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "abstract");
78731                         }
78732                         else if (flags & 256 /* Async */) {
78733                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_must_precede_1_modifier, "export", "async");
78734                         }
78735                         else if (ts.isClassLike(node.parent)) {
78736                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "export");
78737                         }
78738                         else if (node.kind === 160 /* Parameter */) {
78739                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "export");
78740                         }
78741                         flags |= 1 /* Export */;
78742                         break;
78743                     case 87 /* DefaultKeyword */:
78744                         var container = node.parent.kind === 297 /* SourceFile */ ? node.parent : node.parent.parent;
78745                         if (container.kind === 256 /* ModuleDeclaration */ && !ts.isAmbientModule(container)) {
78746                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_default_export_can_only_be_used_in_an_ECMAScript_style_module);
78747                         }
78748                         flags |= 512 /* Default */;
78749                         break;
78750                     case 133 /* DeclareKeyword */:
78751                         if (flags & 2 /* Ambient */) {
78752                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "declare");
78753                         }
78754                         else if (flags & 256 /* Async */) {
78755                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
78756                         }
78757                         else if (ts.isClassLike(node.parent) && !ts.isPropertyDeclaration(node)) {
78758                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_class_elements_of_this_kind, "declare");
78759                         }
78760                         else if (node.kind === 160 /* Parameter */) {
78761                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "declare");
78762                         }
78763                         else if ((node.parent.flags & 8388608 /* Ambient */) && node.parent.kind === 257 /* ModuleBlock */) {
78764                             return grammarErrorOnNode(modifier, ts.Diagnostics.A_declare_modifier_cannot_be_used_in_an_already_ambient_context);
78765                         }
78766                         else if (ts.isPrivateIdentifierPropertyDeclaration(node)) {
78767                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "declare");
78768                         }
78769                         flags |= 2 /* Ambient */;
78770                         lastDeclare = modifier;
78771                         break;
78772                     case 125 /* AbstractKeyword */:
78773                         if (flags & 128 /* Abstract */) {
78774                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "abstract");
78775                         }
78776                         if (node.kind !== 252 /* ClassDeclaration */) {
78777                             if (node.kind !== 165 /* MethodDeclaration */ &&
78778                                 node.kind !== 163 /* PropertyDeclaration */ &&
78779                                 node.kind !== 167 /* GetAccessor */ &&
78780                                 node.kind !== 168 /* SetAccessor */) {
78781                                 return grammarErrorOnNode(modifier, ts.Diagnostics.abstract_modifier_can_only_appear_on_a_class_method_or_property_declaration);
78782                             }
78783                             if (!(node.parent.kind === 252 /* ClassDeclaration */ && ts.hasSyntacticModifier(node.parent, 128 /* Abstract */))) {
78784                                 return grammarErrorOnNode(modifier, ts.Diagnostics.Abstract_methods_can_only_appear_within_an_abstract_class);
78785                             }
78786                             if (flags & 32 /* Static */) {
78787                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "static", "abstract");
78788                             }
78789                             if (flags & 8 /* Private */) {
78790                                 return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "private", "abstract");
78791                             }
78792                             if (flags & 256 /* Async */ && lastAsync) {
78793                                 return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
78794                             }
78795                         }
78796                         if (ts.isNamedDeclaration(node) && node.name.kind === 79 /* PrivateIdentifier */) {
78797                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_a_private_identifier, "abstract");
78798                         }
78799                         flags |= 128 /* Abstract */;
78800                         break;
78801                     case 129 /* AsyncKeyword */:
78802                         if (flags & 256 /* Async */) {
78803                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_already_seen, "async");
78804                         }
78805                         else if (flags & 2 /* Ambient */ || node.parent.flags & 8388608 /* Ambient */) {
78806                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_in_an_ambient_context, "async");
78807                         }
78808                         else if (node.kind === 160 /* Parameter */) {
78809                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_appear_on_a_parameter, "async");
78810                         }
78811                         if (flags & 128 /* Abstract */) {
78812                             return grammarErrorOnNode(modifier, ts.Diagnostics._0_modifier_cannot_be_used_with_1_modifier, "async", "abstract");
78813                         }
78814                         flags |= 256 /* Async */;
78815                         lastAsync = modifier;
78816                         break;
78817                 }
78818             }
78819             if (node.kind === 166 /* Constructor */) {
78820                 if (flags & 32 /* Static */) {
78821                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "static");
78822                 }
78823                 if (flags & 128 /* Abstract */) {
78824                     return grammarErrorOnNode(lastStatic, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "abstract"); // TODO: GH#18217
78825                 }
78826                 else if (flags & 256 /* Async */) {
78827                     return grammarErrorOnNode(lastAsync, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "async");
78828                 }
78829                 else if (flags & 64 /* Readonly */) {
78830                     return grammarErrorOnNode(lastReadonly, ts.Diagnostics._0_modifier_cannot_appear_on_a_constructor_declaration, "readonly");
78831                 }
78832                 return false;
78833             }
78834             else if ((node.kind === 261 /* ImportDeclaration */ || node.kind === 260 /* ImportEqualsDeclaration */) && flags & 2 /* Ambient */) {
78835                 return grammarErrorOnNode(lastDeclare, ts.Diagnostics.A_0_modifier_cannot_be_used_with_an_import_declaration, "declare");
78836             }
78837             else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && ts.isBindingPattern(node.name)) {
78838                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_may_not_be_declared_using_a_binding_pattern);
78839             }
78840             else if (node.kind === 160 /* Parameter */ && (flags & 92 /* ParameterPropertyModifier */) && node.dotDotDotToken) {
78841                 return grammarErrorOnNode(node, ts.Diagnostics.A_parameter_property_cannot_be_declared_using_a_rest_parameter);
78842             }
78843             if (flags & 256 /* Async */) {
78844                 return checkGrammarAsyncModifier(node, lastAsync);
78845             }
78846             return false;
78847         }
78848         /**
78849          * true | false: Early return this value from checkGrammarModifiers.
78850          * undefined: Need to do full checking on the modifiers.
78851          */
78852         function reportObviousModifierErrors(node) {
78853             return !node.modifiers
78854                 ? false
78855                 : shouldReportBadModifier(node)
78856                     ? grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here)
78857                     : undefined;
78858         }
78859         function shouldReportBadModifier(node) {
78860             switch (node.kind) {
78861                 case 167 /* GetAccessor */:
78862                 case 168 /* SetAccessor */:
78863                 case 166 /* Constructor */:
78864                 case 163 /* PropertyDeclaration */:
78865                 case 162 /* PropertySignature */:
78866                 case 165 /* MethodDeclaration */:
78867                 case 164 /* MethodSignature */:
78868                 case 171 /* IndexSignature */:
78869                 case 256 /* ModuleDeclaration */:
78870                 case 261 /* ImportDeclaration */:
78871                 case 260 /* ImportEqualsDeclaration */:
78872                 case 267 /* ExportDeclaration */:
78873                 case 266 /* ExportAssignment */:
78874                 case 208 /* FunctionExpression */:
78875                 case 209 /* ArrowFunction */:
78876                 case 160 /* Parameter */:
78877                     return false;
78878                 default:
78879                     if (node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
78880                         return false;
78881                     }
78882                     switch (node.kind) {
78883                         case 251 /* FunctionDeclaration */:
78884                             return nodeHasAnyModifiersExcept(node, 129 /* AsyncKeyword */);
78885                         case 252 /* ClassDeclaration */:
78886                             return nodeHasAnyModifiersExcept(node, 125 /* AbstractKeyword */);
78887                         case 253 /* InterfaceDeclaration */:
78888                         case 232 /* VariableStatement */:
78889                         case 254 /* TypeAliasDeclaration */:
78890                             return true;
78891                         case 255 /* EnumDeclaration */:
78892                             return nodeHasAnyModifiersExcept(node, 84 /* ConstKeyword */);
78893                         default:
78894                             ts.Debug.fail();
78895                             return false;
78896                     }
78897             }
78898         }
78899         function nodeHasAnyModifiersExcept(node, allowedModifier) {
78900             return node.modifiers.length > 1 || node.modifiers[0].kind !== allowedModifier;
78901         }
78902         function checkGrammarAsyncModifier(node, asyncModifier) {
78903             switch (node.kind) {
78904                 case 165 /* MethodDeclaration */:
78905                 case 251 /* FunctionDeclaration */:
78906                 case 208 /* FunctionExpression */:
78907                 case 209 /* ArrowFunction */:
78908                     return false;
78909             }
78910             return grammarErrorOnNode(asyncModifier, ts.Diagnostics._0_modifier_cannot_be_used_here, "async");
78911         }
78912         function checkGrammarForDisallowedTrailingComma(list, diag) {
78913             if (diag === void 0) { diag = ts.Diagnostics.Trailing_comma_not_allowed; }
78914             if (list && list.hasTrailingComma) {
78915                 return grammarErrorAtPos(list[0], list.end - ",".length, ",".length, diag);
78916             }
78917             return false;
78918         }
78919         function checkGrammarTypeParameterList(typeParameters, file) {
78920             if (typeParameters && typeParameters.length === 0) {
78921                 var start = typeParameters.pos - "<".length;
78922                 var end = ts.skipTrivia(file.text, typeParameters.end) + ">".length;
78923                 return grammarErrorAtPos(file, start, end - start, ts.Diagnostics.Type_parameter_list_cannot_be_empty);
78924             }
78925             return false;
78926         }
78927         function checkGrammarParameterList(parameters) {
78928             var seenOptionalParameter = false;
78929             var parameterCount = parameters.length;
78930             for (var i = 0; i < parameterCount; i++) {
78931                 var parameter = parameters[i];
78932                 if (parameter.dotDotDotToken) {
78933                     if (i !== (parameterCount - 1)) {
78934                         return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_rest_parameter_must_be_last_in_a_parameter_list);
78935                     }
78936                     if (!(parameter.flags & 8388608 /* Ambient */)) { // Allow `...foo,` in ambient declarations; see GH#23070
78937                         checkGrammarForDisallowedTrailingComma(parameters, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
78938                     }
78939                     if (parameter.questionToken) {
78940                         return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_rest_parameter_cannot_be_optional);
78941                     }
78942                     if (parameter.initializer) {
78943                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_rest_parameter_cannot_have_an_initializer);
78944                     }
78945                 }
78946                 else if (isOptionalParameter(parameter)) {
78947                     seenOptionalParameter = true;
78948                     if (parameter.questionToken && parameter.initializer) {
78949                         return grammarErrorOnNode(parameter.name, ts.Diagnostics.Parameter_cannot_have_question_mark_and_initializer);
78950                     }
78951                 }
78952                 else if (seenOptionalParameter && !parameter.initializer) {
78953                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.A_required_parameter_cannot_follow_an_optional_parameter);
78954                 }
78955             }
78956         }
78957         function getNonSimpleParameters(parameters) {
78958             return ts.filter(parameters, function (parameter) { return !!parameter.initializer || ts.isBindingPattern(parameter.name) || ts.isRestParameter(parameter); });
78959         }
78960         function checkGrammarForUseStrictSimpleParameterList(node) {
78961             if (languageVersion >= 3 /* ES2016 */) {
78962                 var useStrictDirective_1 = node.body && ts.isBlock(node.body) && ts.findUseStrictPrologue(node.body.statements);
78963                 if (useStrictDirective_1) {
78964                     var nonSimpleParameters = getNonSimpleParameters(node.parameters);
78965                     if (ts.length(nonSimpleParameters)) {
78966                         ts.forEach(nonSimpleParameters, function (parameter) {
78967                             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));
78968                         });
78969                         var diagnostics_2 = 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)); });
78970                         ts.addRelatedInfo.apply(void 0, __spreadArrays([error(useStrictDirective_1, ts.Diagnostics.use_strict_directive_cannot_be_used_with_non_simple_parameter_list)], diagnostics_2));
78971                         return true;
78972                     }
78973                 }
78974             }
78975             return false;
78976         }
78977         function checkGrammarFunctionLikeDeclaration(node) {
78978             // Prevent cascading error by short-circuit
78979             var file = ts.getSourceFileOfNode(node);
78980             return checkGrammarDecoratorsAndModifiers(node) ||
78981                 checkGrammarTypeParameterList(node.typeParameters, file) ||
78982                 checkGrammarParameterList(node.parameters) ||
78983                 checkGrammarArrowFunction(node, file) ||
78984                 (ts.isFunctionLikeDeclaration(node) && checkGrammarForUseStrictSimpleParameterList(node));
78985         }
78986         function checkGrammarClassLikeDeclaration(node) {
78987             var file = ts.getSourceFileOfNode(node);
78988             return checkGrammarClassDeclarationHeritageClauses(node) ||
78989                 checkGrammarTypeParameterList(node.typeParameters, file);
78990         }
78991         function checkGrammarArrowFunction(node, file) {
78992             if (!ts.isArrowFunction(node)) {
78993                 return false;
78994             }
78995             var equalsGreaterThanToken = node.equalsGreaterThanToken;
78996             var startLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.pos).line;
78997             var endLine = ts.getLineAndCharacterOfPosition(file, equalsGreaterThanToken.end).line;
78998             return startLine !== endLine && grammarErrorOnNode(equalsGreaterThanToken, ts.Diagnostics.Line_terminator_not_permitted_before_arrow);
78999         }
79000         function checkGrammarIndexSignatureParameters(node) {
79001             var parameter = node.parameters[0];
79002             if (node.parameters.length !== 1) {
79003                 if (parameter) {
79004                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
79005                 }
79006                 else {
79007                     return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_exactly_one_parameter);
79008                 }
79009             }
79010             checkGrammarForDisallowedTrailingComma(node.parameters, ts.Diagnostics.An_index_signature_cannot_have_a_trailing_comma);
79011             if (parameter.dotDotDotToken) {
79012                 return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.An_index_signature_cannot_have_a_rest_parameter);
79013             }
79014             if (ts.hasEffectiveModifiers(parameter)) {
79015                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_accessibility_modifier);
79016             }
79017             if (parameter.questionToken) {
79018                 return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.An_index_signature_parameter_cannot_have_a_question_mark);
79019             }
79020             if (parameter.initializer) {
79021                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_cannot_have_an_initializer);
79022             }
79023             if (!parameter.type) {
79024                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_must_have_a_type_annotation);
79025             }
79026             if (parameter.type.kind !== 147 /* StringKeyword */ && parameter.type.kind !== 144 /* NumberKeyword */) {
79027                 var type = getTypeFromTypeNode(parameter.type);
79028                 if (type.flags & 4 /* String */ || type.flags & 8 /* Number */) {
79029                     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));
79030                 }
79031                 if (type.flags & 1048576 /* Union */ && allTypesAssignableToKind(type, 384 /* StringOrNumberLiteral */, /*strict*/ true)) {
79032                     return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_cannot_be_a_union_type_Consider_using_a_mapped_object_type_instead);
79033                 }
79034                 return grammarErrorOnNode(parameter.name, ts.Diagnostics.An_index_signature_parameter_type_must_be_either_string_or_number);
79035             }
79036             if (!node.type) {
79037                 return grammarErrorOnNode(node, ts.Diagnostics.An_index_signature_must_have_a_type_annotation);
79038             }
79039             return false;
79040         }
79041         function checkGrammarIndexSignature(node) {
79042             // Prevent cascading error by short-circuit
79043             return checkGrammarDecoratorsAndModifiers(node) || checkGrammarIndexSignatureParameters(node);
79044         }
79045         function checkGrammarForAtLeastOneTypeArgument(node, typeArguments) {
79046             if (typeArguments && typeArguments.length === 0) {
79047                 var sourceFile = ts.getSourceFileOfNode(node);
79048                 var start = typeArguments.pos - "<".length;
79049                 var end = ts.skipTrivia(sourceFile.text, typeArguments.end) + ">".length;
79050                 return grammarErrorAtPos(sourceFile, start, end - start, ts.Diagnostics.Type_argument_list_cannot_be_empty);
79051             }
79052             return false;
79053         }
79054         function checkGrammarTypeArguments(node, typeArguments) {
79055             return checkGrammarForDisallowedTrailingComma(typeArguments) ||
79056                 checkGrammarForAtLeastOneTypeArgument(node, typeArguments);
79057         }
79058         function checkGrammarTaggedTemplateChain(node) {
79059             if (node.questionDotToken || node.flags & 32 /* OptionalChain */) {
79060                 return grammarErrorOnNode(node.template, ts.Diagnostics.Tagged_template_expressions_are_not_permitted_in_an_optional_chain);
79061             }
79062             return false;
79063         }
79064         function checkGrammarForOmittedArgument(args) {
79065             if (args) {
79066                 for (var _i = 0, args_4 = args; _i < args_4.length; _i++) {
79067                     var arg = args_4[_i];
79068                     if (arg.kind === 222 /* OmittedExpression */) {
79069                         return grammarErrorAtPos(arg, arg.pos, 0, ts.Diagnostics.Argument_expression_expected);
79070                     }
79071                 }
79072             }
79073             return false;
79074         }
79075         function checkGrammarArguments(args) {
79076             return checkGrammarForOmittedArgument(args);
79077         }
79078         function checkGrammarHeritageClause(node) {
79079             var types = node.types;
79080             if (checkGrammarForDisallowedTrailingComma(types)) {
79081                 return true;
79082             }
79083             if (types && types.length === 0) {
79084                 var listType = ts.tokenToString(node.token);
79085                 return grammarErrorAtPos(node, types.pos, 0, ts.Diagnostics._0_list_cannot_be_empty, listType);
79086             }
79087             return ts.some(types, checkGrammarExpressionWithTypeArguments);
79088         }
79089         function checkGrammarExpressionWithTypeArguments(node) {
79090             return checkGrammarTypeArguments(node, node.typeArguments);
79091         }
79092         function checkGrammarClassDeclarationHeritageClauses(node) {
79093             var seenExtendsClause = false;
79094             var seenImplementsClause = false;
79095             if (!checkGrammarDecoratorsAndModifiers(node) && node.heritageClauses) {
79096                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
79097                     var heritageClause = _a[_i];
79098                     if (heritageClause.token === 93 /* ExtendsKeyword */) {
79099                         if (seenExtendsClause) {
79100                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
79101                         }
79102                         if (seenImplementsClause) {
79103                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_must_precede_implements_clause);
79104                         }
79105                         if (heritageClause.types.length > 1) {
79106                             return grammarErrorOnFirstToken(heritageClause.types[1], ts.Diagnostics.Classes_can_only_extend_a_single_class);
79107                         }
79108                         seenExtendsClause = true;
79109                     }
79110                     else {
79111                         ts.Debug.assert(heritageClause.token === 116 /* ImplementsKeyword */);
79112                         if (seenImplementsClause) {
79113                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.implements_clause_already_seen);
79114                         }
79115                         seenImplementsClause = true;
79116                     }
79117                     // Grammar checking heritageClause inside class declaration
79118                     checkGrammarHeritageClause(heritageClause);
79119                 }
79120             }
79121         }
79122         function checkGrammarInterfaceDeclaration(node) {
79123             var seenExtendsClause = false;
79124             if (node.heritageClauses) {
79125                 for (var _i = 0, _a = node.heritageClauses; _i < _a.length; _i++) {
79126                     var heritageClause = _a[_i];
79127                     if (heritageClause.token === 93 /* ExtendsKeyword */) {
79128                         if (seenExtendsClause) {
79129                             return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.extends_clause_already_seen);
79130                         }
79131                         seenExtendsClause = true;
79132                     }
79133                     else {
79134                         ts.Debug.assert(heritageClause.token === 116 /* ImplementsKeyword */);
79135                         return grammarErrorOnFirstToken(heritageClause, ts.Diagnostics.Interface_declaration_cannot_have_implements_clause);
79136                     }
79137                     // Grammar checking heritageClause inside class declaration
79138                     checkGrammarHeritageClause(heritageClause);
79139                 }
79140             }
79141             return false;
79142         }
79143         function checkGrammarComputedPropertyName(node) {
79144             // If node is not a computedPropertyName, just skip the grammar checking
79145             if (node.kind !== 158 /* ComputedPropertyName */) {
79146                 return false;
79147             }
79148             var computedPropertyName = node;
79149             if (computedPropertyName.expression.kind === 216 /* BinaryExpression */ && computedPropertyName.expression.operatorToken.kind === 27 /* CommaToken */) {
79150                 return grammarErrorOnNode(computedPropertyName.expression, ts.Diagnostics.A_comma_expression_is_not_allowed_in_a_computed_property_name);
79151             }
79152             return false;
79153         }
79154         function checkGrammarForGenerator(node) {
79155             if (node.asteriskToken) {
79156                 ts.Debug.assert(node.kind === 251 /* FunctionDeclaration */ ||
79157                     node.kind === 208 /* FunctionExpression */ ||
79158                     node.kind === 165 /* MethodDeclaration */);
79159                 if (node.flags & 8388608 /* Ambient */) {
79160                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.Generators_are_not_allowed_in_an_ambient_context);
79161                 }
79162                 if (!node.body) {
79163                     return grammarErrorOnNode(node.asteriskToken, ts.Diagnostics.An_overload_signature_cannot_be_declared_as_a_generator);
79164                 }
79165             }
79166         }
79167         function checkGrammarForInvalidQuestionMark(questionToken, message) {
79168             return !!questionToken && grammarErrorOnNode(questionToken, message);
79169         }
79170         function checkGrammarForInvalidExclamationToken(exclamationToken, message) {
79171             return !!exclamationToken && grammarErrorOnNode(exclamationToken, message);
79172         }
79173         function checkGrammarObjectLiteralExpression(node, inDestructuring) {
79174             var seen = new ts.Map();
79175             for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
79176                 var prop = _a[_i];
79177                 if (prop.kind === 290 /* SpreadAssignment */) {
79178                     if (inDestructuring) {
79179                         // a rest property cannot be destructured any further
79180                         var expression = ts.skipParentheses(prop.expression);
79181                         if (ts.isArrayLiteralExpression(expression) || ts.isObjectLiteralExpression(expression)) {
79182                             return grammarErrorOnNode(prop.expression, ts.Diagnostics.A_rest_element_cannot_contain_a_binding_pattern);
79183                         }
79184                     }
79185                     continue;
79186                 }
79187                 var name = prop.name;
79188                 if (name.kind === 158 /* ComputedPropertyName */) {
79189                     // If the name is not a ComputedPropertyName, the grammar checking will skip it
79190                     checkGrammarComputedPropertyName(name);
79191                 }
79192                 if (prop.kind === 289 /* ShorthandPropertyAssignment */ && !inDestructuring && prop.objectAssignmentInitializer) {
79193                     // having objectAssignmentInitializer is only valid in ObjectAssignmentPattern
79194                     // outside of destructuring it is a syntax error
79195                     return grammarErrorOnNode(prop.equalsToken, ts.Diagnostics.Did_you_mean_to_use_a_Colon_An_can_only_follow_a_property_name_when_the_containing_object_literal_is_part_of_a_destructuring_pattern);
79196                 }
79197                 if (name.kind === 79 /* PrivateIdentifier */) {
79198                     return grammarErrorOnNode(name, ts.Diagnostics.Private_identifiers_are_not_allowed_outside_class_bodies);
79199                 }
79200                 // Modifiers are never allowed on properties except for 'async' on a method declaration
79201                 if (prop.modifiers) {
79202                     // eslint-disable-next-line @typescript-eslint/no-unnecessary-type-assertion
79203                     for (var _b = 0, _c = prop.modifiers; _b < _c.length; _b++) { // TODO: GH#19955
79204                         var mod = _c[_b];
79205                         if (mod.kind !== 129 /* AsyncKeyword */ || prop.kind !== 165 /* MethodDeclaration */) {
79206                             grammarErrorOnNode(mod, ts.Diagnostics._0_modifier_cannot_be_used_here, ts.getTextOfNode(mod));
79207                         }
79208                     }
79209                 }
79210                 // ECMA-262 11.1.5 Object Initializer
79211                 // If previous is not undefined then throw a SyntaxError exception if any of the following conditions are true
79212                 // a.This production is contained in strict code and IsDataDescriptor(previous) is true and
79213                 // IsDataDescriptor(propId.descriptor) is true.
79214                 //    b.IsDataDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true.
79215                 //    c.IsAccessorDescriptor(previous) is true and IsDataDescriptor(propId.descriptor) is true.
79216                 //    d.IsAccessorDescriptor(previous) is true and IsAccessorDescriptor(propId.descriptor) is true
79217                 // and either both previous and propId.descriptor have[[Get]] fields or both previous and propId.descriptor have[[Set]] fields
79218                 var currentKind = void 0;
79219                 switch (prop.kind) {
79220                     case 289 /* ShorthandPropertyAssignment */:
79221                         checkGrammarForInvalidExclamationToken(prop.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context);
79222                     // falls through
79223                     case 288 /* PropertyAssignment */:
79224                         // Grammar checking for computedPropertyName and shorthandPropertyAssignment
79225                         checkGrammarForInvalidQuestionMark(prop.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional);
79226                         if (name.kind === 8 /* NumericLiteral */) {
79227                             checkGrammarNumericLiteral(name);
79228                         }
79229                         currentKind = 4 /* PropertyAssignment */;
79230                         break;
79231                     case 165 /* MethodDeclaration */:
79232                         currentKind = 8 /* Method */;
79233                         break;
79234                     case 167 /* GetAccessor */:
79235                         currentKind = 1 /* GetAccessor */;
79236                         break;
79237                     case 168 /* SetAccessor */:
79238                         currentKind = 2 /* SetAccessor */;
79239                         break;
79240                     default:
79241                         throw ts.Debug.assertNever(prop, "Unexpected syntax kind:" + prop.kind);
79242                 }
79243                 if (!inDestructuring) {
79244                     var effectiveName = ts.getPropertyNameForPropertyNameNode(name);
79245                     if (effectiveName === undefined) {
79246                         continue;
79247                     }
79248                     var existingKind = seen.get(effectiveName);
79249                     if (!existingKind) {
79250                         seen.set(effectiveName, currentKind);
79251                     }
79252                     else {
79253                         if ((currentKind & 12 /* PropertyAssignmentOrMethod */) && (existingKind & 12 /* PropertyAssignmentOrMethod */)) {
79254                             grammarErrorOnNode(name, ts.Diagnostics.Duplicate_identifier_0, ts.getTextOfNode(name));
79255                         }
79256                         else if ((currentKind & 3 /* GetOrSetAccessor */) && (existingKind & 3 /* GetOrSetAccessor */)) {
79257                             if (existingKind !== 3 /* GetOrSetAccessor */ && currentKind !== existingKind) {
79258                                 seen.set(effectiveName, currentKind | existingKind);
79259                             }
79260                             else {
79261                                 return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_multiple_get_Slashset_accessors_with_the_same_name);
79262                             }
79263                         }
79264                         else {
79265                             return grammarErrorOnNode(name, ts.Diagnostics.An_object_literal_cannot_have_property_and_accessor_with_the_same_name);
79266                         }
79267                     }
79268                 }
79269             }
79270         }
79271         function checkGrammarJsxElement(node) {
79272             checkGrammarTypeArguments(node, node.typeArguments);
79273             var seen = new ts.Map();
79274             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
79275                 var attr = _a[_i];
79276                 if (attr.kind === 282 /* JsxSpreadAttribute */) {
79277                     continue;
79278                 }
79279                 var name = attr.name, initializer = attr.initializer;
79280                 if (!seen.get(name.escapedText)) {
79281                     seen.set(name.escapedText, true);
79282                 }
79283                 else {
79284                     return grammarErrorOnNode(name, ts.Diagnostics.JSX_elements_cannot_have_multiple_attributes_with_the_same_name);
79285                 }
79286                 if (initializer && initializer.kind === 283 /* JsxExpression */ && !initializer.expression) {
79287                     return grammarErrorOnNode(initializer, ts.Diagnostics.JSX_attributes_must_only_be_assigned_a_non_empty_expression);
79288                 }
79289             }
79290         }
79291         function checkGrammarJsxExpression(node) {
79292             if (node.expression && ts.isCommaSequence(node.expression)) {
79293                 return grammarErrorOnNode(node.expression, ts.Diagnostics.JSX_expressions_may_not_use_the_comma_operator_Did_you_mean_to_write_an_array);
79294             }
79295         }
79296         function checkGrammarForInOrForOfStatement(forInOrOfStatement) {
79297             if (checkGrammarStatementInAmbientContext(forInOrOfStatement)) {
79298                 return true;
79299             }
79300             if (forInOrOfStatement.kind === 239 /* ForOfStatement */ && forInOrOfStatement.awaitModifier) {
79301                 if ((forInOrOfStatement.flags & 32768 /* AwaitContext */) === 0 /* None */) {
79302                     // use of 'for-await-of' in non-async function
79303                     var sourceFile = ts.getSourceFileOfNode(forInOrOfStatement);
79304                     if (!hasParseDiagnostics(sourceFile)) {
79305                         var diagnostic = ts.createDiagnosticForNode(forInOrOfStatement.awaitModifier, ts.Diagnostics.A_for_await_of_statement_is_only_allowed_within_an_async_function_or_async_generator);
79306                         var func = ts.getContainingFunction(forInOrOfStatement);
79307                         if (func && func.kind !== 166 /* Constructor */) {
79308                             ts.Debug.assert((ts.getFunctionFlags(func) & 2 /* Async */) === 0, "Enclosing function should never be an async function.");
79309                             var relatedInfo = ts.createDiagnosticForNode(func, ts.Diagnostics.Did_you_mean_to_mark_this_function_as_async);
79310                             ts.addRelatedInfo(diagnostic, relatedInfo);
79311                         }
79312                         diagnostics.add(diagnostic);
79313                         return true;
79314                     }
79315                     return false;
79316                 }
79317             }
79318             if (forInOrOfStatement.initializer.kind === 250 /* VariableDeclarationList */) {
79319                 var variableList = forInOrOfStatement.initializer;
79320                 if (!checkGrammarVariableDeclarationList(variableList)) {
79321                     var declarations = variableList.declarations;
79322                     // declarations.length can be zero if there is an error in variable declaration in for-of or for-in
79323                     // See http://www.ecma-international.org/ecma-262/6.0/#sec-for-in-and-for-of-statements for details
79324                     // For example:
79325                     //      var let = 10;
79326                     //      for (let of [1,2,3]) {} // this is invalid ES6 syntax
79327                     //      for (let in [1,2,3]) {} // this is invalid ES6 syntax
79328                     // We will then want to skip on grammar checking on variableList declaration
79329                     if (!declarations.length) {
79330                         return false;
79331                     }
79332                     if (declarations.length > 1) {
79333                         var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */
79334                             ? ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_in_statement
79335                             : ts.Diagnostics.Only_a_single_variable_declaration_is_allowed_in_a_for_of_statement;
79336                         return grammarErrorOnFirstToken(variableList.declarations[1], diagnostic);
79337                     }
79338                     var firstDeclaration = declarations[0];
79339                     if (firstDeclaration.initializer) {
79340                         var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */
79341                             ? ts.Diagnostics.The_variable_declaration_of_a_for_in_statement_cannot_have_an_initializer
79342                             : ts.Diagnostics.The_variable_declaration_of_a_for_of_statement_cannot_have_an_initializer;
79343                         return grammarErrorOnNode(firstDeclaration.name, diagnostic);
79344                     }
79345                     if (firstDeclaration.type) {
79346                         var diagnostic = forInOrOfStatement.kind === 238 /* ForInStatement */
79347                             ? ts.Diagnostics.The_left_hand_side_of_a_for_in_statement_cannot_use_a_type_annotation
79348                             : ts.Diagnostics.The_left_hand_side_of_a_for_of_statement_cannot_use_a_type_annotation;
79349                         return grammarErrorOnNode(firstDeclaration, diagnostic);
79350                     }
79351                 }
79352             }
79353             return false;
79354         }
79355         function checkGrammarAccessor(accessor) {
79356             if (!(accessor.flags & 8388608 /* Ambient */)) {
79357                 if (languageVersion < 1 /* ES5 */) {
79358                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.Accessors_are_only_available_when_targeting_ECMAScript_5_and_higher);
79359                 }
79360                 if (accessor.body === undefined && !ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
79361                     return grammarErrorAtPos(accessor, accessor.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
79362                 }
79363             }
79364             if (accessor.body && ts.hasSyntacticModifier(accessor, 128 /* Abstract */)) {
79365                 return grammarErrorOnNode(accessor, ts.Diagnostics.An_abstract_accessor_cannot_have_an_implementation);
79366             }
79367             if (accessor.typeParameters) {
79368                 return grammarErrorOnNode(accessor.name, ts.Diagnostics.An_accessor_cannot_have_type_parameters);
79369             }
79370             if (!doesAccessorHaveCorrectParameterCount(accessor)) {
79371                 return grammarErrorOnNode(accessor.name, accessor.kind === 167 /* GetAccessor */ ?
79372                     ts.Diagnostics.A_get_accessor_cannot_have_parameters :
79373                     ts.Diagnostics.A_set_accessor_must_have_exactly_one_parameter);
79374             }
79375             if (accessor.kind === 168 /* SetAccessor */) {
79376                 if (accessor.type) {
79377                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_cannot_have_a_return_type_annotation);
79378                 }
79379                 var parameter = ts.Debug.checkDefined(ts.getSetAccessorValueParameter(accessor), "Return value does not match parameter count assertion.");
79380                 if (parameter.dotDotDotToken) {
79381                     return grammarErrorOnNode(parameter.dotDotDotToken, ts.Diagnostics.A_set_accessor_cannot_have_rest_parameter);
79382                 }
79383                 if (parameter.questionToken) {
79384                     return grammarErrorOnNode(parameter.questionToken, ts.Diagnostics.A_set_accessor_cannot_have_an_optional_parameter);
79385                 }
79386                 if (parameter.initializer) {
79387                     return grammarErrorOnNode(accessor.name, ts.Diagnostics.A_set_accessor_parameter_cannot_have_an_initializer);
79388                 }
79389             }
79390             return false;
79391         }
79392         /** Does the accessor have the right number of parameters?
79393          * A get accessor has no parameters or a single `this` parameter.
79394          * A set accessor has one parameter or a `this` parameter and one more parameter.
79395          */
79396         function doesAccessorHaveCorrectParameterCount(accessor) {
79397             return getAccessorThisParameter(accessor) || accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 0 : 1);
79398         }
79399         function getAccessorThisParameter(accessor) {
79400             if (accessor.parameters.length === (accessor.kind === 167 /* GetAccessor */ ? 1 : 2)) {
79401                 return ts.getThisParameter(accessor);
79402             }
79403         }
79404         function checkGrammarTypeOperatorNode(node) {
79405             if (node.operator === 151 /* UniqueKeyword */) {
79406                 if (node.type.kind !== 148 /* SymbolKeyword */) {
79407                     return grammarErrorOnNode(node.type, ts.Diagnostics._0_expected, ts.tokenToString(148 /* SymbolKeyword */));
79408                 }
79409                 var parent = ts.walkUpParenthesizedTypes(node.parent);
79410                 if (ts.isInJSFile(parent) && ts.isJSDocTypeExpression(parent)) {
79411                     parent = parent.parent;
79412                     if (ts.isJSDocTypeTag(parent)) {
79413                         // walk up past JSDoc comment node
79414                         parent = parent.parent.parent;
79415                     }
79416                 }
79417                 switch (parent.kind) {
79418                     case 249 /* VariableDeclaration */:
79419                         var decl = parent;
79420                         if (decl.name.kind !== 78 /* Identifier */) {
79421                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_may_not_be_used_on_a_variable_declaration_with_a_binding_name);
79422                         }
79423                         if (!ts.isVariableDeclarationInVariableStatement(decl)) {
79424                             return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_only_allowed_on_variables_in_a_variable_statement);
79425                         }
79426                         if (!(decl.parent.flags & 2 /* Const */)) {
79427                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_variable_whose_type_is_a_unique_symbol_type_must_be_const);
79428                         }
79429                         break;
79430                     case 163 /* PropertyDeclaration */:
79431                         if (!ts.hasSyntacticModifier(parent, 32 /* Static */) ||
79432                             !ts.hasEffectiveModifier(parent, 64 /* Readonly */)) {
79433                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_a_class_whose_type_is_a_unique_symbol_type_must_be_both_static_and_readonly);
79434                         }
79435                         break;
79436                     case 162 /* PropertySignature */:
79437                         if (!ts.hasSyntacticModifier(parent, 64 /* Readonly */)) {
79438                             return grammarErrorOnNode(parent.name, ts.Diagnostics.A_property_of_an_interface_or_type_literal_whose_type_is_a_unique_symbol_type_must_be_readonly);
79439                         }
79440                         break;
79441                     default:
79442                         return grammarErrorOnNode(node, ts.Diagnostics.unique_symbol_types_are_not_allowed_here);
79443                 }
79444             }
79445             else if (node.operator === 142 /* ReadonlyKeyword */) {
79446                 if (node.type.kind !== 178 /* ArrayType */ && node.type.kind !== 179 /* TupleType */) {
79447                     return grammarErrorOnFirstToken(node, ts.Diagnostics.readonly_type_modifier_is_only_permitted_on_array_and_tuple_literal_types, ts.tokenToString(148 /* SymbolKeyword */));
79448                 }
79449             }
79450         }
79451         function checkGrammarForInvalidDynamicName(node, message) {
79452             if (isNonBindableDynamicName(node)) {
79453                 return grammarErrorOnNode(node, message);
79454             }
79455         }
79456         function checkGrammarMethod(node) {
79457             if (checkGrammarFunctionLikeDeclaration(node)) {
79458                 return true;
79459             }
79460             if (node.kind === 165 /* MethodDeclaration */) {
79461                 if (node.parent.kind === 200 /* ObjectLiteralExpression */) {
79462                     // We only disallow modifier on a method declaration if it is a property of object-literal-expression
79463                     if (node.modifiers && !(node.modifiers.length === 1 && ts.first(node.modifiers).kind === 129 /* AsyncKeyword */)) {
79464                         return grammarErrorOnFirstToken(node, ts.Diagnostics.Modifiers_cannot_appear_here);
79465                     }
79466                     else if (checkGrammarForInvalidQuestionMark(node.questionToken, ts.Diagnostics.An_object_member_cannot_be_declared_optional)) {
79467                         return true;
79468                     }
79469                     else if (checkGrammarForInvalidExclamationToken(node.exclamationToken, ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context)) {
79470                         return true;
79471                     }
79472                     else if (node.body === undefined) {
79473                         return grammarErrorAtPos(node, node.end - 1, ";".length, ts.Diagnostics._0_expected, "{");
79474                     }
79475                 }
79476                 if (checkGrammarForGenerator(node)) {
79477                     return true;
79478                 }
79479             }
79480             if (ts.isClassLike(node.parent)) {
79481                 // Technically, computed properties in ambient contexts is disallowed
79482                 // for property declarations and accessors too, not just methods.
79483                 // However, property declarations disallow computed names in general,
79484                 // and accessors are not allowed in ambient contexts in general,
79485                 // so this error only really matters for methods.
79486                 if (node.flags & 8388608 /* Ambient */) {
79487                     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);
79488                 }
79489                 else if (node.kind === 165 /* MethodDeclaration */ && !node.body) {
79490                     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);
79491                 }
79492             }
79493             else if (node.parent.kind === 253 /* InterfaceDeclaration */) {
79494                 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);
79495             }
79496             else if (node.parent.kind === 177 /* TypeLiteral */) {
79497                 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);
79498             }
79499         }
79500         function checkGrammarBreakOrContinueStatement(node) {
79501             var current = node;
79502             while (current) {
79503                 if (ts.isFunctionLike(current)) {
79504                     return grammarErrorOnNode(node, ts.Diagnostics.Jump_target_cannot_cross_function_boundary);
79505                 }
79506                 switch (current.kind) {
79507                     case 245 /* LabeledStatement */:
79508                         if (node.label && current.label.escapedText === node.label.escapedText) {
79509                             // found matching label - verify that label usage is correct
79510                             // continue can only target labels that are on iteration statements
79511                             var isMisplacedContinueLabel = node.kind === 240 /* ContinueStatement */
79512                                 && !ts.isIterationStatement(current.statement, /*lookInLabeledStatement*/ true);
79513                             if (isMisplacedContinueLabel) {
79514                                 return grammarErrorOnNode(node, ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement);
79515                             }
79516                             return false;
79517                         }
79518                         break;
79519                     case 244 /* SwitchStatement */:
79520                         if (node.kind === 241 /* BreakStatement */ && !node.label) {
79521                             // unlabeled break within switch statement - ok
79522                             return false;
79523                         }
79524                         break;
79525                     default:
79526                         if (ts.isIterationStatement(current, /*lookInLabeledStatement*/ false) && !node.label) {
79527                             // unlabeled break or continue within iteration statement - ok
79528                             return false;
79529                         }
79530                         break;
79531                 }
79532                 current = current.parent;
79533             }
79534             if (node.label) {
79535                 var message = node.kind === 241 /* BreakStatement */
79536                     ? ts.Diagnostics.A_break_statement_can_only_jump_to_a_label_of_an_enclosing_statement
79537                     : ts.Diagnostics.A_continue_statement_can_only_jump_to_a_label_of_an_enclosing_iteration_statement;
79538                 return grammarErrorOnNode(node, message);
79539             }
79540             else {
79541                 var message = node.kind === 241 /* BreakStatement */
79542                     ? ts.Diagnostics.A_break_statement_can_only_be_used_within_an_enclosing_iteration_or_switch_statement
79543                     : ts.Diagnostics.A_continue_statement_can_only_be_used_within_an_enclosing_iteration_statement;
79544                 return grammarErrorOnNode(node, message);
79545             }
79546         }
79547         function checkGrammarBindingElement(node) {
79548             if (node.dotDotDotToken) {
79549                 var elements = node.parent.elements;
79550                 if (node !== ts.last(elements)) {
79551                     return grammarErrorOnNode(node, ts.Diagnostics.A_rest_element_must_be_last_in_a_destructuring_pattern);
79552                 }
79553                 checkGrammarForDisallowedTrailingComma(elements, ts.Diagnostics.A_rest_parameter_or_binding_pattern_may_not_have_a_trailing_comma);
79554                 if (node.propertyName) {
79555                     return grammarErrorOnNode(node.name, ts.Diagnostics.A_rest_element_cannot_have_a_property_name);
79556                 }
79557             }
79558             if (node.dotDotDotToken && node.initializer) {
79559                 // Error on equals token which immediately precedes the initializer
79560                 return grammarErrorAtPos(node, node.initializer.pos - 1, 1, ts.Diagnostics.A_rest_element_cannot_have_an_initializer);
79561             }
79562         }
79563         function isStringOrNumberLiteralExpression(expr) {
79564             return ts.isStringOrNumericLiteralLike(expr) ||
79565                 expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
79566                     expr.operand.kind === 8 /* NumericLiteral */;
79567         }
79568         function isBigIntLiteralExpression(expr) {
79569             return expr.kind === 9 /* BigIntLiteral */ ||
79570                 expr.kind === 214 /* PrefixUnaryExpression */ && expr.operator === 40 /* MinusToken */ &&
79571                     expr.operand.kind === 9 /* BigIntLiteral */;
79572         }
79573         function isSimpleLiteralEnumReference(expr) {
79574             if ((ts.isPropertyAccessExpression(expr) || (ts.isElementAccessExpression(expr) && isStringOrNumberLiteralExpression(expr.argumentExpression))) &&
79575                 ts.isEntityNameExpression(expr.expression)) {
79576                 return !!(checkExpressionCached(expr).flags & 1024 /* EnumLiteral */);
79577             }
79578         }
79579         function checkAmbientInitializer(node) {
79580             var initializer = node.initializer;
79581             if (initializer) {
79582                 var isInvalidInitializer = !(isStringOrNumberLiteralExpression(initializer) ||
79583                     isSimpleLiteralEnumReference(initializer) ||
79584                     initializer.kind === 109 /* TrueKeyword */ || initializer.kind === 94 /* FalseKeyword */ ||
79585                     isBigIntLiteralExpression(initializer));
79586                 var isConstOrReadonly = ts.isDeclarationReadonly(node) || ts.isVariableDeclaration(node) && ts.isVarConst(node);
79587                 if (isConstOrReadonly && !node.type) {
79588                     if (isInvalidInitializer) {
79589                         return grammarErrorOnNode(initializer, ts.Diagnostics.A_const_initializer_in_an_ambient_context_must_be_a_string_or_numeric_literal_or_literal_enum_reference);
79590                     }
79591                 }
79592                 else {
79593                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
79594                 }
79595                 if (!isConstOrReadonly || isInvalidInitializer) {
79596                     return grammarErrorOnNode(initializer, ts.Diagnostics.Initializers_are_not_allowed_in_ambient_contexts);
79597                 }
79598             }
79599         }
79600         function checkGrammarVariableDeclaration(node) {
79601             if (node.parent.parent.kind !== 238 /* ForInStatement */ && node.parent.parent.kind !== 239 /* ForOfStatement */) {
79602                 if (node.flags & 8388608 /* Ambient */) {
79603                     checkAmbientInitializer(node);
79604                 }
79605                 else if (!node.initializer) {
79606                     if (ts.isBindingPattern(node.name) && !ts.isBindingPattern(node.parent)) {
79607                         return grammarErrorOnNode(node, ts.Diagnostics.A_destructuring_declaration_must_have_an_initializer);
79608                     }
79609                     if (ts.isVarConst(node)) {
79610                         return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_must_be_initialized);
79611                     }
79612                 }
79613             }
79614             if (node.exclamationToken && (node.parent.parent.kind !== 232 /* VariableStatement */ || !node.type || node.initializer || node.flags & 8388608 /* Ambient */)) {
79615                 var message = node.initializer
79616                     ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions
79617                     : ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations;
79618                 return grammarErrorOnNode(node.exclamationToken, message);
79619             }
79620             var moduleKind = ts.getEmitModuleKind(compilerOptions);
79621             if (moduleKind < ts.ModuleKind.ES2015 && moduleKind !== ts.ModuleKind.System &&
79622                 !(node.parent.parent.flags & 8388608 /* Ambient */) && ts.hasSyntacticModifier(node.parent.parent, 1 /* Export */)) {
79623                 checkESModuleMarker(node.name);
79624             }
79625             var checkLetConstNames = (ts.isLet(node) || ts.isVarConst(node));
79626             // 1. LexicalDeclaration : LetOrConst BindingList ;
79627             // It is a Syntax Error if the BoundNames of BindingList contains "let".
79628             // 2. ForDeclaration: ForDeclaration : LetOrConst ForBinding
79629             // It is a Syntax Error if the BoundNames of ForDeclaration contains "let".
79630             // It is a SyntaxError if a VariableDeclaration or VariableDeclarationNoIn occurs within strict code
79631             // and its Identifier is eval or arguments
79632             return checkLetConstNames && checkGrammarNameInLetOrConstDeclarations(node.name);
79633         }
79634         function checkESModuleMarker(name) {
79635             if (name.kind === 78 /* Identifier */) {
79636                 if (ts.idText(name) === "__esModule") {
79637                     return grammarErrorOnNodeSkippedOn("noEmit", name, ts.Diagnostics.Identifier_expected_esModule_is_reserved_as_an_exported_marker_when_transforming_ECMAScript_modules);
79638                 }
79639             }
79640             else {
79641                 var elements = name.elements;
79642                 for (var _i = 0, elements_1 = elements; _i < elements_1.length; _i++) {
79643                     var element = elements_1[_i];
79644                     if (!ts.isOmittedExpression(element)) {
79645                         return checkESModuleMarker(element.name);
79646                     }
79647                 }
79648             }
79649             return false;
79650         }
79651         function checkGrammarNameInLetOrConstDeclarations(name) {
79652             if (name.kind === 78 /* Identifier */) {
79653                 if (name.originalKeywordKind === 118 /* LetKeyword */) {
79654                     return grammarErrorOnNode(name, ts.Diagnostics.let_is_not_allowed_to_be_used_as_a_name_in_let_or_const_declarations);
79655                 }
79656             }
79657             else {
79658                 var elements = name.elements;
79659                 for (var _i = 0, elements_2 = elements; _i < elements_2.length; _i++) {
79660                     var element = elements_2[_i];
79661                     if (!ts.isOmittedExpression(element)) {
79662                         checkGrammarNameInLetOrConstDeclarations(element.name);
79663                     }
79664                 }
79665             }
79666             return false;
79667         }
79668         function checkGrammarVariableDeclarationList(declarationList) {
79669             var declarations = declarationList.declarations;
79670             if (checkGrammarForDisallowedTrailingComma(declarationList.declarations)) {
79671                 return true;
79672             }
79673             if (!declarationList.declarations.length) {
79674                 return grammarErrorAtPos(declarationList, declarations.pos, declarations.end - declarations.pos, ts.Diagnostics.Variable_declaration_list_cannot_be_empty);
79675             }
79676             return false;
79677         }
79678         function allowLetAndConstDeclarations(parent) {
79679             switch (parent.kind) {
79680                 case 234 /* IfStatement */:
79681                 case 235 /* DoStatement */:
79682                 case 236 /* WhileStatement */:
79683                 case 243 /* WithStatement */:
79684                 case 237 /* ForStatement */:
79685                 case 238 /* ForInStatement */:
79686                 case 239 /* ForOfStatement */:
79687                     return false;
79688                 case 245 /* LabeledStatement */:
79689                     return allowLetAndConstDeclarations(parent.parent);
79690             }
79691             return true;
79692         }
79693         function checkGrammarForDisallowedLetOrConstStatement(node) {
79694             if (!allowLetAndConstDeclarations(node.parent)) {
79695                 if (ts.isLet(node.declarationList)) {
79696                     return grammarErrorOnNode(node, ts.Diagnostics.let_declarations_can_only_be_declared_inside_a_block);
79697                 }
79698                 else if (ts.isVarConst(node.declarationList)) {
79699                     return grammarErrorOnNode(node, ts.Diagnostics.const_declarations_can_only_be_declared_inside_a_block);
79700                 }
79701             }
79702         }
79703         function checkGrammarMetaProperty(node) {
79704             var escapedText = node.name.escapedText;
79705             switch (node.keywordToken) {
79706                 case 102 /* NewKeyword */:
79707                     if (escapedText !== "target") {
79708                         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");
79709                     }
79710                     break;
79711                 case 99 /* ImportKeyword */:
79712                     if (escapedText !== "meta") {
79713                         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");
79714                     }
79715                     break;
79716             }
79717         }
79718         function hasParseDiagnostics(sourceFile) {
79719             return sourceFile.parseDiagnostics.length > 0;
79720         }
79721         function grammarErrorOnFirstToken(node, message, arg0, arg1, arg2) {
79722             var sourceFile = ts.getSourceFileOfNode(node);
79723             if (!hasParseDiagnostics(sourceFile)) {
79724                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
79725                 diagnostics.add(ts.createFileDiagnostic(sourceFile, span.start, span.length, message, arg0, arg1, arg2));
79726                 return true;
79727             }
79728             return false;
79729         }
79730         function grammarErrorAtPos(nodeForSourceFile, start, length, message, arg0, arg1, arg2) {
79731             var sourceFile = ts.getSourceFileOfNode(nodeForSourceFile);
79732             if (!hasParseDiagnostics(sourceFile)) {
79733                 diagnostics.add(ts.createFileDiagnostic(sourceFile, start, length, message, arg0, arg1, arg2));
79734                 return true;
79735             }
79736             return false;
79737         }
79738         function grammarErrorOnNodeSkippedOn(key, node, message, arg0, arg1, arg2) {
79739             var sourceFile = ts.getSourceFileOfNode(node);
79740             if (!hasParseDiagnostics(sourceFile)) {
79741                 errorSkippedOn(key, node, message, arg0, arg1, arg2);
79742                 return true;
79743             }
79744             return false;
79745         }
79746         function grammarErrorOnNode(node, message, arg0, arg1, arg2) {
79747             var sourceFile = ts.getSourceFileOfNode(node);
79748             if (!hasParseDiagnostics(sourceFile)) {
79749                 diagnostics.add(ts.createDiagnosticForNode(node, message, arg0, arg1, arg2));
79750                 return true;
79751             }
79752             return false;
79753         }
79754         function checkGrammarConstructorTypeParameters(node) {
79755             var jsdocTypeParameters = ts.isInJSFile(node) ? ts.getJSDocTypeParameterDeclarations(node) : undefined;
79756             var range = node.typeParameters || jsdocTypeParameters && ts.firstOrUndefined(jsdocTypeParameters);
79757             if (range) {
79758                 var pos = range.pos === range.end ? range.pos : ts.skipTrivia(ts.getSourceFileOfNode(node).text, range.pos);
79759                 return grammarErrorAtPos(node, pos, range.end - pos, ts.Diagnostics.Type_parameters_cannot_appear_on_a_constructor_declaration);
79760             }
79761         }
79762         function checkGrammarConstructorTypeAnnotation(node) {
79763             var type = ts.getEffectiveReturnTypeNode(node);
79764             if (type) {
79765                 return grammarErrorOnNode(type, ts.Diagnostics.Type_annotation_cannot_appear_on_a_constructor_declaration);
79766             }
79767         }
79768         function checkGrammarProperty(node) {
79769             if (ts.isClassLike(node.parent)) {
79770                 if (ts.isStringLiteral(node.name) && node.name.text === "constructor") {
79771                     return grammarErrorOnNode(node.name, ts.Diagnostics.Classes_may_not_have_a_field_named_constructor);
79772                 }
79773                 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)) {
79774                     return true;
79775                 }
79776                 if (languageVersion < 2 /* ES2015 */ && ts.isPrivateIdentifier(node.name)) {
79777                     return grammarErrorOnNode(node.name, ts.Diagnostics.Private_identifiers_are_only_available_when_targeting_ECMAScript_2015_and_higher);
79778                 }
79779             }
79780             else if (node.parent.kind === 253 /* InterfaceDeclaration */) {
79781                 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)) {
79782                     return true;
79783                 }
79784                 if (node.initializer) {
79785                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.An_interface_property_cannot_have_an_initializer);
79786                 }
79787             }
79788             else if (node.parent.kind === 177 /* TypeLiteral */) {
79789                 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)) {
79790                     return true;
79791                 }
79792                 if (node.initializer) {
79793                     return grammarErrorOnNode(node.initializer, ts.Diagnostics.A_type_literal_property_cannot_have_an_initializer);
79794                 }
79795             }
79796             if (node.flags & 8388608 /* Ambient */) {
79797                 checkAmbientInitializer(node);
79798             }
79799             if (ts.isPropertyDeclaration(node) && node.exclamationToken && (!ts.isClassLike(node.parent) || !node.type || node.initializer ||
79800                 node.flags & 8388608 /* Ambient */ || ts.hasSyntacticModifier(node, 32 /* Static */ | 128 /* Abstract */))) {
79801                 var message = node.initializer
79802                     ? ts.Diagnostics.Declarations_with_initializers_cannot_also_have_definite_assignment_assertions
79803                     : !node.type
79804                         ? ts.Diagnostics.Declarations_with_definite_assignment_assertions_must_also_have_type_annotations
79805                         : ts.Diagnostics.A_definite_assignment_assertion_is_not_permitted_in_this_context;
79806                 return grammarErrorOnNode(node.exclamationToken, message);
79807             }
79808         }
79809         function checkGrammarTopLevelElementForRequiredDeclareModifier(node) {
79810             // A declare modifier is required for any top level .d.ts declaration except export=, export default, export as namespace
79811             // interfaces and imports categories:
79812             //
79813             //  DeclarationElement:
79814             //     ExportAssignment
79815             //     export_opt   InterfaceDeclaration
79816             //     export_opt   TypeAliasDeclaration
79817             //     export_opt   ImportDeclaration
79818             //     export_opt   ExternalImportDeclaration
79819             //     export_opt   AmbientDeclaration
79820             //
79821             // TODO: The spec needs to be amended to reflect this grammar.
79822             if (node.kind === 253 /* InterfaceDeclaration */ ||
79823                 node.kind === 254 /* TypeAliasDeclaration */ ||
79824                 node.kind === 261 /* ImportDeclaration */ ||
79825                 node.kind === 260 /* ImportEqualsDeclaration */ ||
79826                 node.kind === 267 /* ExportDeclaration */ ||
79827                 node.kind === 266 /* ExportAssignment */ ||
79828                 node.kind === 259 /* NamespaceExportDeclaration */ ||
79829                 ts.hasSyntacticModifier(node, 2 /* Ambient */ | 1 /* Export */ | 512 /* Default */)) {
79830                 return false;
79831             }
79832             return grammarErrorOnFirstToken(node, ts.Diagnostics.Top_level_declarations_in_d_ts_files_must_start_with_either_a_declare_or_export_modifier);
79833         }
79834         function checkGrammarTopLevelElementsForRequiredDeclareModifier(file) {
79835             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
79836                 var decl = _a[_i];
79837                 if (ts.isDeclaration(decl) || decl.kind === 232 /* VariableStatement */) {
79838                     if (checkGrammarTopLevelElementForRequiredDeclareModifier(decl)) {
79839                         return true;
79840                     }
79841                 }
79842             }
79843             return false;
79844         }
79845         function checkGrammarSourceFile(node) {
79846             return !!(node.flags & 8388608 /* Ambient */) && checkGrammarTopLevelElementsForRequiredDeclareModifier(node);
79847         }
79848         function checkGrammarStatementInAmbientContext(node) {
79849             if (node.flags & 8388608 /* Ambient */) {
79850                 // Find containing block which is either Block, ModuleBlock, SourceFile
79851                 var links = getNodeLinks(node);
79852                 if (!links.hasReportedStatementInAmbientContext && (ts.isFunctionLike(node.parent) || ts.isAccessor(node.parent))) {
79853                     return getNodeLinks(node).hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.An_implementation_cannot_be_declared_in_ambient_contexts);
79854                 }
79855                 // We are either parented by another statement, or some sort of block.
79856                 // If we're in a block, we only want to really report an error once
79857                 // to prevent noisiness.  So use a bit on the block to indicate if
79858                 // this has already been reported, and don't report if it has.
79859                 //
79860                 if (node.parent.kind === 230 /* Block */ || node.parent.kind === 257 /* ModuleBlock */ || node.parent.kind === 297 /* SourceFile */) {
79861                     var links_2 = getNodeLinks(node.parent);
79862                     // Check if the containing block ever report this error
79863                     if (!links_2.hasReportedStatementInAmbientContext) {
79864                         return links_2.hasReportedStatementInAmbientContext = grammarErrorOnFirstToken(node, ts.Diagnostics.Statements_are_not_allowed_in_ambient_contexts);
79865                     }
79866                 }
79867                 else {
79868                     // We must be parented by a statement.  If so, there's no need
79869                     // to report the error as our parent will have already done it.
79870                     // Debug.assert(isStatement(node.parent));
79871                 }
79872             }
79873             return false;
79874         }
79875         function checkGrammarNumericLiteral(node) {
79876             // Grammar checking
79877             if (node.numericLiteralFlags & 32 /* Octal */) {
79878                 var diagnosticMessage = void 0;
79879                 if (languageVersion >= 1 /* ES5 */) {
79880                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_available_when_targeting_ECMAScript_5_and_higher_Use_the_syntax_0;
79881                 }
79882                 else if (ts.isChildOfNodeWithKind(node, 191 /* LiteralType */)) {
79883                     diagnosticMessage = ts.Diagnostics.Octal_literal_types_must_use_ES2015_syntax_Use_the_syntax_0;
79884                 }
79885                 else if (ts.isChildOfNodeWithKind(node, 291 /* EnumMember */)) {
79886                     diagnosticMessage = ts.Diagnostics.Octal_literals_are_not_allowed_in_enums_members_initializer_Use_the_syntax_0;
79887                 }
79888                 if (diagnosticMessage) {
79889                     var withMinus = ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === 40 /* MinusToken */;
79890                     var literal = (withMinus ? "-" : "") + "0o" + node.text;
79891                     return grammarErrorOnNode(withMinus ? node.parent : node, diagnosticMessage, literal);
79892                 }
79893             }
79894             // Realism (size) checking
79895             checkNumericLiteralValueSize(node);
79896             return false;
79897         }
79898         function checkNumericLiteralValueSize(node) {
79899             // Scientific notation (e.g. 2e54 and 1e00000000010) can't be converted to bigint
79900             // Literals with 15 or fewer characters aren't long enough to reach past 2^53 - 1
79901             // Fractional numbers (e.g. 9000000000000000.001) are inherently imprecise anyway
79902             if (node.numericLiteralFlags & 16 /* Scientific */ || node.text.length <= 15 || node.text.indexOf(".") !== -1) {
79903                 return;
79904             }
79905             // We can't rely on the runtime to accurately store and compare extremely large numeric values
79906             // Even for internal use, we use getTextOfNode: https://github.com/microsoft/TypeScript/issues/33298
79907             // Thus, if the runtime claims a too-large number is lower than Number.MAX_SAFE_INTEGER,
79908             // it's likely addition operations on it will fail too
79909             var apparentValue = +ts.getTextOfNode(node);
79910             if (apparentValue <= Math.pow(2, 53) - 1 && apparentValue + 1 > apparentValue) {
79911                 return;
79912             }
79913             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));
79914         }
79915         function checkGrammarBigIntLiteral(node) {
79916             var literalType = ts.isLiteralTypeNode(node.parent) ||
79917                 ts.isPrefixUnaryExpression(node.parent) && ts.isLiteralTypeNode(node.parent.parent);
79918             if (!literalType) {
79919                 if (languageVersion < 7 /* ES2020 */) {
79920                     if (grammarErrorOnNode(node, ts.Diagnostics.BigInt_literals_are_not_available_when_targeting_lower_than_ES2020)) {
79921                         return true;
79922                     }
79923                 }
79924             }
79925             return false;
79926         }
79927         function grammarErrorAfterFirstToken(node, message, arg0, arg1, arg2) {
79928             var sourceFile = ts.getSourceFileOfNode(node);
79929             if (!hasParseDiagnostics(sourceFile)) {
79930                 var span = ts.getSpanOfTokenAtPosition(sourceFile, node.pos);
79931                 diagnostics.add(ts.createFileDiagnostic(sourceFile, ts.textSpanEnd(span), /*length*/ 0, message, arg0, arg1, arg2));
79932                 return true;
79933             }
79934             return false;
79935         }
79936         function getAmbientModules() {
79937             if (!ambientModulesCache) {
79938                 ambientModulesCache = [];
79939                 globals.forEach(function (global, sym) {
79940                     // No need to `unescapeLeadingUnderscores`, an escaped symbol is never an ambient module.
79941                     if (ambientModuleSymbolRegex.test(sym)) {
79942                         ambientModulesCache.push(global);
79943                     }
79944                 });
79945             }
79946             return ambientModulesCache;
79947         }
79948         function checkGrammarImportClause(node) {
79949             if (node.isTypeOnly && node.name && node.namedBindings) {
79950                 return grammarErrorOnNode(node, ts.Diagnostics.A_type_only_import_can_specify_a_default_import_or_named_bindings_but_not_both);
79951             }
79952             return false;
79953         }
79954         function checkGrammarImportCallExpression(node) {
79955             if (moduleKind === ts.ModuleKind.ES2015) {
79956                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_imports_are_only_supported_when_the_module_flag_is_set_to_es2020_esnext_commonjs_amd_system_or_umd);
79957             }
79958             if (node.typeArguments) {
79959                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_cannot_have_type_arguments);
79960             }
79961             var nodeArguments = node.arguments;
79962             if (nodeArguments.length !== 1) {
79963                 return grammarErrorOnNode(node, ts.Diagnostics.Dynamic_import_must_have_one_specifier_as_an_argument);
79964             }
79965             checkGrammarForDisallowedTrailingComma(nodeArguments);
79966             // see: parseArgumentOrArrayLiteralElement...we use this function which parse arguments of callExpression to parse specifier for dynamic import.
79967             // parseArgumentOrArrayLiteralElement allows spread element to be in an argument list which is not allowed as specifier in dynamic import.
79968             if (ts.isSpreadElement(nodeArguments[0])) {
79969                 return grammarErrorOnNode(nodeArguments[0], ts.Diagnostics.Specifier_of_dynamic_import_cannot_be_spread_element);
79970             }
79971             return false;
79972         }
79973         function findMatchingTypeReferenceOrTypeAliasReference(source, unionTarget) {
79974             var sourceObjectFlags = ts.getObjectFlags(source);
79975             if (sourceObjectFlags & (4 /* Reference */ | 16 /* Anonymous */) && unionTarget.flags & 1048576 /* Union */) {
79976                 return ts.find(unionTarget.types, function (target) {
79977                     if (target.flags & 524288 /* Object */) {
79978                         var overlapObjFlags = sourceObjectFlags & ts.getObjectFlags(target);
79979                         if (overlapObjFlags & 4 /* Reference */) {
79980                             return source.target === target.target;
79981                         }
79982                         if (overlapObjFlags & 16 /* Anonymous */) {
79983                             return !!source.aliasSymbol && source.aliasSymbol === target.aliasSymbol;
79984                         }
79985                     }
79986                     return false;
79987                 });
79988             }
79989         }
79990         function findBestTypeForObjectLiteral(source, unionTarget) {
79991             if (ts.getObjectFlags(source) & 128 /* ObjectLiteral */ && forEachType(unionTarget, isArrayLikeType)) {
79992                 return ts.find(unionTarget.types, function (t) { return !isArrayLikeType(t); });
79993             }
79994         }
79995         function findBestTypeForInvokable(source, unionTarget) {
79996             var signatureKind = 0 /* Call */;
79997             var hasSignatures = getSignaturesOfType(source, signatureKind).length > 0 ||
79998                 (signatureKind = 1 /* Construct */, getSignaturesOfType(source, signatureKind).length > 0);
79999             if (hasSignatures) {
80000                 return ts.find(unionTarget.types, function (t) { return getSignaturesOfType(t, signatureKind).length > 0; });
80001             }
80002         }
80003         function findMostOverlappyType(source, unionTarget) {
80004             var bestMatch;
80005             var matchingCount = 0;
80006             for (var _i = 0, _a = unionTarget.types; _i < _a.length; _i++) {
80007                 var target = _a[_i];
80008                 var overlap = getIntersectionType([getIndexType(source), getIndexType(target)]);
80009                 if (overlap.flags & 4194304 /* Index */) {
80010                     // perfect overlap of keys
80011                     bestMatch = target;
80012                     matchingCount = Infinity;
80013                 }
80014                 else if (overlap.flags & 1048576 /* Union */) {
80015                     // We only want to account for literal types otherwise.
80016                     // If we have a union of index types, it seems likely that we
80017                     // needed to elaborate between two generic mapped types anyway.
80018                     var len = ts.length(ts.filter(overlap.types, isUnitType));
80019                     if (len >= matchingCount) {
80020                         bestMatch = target;
80021                         matchingCount = len;
80022                     }
80023                 }
80024                 else if (isUnitType(overlap) && 1 >= matchingCount) {
80025                     bestMatch = target;
80026                     matchingCount = 1;
80027                 }
80028             }
80029             return bestMatch;
80030         }
80031         function filterPrimitivesIfContainsNonPrimitive(type) {
80032             if (maybeTypeOfKind(type, 67108864 /* NonPrimitive */)) {
80033                 var result = filterType(type, function (t) { return !(t.flags & 131068 /* Primitive */); });
80034                 if (!(result.flags & 131072 /* Never */)) {
80035                     return result;
80036                 }
80037             }
80038             return type;
80039         }
80040         // Keep this up-to-date with the same logic within `getApparentTypeOfContextualType`, since they should behave similarly
80041         function findMatchingDiscriminantType(source, target, isRelatedTo, skipPartial) {
80042             if (target.flags & 1048576 /* Union */ && source.flags & (2097152 /* Intersection */ | 524288 /* Object */)) {
80043                 var sourceProperties = getPropertiesOfType(source);
80044                 if (sourceProperties) {
80045                     var sourcePropertiesFiltered = findDiscriminantProperties(sourceProperties, target);
80046                     if (sourcePropertiesFiltered) {
80047                         return discriminateTypeByDiscriminableItems(target, ts.map(sourcePropertiesFiltered, function (p) { return [function () { return getTypeOfSymbol(p); }, p.escapedName]; }), isRelatedTo, /*defaultValue*/ undefined, skipPartial);
80048                     }
80049                 }
80050             }
80051             return undefined;
80052         }
80053     }
80054     ts.createTypeChecker = createTypeChecker;
80055     function isNotAccessor(declaration) {
80056         // Accessors check for their own matching duplicates, and in contexts where they are valid, there are already duplicate identifier checks
80057         return !ts.isAccessor(declaration);
80058     }
80059     function isNotOverload(declaration) {
80060         return (declaration.kind !== 251 /* FunctionDeclaration */ && declaration.kind !== 165 /* MethodDeclaration */) ||
80061             !!declaration.body;
80062     }
80063     /** Like 'isDeclarationName', but returns true for LHS of `import { x as y }` or `export { x as y }`. */
80064     function isDeclarationNameOrImportPropertyName(name) {
80065         switch (name.parent.kind) {
80066             case 265 /* ImportSpecifier */:
80067             case 270 /* ExportSpecifier */:
80068                 return ts.isIdentifier(name);
80069             default:
80070                 return ts.isDeclarationName(name);
80071         }
80072     }
80073     function isSomeImportDeclaration(decl) {
80074         switch (decl.kind) {
80075             case 262 /* ImportClause */: // For default import
80076             case 260 /* ImportEqualsDeclaration */:
80077             case 263 /* NamespaceImport */:
80078             case 265 /* ImportSpecifier */: // For rename import `x as y`
80079                 return true;
80080             case 78 /* Identifier */:
80081                 // For regular import, `decl` is an Identifier under the ImportSpecifier.
80082                 return decl.parent.kind === 265 /* ImportSpecifier */;
80083             default:
80084                 return false;
80085         }
80086     }
80087     var JsxNames;
80088     (function (JsxNames) {
80089         JsxNames.JSX = "JSX";
80090         JsxNames.IntrinsicElements = "IntrinsicElements";
80091         JsxNames.ElementClass = "ElementClass";
80092         JsxNames.ElementAttributesPropertyNameContainer = "ElementAttributesProperty"; // TODO: Deprecate and remove support
80093         JsxNames.ElementChildrenAttributeNameContainer = "ElementChildrenAttribute";
80094         JsxNames.Element = "Element";
80095         JsxNames.IntrinsicAttributes = "IntrinsicAttributes";
80096         JsxNames.IntrinsicClassAttributes = "IntrinsicClassAttributes";
80097         JsxNames.LibraryManagedAttributes = "LibraryManagedAttributes";
80098     })(JsxNames || (JsxNames = {}));
80099     function getIterationTypesKeyFromIterationTypeKind(typeKind) {
80100         switch (typeKind) {
80101             case 0 /* Yield */: return "yieldType";
80102             case 1 /* Return */: return "returnType";
80103             case 2 /* Next */: return "nextType";
80104         }
80105     }
80106     function signatureHasRestParameter(s) {
80107         return !!(s.flags & 1 /* HasRestParameter */);
80108     }
80109     ts.signatureHasRestParameter = signatureHasRestParameter;
80110     function signatureHasLiteralTypes(s) {
80111         return !!(s.flags & 2 /* HasLiteralTypes */);
80112     }
80113     ts.signatureHasLiteralTypes = signatureHasLiteralTypes;
80114 })(ts || (ts = {}));
80115 var ts;
80116 (function (ts) {
80117     var isTypeNodeOrTypeParameterDeclaration = ts.or(ts.isTypeNode, ts.isTypeParameterDeclaration);
80118     function visitNode(node, visitor, test, lift) {
80119         if (node === undefined || visitor === undefined) {
80120             return node;
80121         }
80122         var visited = visitor(node);
80123         if (visited === node) {
80124             return node;
80125         }
80126         var visitedNode;
80127         if (visited === undefined) {
80128             return undefined;
80129         }
80130         else if (ts.isArray(visited)) {
80131             visitedNode = (lift || extractSingleNode)(visited);
80132         }
80133         else {
80134             visitedNode = visited;
80135         }
80136         ts.Debug.assertNode(visitedNode, test);
80137         return visitedNode;
80138     }
80139     ts.visitNode = visitNode;
80140     /**
80141      * Visits a NodeArray using the supplied visitor, possibly returning a new NodeArray in its place.
80142      *
80143      * @param nodes The NodeArray to visit.
80144      * @param visitor The callback used to visit a Node.
80145      * @param test A node test to execute for each node.
80146      * @param start An optional value indicating the starting offset at which to start visiting.
80147      * @param count An optional value indicating the maximum number of nodes to visit.
80148      */
80149     function visitNodes(nodes, visitor, test, start, count) {
80150         if (nodes === undefined || visitor === undefined) {
80151             return nodes;
80152         }
80153         var updated;
80154         // Ensure start and count have valid values
80155         var length = nodes.length;
80156         if (start === undefined || start < 0) {
80157             start = 0;
80158         }
80159         if (count === undefined || count > length - start) {
80160             count = length - start;
80161         }
80162         var hasTrailingComma;
80163         var pos = -1;
80164         var end = -1;
80165         if (start > 0 || count < length) {
80166             // If we are not visiting all of the original nodes, we must always create a new array.
80167             // Since this is a fragment of a node array, we do not copy over the previous location
80168             // and will only copy over `hasTrailingComma` if we are including the last element.
80169             updated = [];
80170             hasTrailingComma = nodes.hasTrailingComma && start + count === length;
80171         }
80172         // Visit each original node.
80173         for (var i = 0; i < count; i++) {
80174             var node = nodes[i + start];
80175             var visited = node !== undefined ? visitor(node) : undefined;
80176             if (updated !== undefined || visited === undefined || visited !== node) {
80177                 if (updated === undefined) {
80178                     // Ensure we have a copy of `nodes`, up to the current index.
80179                     updated = nodes.slice(0, i);
80180                     hasTrailingComma = nodes.hasTrailingComma;
80181                     pos = nodes.pos;
80182                     end = nodes.end;
80183                 }
80184                 if (visited) {
80185                     if (ts.isArray(visited)) {
80186                         for (var _i = 0, visited_1 = visited; _i < visited_1.length; _i++) {
80187                             var visitedNode = visited_1[_i];
80188                             void ts.Debug.assertNode(visitedNode, test);
80189                             updated.push(visitedNode);
80190                         }
80191                     }
80192                     else {
80193                         void ts.Debug.assertNode(visited, test);
80194                         updated.push(visited);
80195                     }
80196                 }
80197             }
80198         }
80199         if (updated) {
80200             // TODO(rbuckton): Remove dependency on `ts.factory` in favor of a provided factory.
80201             var updatedArray = ts.factory.createNodeArray(updated, hasTrailingComma);
80202             ts.setTextRangePosEnd(updatedArray, pos, end);
80203             return updatedArray;
80204         }
80205         return nodes;
80206     }
80207     ts.visitNodes = visitNodes;
80208     /**
80209      * Starts a new lexical environment and visits a statement list, ending the lexical environment
80210      * and merging hoisted declarations upon completion.
80211      */
80212     function visitLexicalEnvironment(statements, visitor, context, start, ensureUseStrict, nodesVisitor) {
80213         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
80214         context.startLexicalEnvironment();
80215         statements = nodesVisitor(statements, visitor, ts.isStatement, start);
80216         if (ensureUseStrict)
80217             statements = context.factory.ensureUseStrict(statements);
80218         return ts.factory.mergeLexicalEnvironment(statements, context.endLexicalEnvironment());
80219     }
80220     ts.visitLexicalEnvironment = visitLexicalEnvironment;
80221     function visitParameterList(nodes, visitor, context, nodesVisitor) {
80222         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
80223         var updated;
80224         context.startLexicalEnvironment();
80225         if (nodes) {
80226             context.setLexicalEnvironmentFlags(1 /* InParameters */, true);
80227             updated = nodesVisitor(nodes, visitor, ts.isParameterDeclaration);
80228             // As of ES2015, any runtime execution of that occurs in for a parameter (such as evaluating an
80229             // initializer or a binding pattern), occurs in its own lexical scope. As a result, any expression
80230             // that we might transform that introduces a temporary variable would fail as the temporary variable
80231             // exists in a different lexical scope. To address this, we move any binding patterns and initializers
80232             // in a parameter list to the body if we detect a variable being hoisted while visiting a parameter list
80233             // when the emit target is greater than ES2015.
80234             if (context.getLexicalEnvironmentFlags() & 2 /* VariablesHoistedInParameters */ &&
80235                 ts.getEmitScriptTarget(context.getCompilerOptions()) >= 2 /* ES2015 */) {
80236                 updated = addDefaultValueAssignmentsIfNeeded(updated, context);
80237             }
80238             context.setLexicalEnvironmentFlags(1 /* InParameters */, false);
80239         }
80240         context.suspendLexicalEnvironment();
80241         return updated;
80242     }
80243     ts.visitParameterList = visitParameterList;
80244     function addDefaultValueAssignmentsIfNeeded(parameters, context) {
80245         var result;
80246         for (var i = 0; i < parameters.length; i++) {
80247             var parameter = parameters[i];
80248             var updated = addDefaultValueAssignmentIfNeeded(parameter, context);
80249             if (result || updated !== parameter) {
80250                 if (!result)
80251                     result = parameters.slice(0, i);
80252                 result[i] = updated;
80253             }
80254         }
80255         if (result) {
80256             return ts.setTextRange(context.factory.createNodeArray(result, parameters.hasTrailingComma), parameters);
80257         }
80258         return parameters;
80259     }
80260     function addDefaultValueAssignmentIfNeeded(parameter, context) {
80261         // A rest parameter cannot have a binding pattern or an initializer,
80262         // so let's just ignore it.
80263         return parameter.dotDotDotToken ? parameter :
80264             ts.isBindingPattern(parameter.name) ? addDefaultValueAssignmentForBindingPattern(parameter, context) :
80265                 parameter.initializer ? addDefaultValueAssignmentForInitializer(parameter, parameter.name, parameter.initializer, context) :
80266                     parameter;
80267     }
80268     function addDefaultValueAssignmentForBindingPattern(parameter, context) {
80269         var factory = context.factory;
80270         context.addInitializationStatement(factory.createVariableStatement(
80271         /*modifiers*/ undefined, factory.createVariableDeclarationList([
80272             factory.createVariableDeclaration(parameter.name, 
80273             /*exclamationToken*/ undefined, parameter.type, parameter.initializer ?
80274                 factory.createConditionalExpression(factory.createStrictEquality(factory.getGeneratedNameForNode(parameter), factory.createVoidZero()), 
80275                 /*questionToken*/ undefined, parameter.initializer, 
80276                 /*colonToken*/ undefined, factory.getGeneratedNameForNode(parameter)) :
80277                 factory.getGeneratedNameForNode(parameter)),
80278         ])));
80279         return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, factory.getGeneratedNameForNode(parameter), parameter.questionToken, parameter.type, 
80280         /*initializer*/ undefined);
80281     }
80282     function addDefaultValueAssignmentForInitializer(parameter, name, initializer, context) {
80283         var factory = context.factory;
80284         context.addInitializationStatement(factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
80285             factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(ts.setEmitFlags(factory.cloneNode(name), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
80286         ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */)));
80287         return factory.updateParameterDeclaration(parameter, parameter.decorators, parameter.modifiers, parameter.dotDotDotToken, parameter.name, parameter.questionToken, parameter.type, 
80288         /*initializer*/ undefined);
80289     }
80290     function visitFunctionBody(node, visitor, context, nodeVisitor) {
80291         if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
80292         context.resumeLexicalEnvironment();
80293         var updated = nodeVisitor(node, visitor, ts.isConciseBody);
80294         var declarations = context.endLexicalEnvironment();
80295         if (ts.some(declarations)) {
80296             if (!updated) {
80297                 return context.factory.createBlock(declarations);
80298             }
80299             var block = context.factory.converters.convertToFunctionBlock(updated);
80300             var statements = ts.factory.mergeLexicalEnvironment(block.statements, declarations);
80301             return context.factory.updateBlock(block, statements);
80302         }
80303         return updated;
80304     }
80305     ts.visitFunctionBody = visitFunctionBody;
80306     function visitEachChild(node, visitor, context, nodesVisitor, tokenVisitor, nodeVisitor) {
80307         if (nodesVisitor === void 0) { nodesVisitor = visitNodes; }
80308         if (nodeVisitor === void 0) { nodeVisitor = visitNode; }
80309         if (node === undefined) {
80310             return undefined;
80311         }
80312         var kind = node.kind;
80313         // No need to visit nodes with no children.
80314         if ((kind > 0 /* FirstToken */ && kind <= 156 /* LastToken */) || kind === 187 /* ThisType */) {
80315             return node;
80316         }
80317         var factory = context.factory;
80318         switch (kind) {
80319             // Names
80320             case 78 /* Identifier */:
80321                 return factory.updateIdentifier(node, nodesVisitor(node.typeArguments, visitor, isTypeNodeOrTypeParameterDeclaration));
80322             case 157 /* QualifiedName */:
80323                 return factory.updateQualifiedName(node, nodeVisitor(node.left, visitor, ts.isEntityName), nodeVisitor(node.right, visitor, ts.isIdentifier));
80324             case 158 /* ComputedPropertyName */:
80325                 return factory.updateComputedPropertyName(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80326             // Signature elements
80327             case 159 /* TypeParameter */:
80328                 return factory.updateTypeParameterDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.constraint, visitor, ts.isTypeNode), nodeVisitor(node.default, visitor, ts.isTypeNode));
80329             case 160 /* Parameter */:
80330                 return factory.updateParameterDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
80331             case 161 /* Decorator */:
80332                 return factory.updateDecorator(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80333             // Type elements
80334             case 162 /* PropertySignature */:
80335                 return factory.updatePropertySignature(node, nodesVisitor(node.modifiers, visitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode));
80336             case 163 /* PropertyDeclaration */:
80337                 return factory.updatePropertyDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), 
80338                 // QuestionToken and ExclamationToken is uniqued in Property Declaration and the signature of 'updateProperty' is that too
80339                 nodeVisitor(node.questionToken || node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
80340             case 164 /* MethodSignature */:
80341                 return factory.updateMethodSignature(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80342             case 165 /* MethodDeclaration */:
80343                 return factory.updateMethodDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80344             case 166 /* Constructor */:
80345                 return factory.updateConstructorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80346             case 167 /* GetAccessor */:
80347                 return factory.updateGetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80348             case 168 /* SetAccessor */:
80349                 return factory.updateSetAccessorDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isPropertyName), visitParameterList(node.parameters, visitor, context, nodesVisitor), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80350             case 169 /* CallSignature */:
80351                 return factory.updateCallSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80352             case 170 /* ConstructSignature */:
80353                 return factory.updateConstructSignature(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80354             case 171 /* IndexSignature */:
80355                 return factory.updateIndexSignature(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80356             // Types
80357             case 172 /* TypePredicate */:
80358                 return factory.updateTypePredicateNode(node, nodeVisitor(node.assertsModifier, visitor), nodeVisitor(node.parameterName, visitor), nodeVisitor(node.type, visitor, ts.isTypeNode));
80359             case 173 /* TypeReference */:
80360                 return factory.updateTypeReferenceNode(node, nodeVisitor(node.typeName, visitor, ts.isEntityName), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
80361             case 174 /* FunctionType */:
80362                 return factory.updateFunctionTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80363             case 175 /* ConstructorType */:
80364                 return factory.updateConstructorTypeNode(node, nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.parameters, visitor, ts.isParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80365             case 176 /* TypeQuery */:
80366                 return factory.updateTypeQueryNode(node, nodeVisitor(node.exprName, visitor, ts.isEntityName));
80367             case 177 /* TypeLiteral */:
80368                 return factory.updateTypeLiteralNode(node, nodesVisitor(node.members, visitor, ts.isTypeElement));
80369             case 178 /* ArrayType */:
80370                 return factory.updateArrayTypeNode(node, nodeVisitor(node.elementType, visitor, ts.isTypeNode));
80371             case 179 /* TupleType */:
80372                 return factory.updateTupleTypeNode(node, nodesVisitor(node.elements, visitor, ts.isTypeNode));
80373             case 180 /* OptionalType */:
80374                 return factory.updateOptionalTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
80375             case 181 /* RestType */:
80376                 return factory.updateRestTypeNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
80377             case 182 /* UnionType */:
80378                 return factory.updateUnionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
80379             case 183 /* IntersectionType */:
80380                 return factory.updateIntersectionTypeNode(node, nodesVisitor(node.types, visitor, ts.isTypeNode));
80381             case 184 /* ConditionalType */:
80382                 return factory.updateConditionalTypeNode(node, nodeVisitor(node.checkType, visitor, ts.isTypeNode), nodeVisitor(node.extendsType, visitor, ts.isTypeNode), nodeVisitor(node.trueType, visitor, ts.isTypeNode), nodeVisitor(node.falseType, visitor, ts.isTypeNode));
80383             case 185 /* InferType */:
80384                 return factory.updateInferTypeNode(node, nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration));
80385             case 195 /* ImportType */:
80386                 return factory.updateImportTypeNode(node, nodeVisitor(node.argument, visitor, ts.isTypeNode), nodeVisitor(node.qualifier, visitor, ts.isEntityName), visitNodes(node.typeArguments, visitor, ts.isTypeNode), node.isTypeOf);
80387             case 192 /* NamedTupleMember */:
80388                 return factory.updateNamedTupleMember(node, visitNode(node.dotDotDotToken, visitor, ts.isToken), visitNode(node.name, visitor, ts.isIdentifier), visitNode(node.questionToken, visitor, ts.isToken), visitNode(node.type, visitor, ts.isTypeNode));
80389             case 186 /* ParenthesizedType */:
80390                 return factory.updateParenthesizedType(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
80391             case 188 /* TypeOperator */:
80392                 return factory.updateTypeOperatorNode(node, nodeVisitor(node.type, visitor, ts.isTypeNode));
80393             case 189 /* IndexedAccessType */:
80394                 return factory.updateIndexedAccessTypeNode(node, nodeVisitor(node.objectType, visitor, ts.isTypeNode), nodeVisitor(node.indexType, visitor, ts.isTypeNode));
80395             case 190 /* MappedType */:
80396                 return factory.updateMappedTypeNode(node, nodeVisitor(node.readonlyToken, tokenVisitor, ts.isToken), nodeVisitor(node.typeParameter, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.nameType, visitor, ts.isTypeNode), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode));
80397             case 191 /* LiteralType */:
80398                 return factory.updateLiteralTypeNode(node, nodeVisitor(node.literal, visitor, ts.isExpression));
80399             case 193 /* TemplateLiteralType */:
80400                 return factory.updateTemplateLiteralType(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateLiteralTypeSpan));
80401             case 194 /* TemplateLiteralTypeSpan */:
80402                 return factory.updateTemplateLiteralTypeSpan(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
80403             // Binding patterns
80404             case 196 /* ObjectBindingPattern */:
80405                 return factory.updateObjectBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isBindingElement));
80406             case 197 /* ArrayBindingPattern */:
80407                 return factory.updateArrayBindingPattern(node, nodesVisitor(node.elements, visitor, ts.isArrayBindingElement));
80408             case 198 /* BindingElement */:
80409                 return factory.updateBindingElement(node, nodeVisitor(node.dotDotDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.propertyName, visitor, ts.isPropertyName), nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.initializer, visitor, ts.isExpression));
80410             // Expression
80411             case 199 /* ArrayLiteralExpression */:
80412                 return factory.updateArrayLiteralExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
80413             case 200 /* ObjectLiteralExpression */:
80414                 return factory.updateObjectLiteralExpression(node, nodesVisitor(node.properties, visitor, ts.isObjectLiteralElementLike));
80415             case 201 /* PropertyAccessExpression */:
80416                 if (node.flags & 32 /* OptionalChain */) {
80417                     return factory.updatePropertyAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier));
80418                 }
80419                 return factory.updatePropertyAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.name, visitor, ts.isIdentifierOrPrivateIdentifier));
80420             case 202 /* ElementAccessExpression */:
80421                 if (node.flags & 32 /* OptionalChain */) {
80422                     return factory.updateElementAccessChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
80423                 }
80424                 return factory.updateElementAccessExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.argumentExpression, visitor, ts.isExpression));
80425             case 203 /* CallExpression */:
80426                 if (node.flags & 32 /* OptionalChain */) {
80427                     return factory.updateCallChain(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.questionDotToken, tokenVisitor, ts.isToken), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
80428                 }
80429                 return factory.updateCallExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
80430             case 204 /* NewExpression */:
80431                 return factory.updateNewExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodesVisitor(node.arguments, visitor, ts.isExpression));
80432             case 205 /* TaggedTemplateExpression */:
80433                 return factory.updateTaggedTemplateExpression(node, nodeVisitor(node.tag, visitor, ts.isExpression), visitNodes(node.typeArguments, visitor, ts.isExpression), nodeVisitor(node.template, visitor, ts.isTemplateLiteral));
80434             case 206 /* TypeAssertionExpression */:
80435                 return factory.updateTypeAssertion(node, nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.expression, visitor, ts.isExpression));
80436             case 207 /* ParenthesizedExpression */:
80437                 return factory.updateParenthesizedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80438             case 208 /* FunctionExpression */:
80439                 return factory.updateFunctionExpression(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80440             case 209 /* ArrowFunction */:
80441                 return factory.updateArrowFunction(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.equalsGreaterThanToken, tokenVisitor, ts.isToken), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80442             case 210 /* DeleteExpression */:
80443                 return factory.updateDeleteExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80444             case 211 /* TypeOfExpression */:
80445                 return factory.updateTypeOfExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80446             case 212 /* VoidExpression */:
80447                 return factory.updateVoidExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80448             case 213 /* AwaitExpression */:
80449                 return factory.updateAwaitExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80450             case 214 /* PrefixUnaryExpression */:
80451                 return factory.updatePrefixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
80452             case 215 /* PostfixUnaryExpression */:
80453                 return factory.updatePostfixUnaryExpression(node, nodeVisitor(node.operand, visitor, ts.isExpression));
80454             case 216 /* BinaryExpression */:
80455                 return factory.updateBinaryExpression(node, nodeVisitor(node.left, visitor, ts.isExpression), nodeVisitor(node.operatorToken, tokenVisitor, ts.isToken), nodeVisitor(node.right, visitor, ts.isExpression));
80456             case 217 /* ConditionalExpression */:
80457                 return factory.updateConditionalExpression(node, nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.questionToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenTrue, visitor, ts.isExpression), nodeVisitor(node.colonToken, tokenVisitor, ts.isToken), nodeVisitor(node.whenFalse, visitor, ts.isExpression));
80458             case 218 /* TemplateExpression */:
80459                 return factory.updateTemplateExpression(node, nodeVisitor(node.head, visitor, ts.isTemplateHead), nodesVisitor(node.templateSpans, visitor, ts.isTemplateSpan));
80460             case 219 /* YieldExpression */:
80461                 return factory.updateYieldExpression(node, nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.expression, visitor, ts.isExpression));
80462             case 220 /* SpreadElement */:
80463                 return factory.updateSpreadElement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80464             case 221 /* ClassExpression */:
80465                 return factory.updateClassExpression(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
80466             case 223 /* ExpressionWithTypeArguments */:
80467                 return factory.updateExpressionWithTypeArguments(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode));
80468             case 224 /* AsExpression */:
80469                 return factory.updateAsExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.type, visitor, ts.isTypeNode));
80470             case 225 /* NonNullExpression */:
80471                 if (node.flags & 32 /* OptionalChain */) {
80472                     return factory.updateNonNullChain(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80473                 }
80474                 return factory.updateNonNullExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80475             case 226 /* MetaProperty */:
80476                 return factory.updateMetaProperty(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
80477             // Misc
80478             case 228 /* TemplateSpan */:
80479                 return factory.updateTemplateSpan(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.literal, visitor, ts.isTemplateMiddleOrTemplateTail));
80480             // Element
80481             case 230 /* Block */:
80482                 return factory.updateBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
80483             case 232 /* VariableStatement */:
80484                 return factory.updateVariableStatement(node, nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.declarationList, visitor, ts.isVariableDeclarationList));
80485             case 233 /* ExpressionStatement */:
80486                 return factory.updateExpressionStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80487             case 234 /* IfStatement */:
80488                 return factory.updateIfStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.thenStatement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.elseStatement, visitor, ts.isStatement, factory.liftToBlock));
80489             case 235 /* DoStatement */:
80490                 return factory.updateDoStatement(node, nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock), nodeVisitor(node.expression, visitor, ts.isExpression));
80491             case 236 /* WhileStatement */:
80492                 return factory.updateWhileStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80493             case 237 /* ForStatement */:
80494                 return factory.updateForStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.condition, visitor, ts.isExpression), nodeVisitor(node.incrementor, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80495             case 238 /* ForInStatement */:
80496                 return factory.updateForInStatement(node, nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80497             case 239 /* ForOfStatement */:
80498                 return factory.updateForOfStatement(node, nodeVisitor(node.awaitModifier, tokenVisitor, ts.isToken), nodeVisitor(node.initializer, visitor, ts.isForInitializer), nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80499             case 240 /* ContinueStatement */:
80500                 return factory.updateContinueStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
80501             case 241 /* BreakStatement */:
80502                 return factory.updateBreakStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier));
80503             case 242 /* ReturnStatement */:
80504                 return factory.updateReturnStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80505             case 243 /* WithStatement */:
80506                 return factory.updateWithStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80507             case 244 /* SwitchStatement */:
80508                 return factory.updateSwitchStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodeVisitor(node.caseBlock, visitor, ts.isCaseBlock));
80509             case 245 /* LabeledStatement */:
80510                 return factory.updateLabeledStatement(node, nodeVisitor(node.label, visitor, ts.isIdentifier), nodeVisitor(node.statement, visitor, ts.isStatement, factory.liftToBlock));
80511             case 246 /* ThrowStatement */:
80512                 return factory.updateThrowStatement(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80513             case 247 /* TryStatement */:
80514                 return factory.updateTryStatement(node, nodeVisitor(node.tryBlock, visitor, ts.isBlock), nodeVisitor(node.catchClause, visitor, ts.isCatchClause), nodeVisitor(node.finallyBlock, visitor, ts.isBlock));
80515             case 249 /* VariableDeclaration */:
80516                 return factory.updateVariableDeclaration(node, nodeVisitor(node.name, visitor, ts.isBindingName), nodeVisitor(node.exclamationToken, tokenVisitor, ts.isToken), nodeVisitor(node.type, visitor, ts.isTypeNode), nodeVisitor(node.initializer, visitor, ts.isExpression));
80517             case 250 /* VariableDeclarationList */:
80518                 return factory.updateVariableDeclarationList(node, nodesVisitor(node.declarations, visitor, ts.isVariableDeclaration));
80519             case 251 /* FunctionDeclaration */:
80520                 return factory.updateFunctionDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.asteriskToken, tokenVisitor, ts.isToken), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), visitParameterList(node.parameters, visitor, context, nodesVisitor), nodeVisitor(node.type, visitor, ts.isTypeNode), visitFunctionBody(node.body, visitor, context, nodeVisitor));
80521             case 252 /* ClassDeclaration */:
80522                 return factory.updateClassDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isClassElement));
80523             case 253 /* InterfaceDeclaration */:
80524                 return factory.updateInterfaceDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodesVisitor(node.heritageClauses, visitor, ts.isHeritageClause), nodesVisitor(node.members, visitor, ts.isTypeElement));
80525             case 254 /* TypeAliasDeclaration */:
80526                 return factory.updateTypeAliasDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.typeParameters, visitor, ts.isTypeParameterDeclaration), nodeVisitor(node.type, visitor, ts.isTypeNode));
80527             case 255 /* EnumDeclaration */:
80528                 return factory.updateEnumDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodesVisitor(node.members, visitor, ts.isEnumMember));
80529             case 256 /* ModuleDeclaration */:
80530                 return factory.updateModuleDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.body, visitor, ts.isModuleBody));
80531             case 257 /* ModuleBlock */:
80532                 return factory.updateModuleBlock(node, nodesVisitor(node.statements, visitor, ts.isStatement));
80533             case 258 /* CaseBlock */:
80534                 return factory.updateCaseBlock(node, nodesVisitor(node.clauses, visitor, ts.isCaseOrDefaultClause));
80535             case 259 /* NamespaceExportDeclaration */:
80536                 return factory.updateNamespaceExportDeclaration(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
80537             case 260 /* ImportEqualsDeclaration */:
80538                 return factory.updateImportEqualsDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.moduleReference, visitor, ts.isModuleReference));
80539             case 261 /* ImportDeclaration */:
80540                 return factory.updateImportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.importClause, visitor, ts.isImportClause), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression));
80541             case 262 /* ImportClause */:
80542                 return factory.updateImportClause(node, node.isTypeOnly, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.namedBindings, visitor, ts.isNamedImportBindings));
80543             case 263 /* NamespaceImport */:
80544                 return factory.updateNamespaceImport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
80545             case 269 /* NamespaceExport */:
80546                 return factory.updateNamespaceExport(node, nodeVisitor(node.name, visitor, ts.isIdentifier));
80547             case 264 /* NamedImports */:
80548                 return factory.updateNamedImports(node, nodesVisitor(node.elements, visitor, ts.isImportSpecifier));
80549             case 265 /* ImportSpecifier */:
80550                 return factory.updateImportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
80551             case 266 /* ExportAssignment */:
80552                 return factory.updateExportAssignment(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), nodeVisitor(node.expression, visitor, ts.isExpression));
80553             case 267 /* ExportDeclaration */:
80554                 return factory.updateExportDeclaration(node, nodesVisitor(node.decorators, visitor, ts.isDecorator), nodesVisitor(node.modifiers, visitor, ts.isModifier), node.isTypeOnly, nodeVisitor(node.exportClause, visitor, ts.isNamedExportBindings), nodeVisitor(node.moduleSpecifier, visitor, ts.isExpression));
80555             case 268 /* NamedExports */:
80556                 return factory.updateNamedExports(node, nodesVisitor(node.elements, visitor, ts.isExportSpecifier));
80557             case 270 /* ExportSpecifier */:
80558                 return factory.updateExportSpecifier(node, nodeVisitor(node.propertyName, visitor, ts.isIdentifier), nodeVisitor(node.name, visitor, ts.isIdentifier));
80559             // Module references
80560             case 272 /* ExternalModuleReference */:
80561                 return factory.updateExternalModuleReference(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80562             // JSX
80563             case 273 /* JsxElement */:
80564                 return factory.updateJsxElement(node, nodeVisitor(node.openingElement, visitor, ts.isJsxOpeningElement), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingElement, visitor, ts.isJsxClosingElement));
80565             case 274 /* JsxSelfClosingElement */:
80566                 return factory.updateJsxSelfClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
80567             case 275 /* JsxOpeningElement */:
80568                 return factory.updateJsxOpeningElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression), nodesVisitor(node.typeArguments, visitor, ts.isTypeNode), nodeVisitor(node.attributes, visitor, ts.isJsxAttributes));
80569             case 276 /* JsxClosingElement */:
80570                 return factory.updateJsxClosingElement(node, nodeVisitor(node.tagName, visitor, ts.isJsxTagNameExpression));
80571             case 277 /* JsxFragment */:
80572                 return factory.updateJsxFragment(node, nodeVisitor(node.openingFragment, visitor, ts.isJsxOpeningFragment), nodesVisitor(node.children, visitor, ts.isJsxChild), nodeVisitor(node.closingFragment, visitor, ts.isJsxClosingFragment));
80573             case 280 /* JsxAttribute */:
80574                 return factory.updateJsxAttribute(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.initializer, visitor, ts.isStringLiteralOrJsxExpression));
80575             case 281 /* JsxAttributes */:
80576                 return factory.updateJsxAttributes(node, nodesVisitor(node.properties, visitor, ts.isJsxAttributeLike));
80577             case 282 /* JsxSpreadAttribute */:
80578                 return factory.updateJsxSpreadAttribute(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80579             case 283 /* JsxExpression */:
80580                 return factory.updateJsxExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80581             // Clauses
80582             case 284 /* CaseClause */:
80583                 return factory.updateCaseClause(node, nodeVisitor(node.expression, visitor, ts.isExpression), nodesVisitor(node.statements, visitor, ts.isStatement));
80584             case 285 /* DefaultClause */:
80585                 return factory.updateDefaultClause(node, nodesVisitor(node.statements, visitor, ts.isStatement));
80586             case 286 /* HeritageClause */:
80587                 return factory.updateHeritageClause(node, nodesVisitor(node.types, visitor, ts.isExpressionWithTypeArguments));
80588             case 287 /* CatchClause */:
80589                 return factory.updateCatchClause(node, nodeVisitor(node.variableDeclaration, visitor, ts.isVariableDeclaration), nodeVisitor(node.block, visitor, ts.isBlock));
80590             // Property assignments
80591             case 288 /* PropertyAssignment */:
80592                 return factory.updatePropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
80593             case 289 /* ShorthandPropertyAssignment */:
80594                 return factory.updateShorthandPropertyAssignment(node, nodeVisitor(node.name, visitor, ts.isIdentifier), nodeVisitor(node.objectAssignmentInitializer, visitor, ts.isExpression));
80595             case 290 /* SpreadAssignment */:
80596                 return factory.updateSpreadAssignment(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80597             // Enum
80598             case 291 /* EnumMember */:
80599                 return factory.updateEnumMember(node, nodeVisitor(node.name, visitor, ts.isPropertyName), nodeVisitor(node.initializer, visitor, ts.isExpression));
80600             // Top-level nodes
80601             case 297 /* SourceFile */:
80602                 return factory.updateSourceFile(node, visitLexicalEnvironment(node.statements, visitor, context));
80603             // Transformation nodes
80604             case 336 /* PartiallyEmittedExpression */:
80605                 return factory.updatePartiallyEmittedExpression(node, nodeVisitor(node.expression, visitor, ts.isExpression));
80606             case 337 /* CommaListExpression */:
80607                 return factory.updateCommaListExpression(node, nodesVisitor(node.elements, visitor, ts.isExpression));
80608             default:
80609                 // No need to visit nodes with no children.
80610                 return node;
80611         }
80612     }
80613     ts.visitEachChild = visitEachChild;
80614     /**
80615      * Extracts the single node from a NodeArray.
80616      *
80617      * @param nodes The NodeArray.
80618      */
80619     function extractSingleNode(nodes) {
80620         ts.Debug.assert(nodes.length <= 1, "Too many nodes written to output.");
80621         return ts.singleOrUndefined(nodes);
80622     }
80623 })(ts || (ts = {}));
80624 /* @internal */
80625 var ts;
80626 (function (ts) {
80627     function createSourceMapGenerator(host, file, sourceRoot, sourcesDirectoryPath, generatorOptions) {
80628         var _a = generatorOptions.extendedDiagnostics
80629             ? ts.performance.createTimer("Source Map", "beforeSourcemap", "afterSourcemap")
80630             : ts.performance.nullTimer, enter = _a.enter, exit = _a.exit;
80631         // Current source map file and its index in the sources list
80632         var rawSources = [];
80633         var sources = [];
80634         var sourceToSourceIndexMap = new ts.Map();
80635         var sourcesContent;
80636         var names = [];
80637         var nameToNameIndexMap;
80638         var mappings = "";
80639         // Last recorded and encoded mappings
80640         var lastGeneratedLine = 0;
80641         var lastGeneratedCharacter = 0;
80642         var lastSourceIndex = 0;
80643         var lastSourceLine = 0;
80644         var lastSourceCharacter = 0;
80645         var lastNameIndex = 0;
80646         var hasLast = false;
80647         var pendingGeneratedLine = 0;
80648         var pendingGeneratedCharacter = 0;
80649         var pendingSourceIndex = 0;
80650         var pendingSourceLine = 0;
80651         var pendingSourceCharacter = 0;
80652         var pendingNameIndex = 0;
80653         var hasPending = false;
80654         var hasPendingSource = false;
80655         var hasPendingName = false;
80656         return {
80657             getSources: function () { return rawSources; },
80658             addSource: addSource,
80659             setSourceContent: setSourceContent,
80660             addName: addName,
80661             addMapping: addMapping,
80662             appendSourceMap: appendSourceMap,
80663             toJSON: toJSON,
80664             toString: function () { return JSON.stringify(toJSON()); }
80665         };
80666         function addSource(fileName) {
80667             enter();
80668             var source = ts.getRelativePathToDirectoryOrUrl(sourcesDirectoryPath, fileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
80669             /*isAbsolutePathAnUrl*/ true);
80670             var sourceIndex = sourceToSourceIndexMap.get(source);
80671             if (sourceIndex === undefined) {
80672                 sourceIndex = sources.length;
80673                 sources.push(source);
80674                 rawSources.push(fileName);
80675                 sourceToSourceIndexMap.set(source, sourceIndex);
80676             }
80677             exit();
80678             return sourceIndex;
80679         }
80680         /* eslint-disable boolean-trivia, no-null/no-null */
80681         function setSourceContent(sourceIndex, content) {
80682             enter();
80683             if (content !== null) {
80684                 if (!sourcesContent)
80685                     sourcesContent = [];
80686                 while (sourcesContent.length < sourceIndex) {
80687                     sourcesContent.push(null);
80688                 }
80689                 sourcesContent[sourceIndex] = content;
80690             }
80691             exit();
80692         }
80693         /* eslint-enable boolean-trivia, no-null/no-null */
80694         function addName(name) {
80695             enter();
80696             if (!nameToNameIndexMap)
80697                 nameToNameIndexMap = new ts.Map();
80698             var nameIndex = nameToNameIndexMap.get(name);
80699             if (nameIndex === undefined) {
80700                 nameIndex = names.length;
80701                 names.push(name);
80702                 nameToNameIndexMap.set(name, nameIndex);
80703             }
80704             exit();
80705             return nameIndex;
80706         }
80707         function isNewGeneratedPosition(generatedLine, generatedCharacter) {
80708             return !hasPending
80709                 || pendingGeneratedLine !== generatedLine
80710                 || pendingGeneratedCharacter !== generatedCharacter;
80711         }
80712         function isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter) {
80713             return sourceIndex !== undefined
80714                 && sourceLine !== undefined
80715                 && sourceCharacter !== undefined
80716                 && pendingSourceIndex === sourceIndex
80717                 && (pendingSourceLine > sourceLine
80718                     || pendingSourceLine === sourceLine && pendingSourceCharacter > sourceCharacter);
80719         }
80720         function addMapping(generatedLine, generatedCharacter, sourceIndex, sourceLine, sourceCharacter, nameIndex) {
80721             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
80722             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
80723             ts.Debug.assert(sourceIndex === undefined || sourceIndex >= 0, "sourceIndex cannot be negative");
80724             ts.Debug.assert(sourceLine === undefined || sourceLine >= 0, "sourceLine cannot be negative");
80725             ts.Debug.assert(sourceCharacter === undefined || sourceCharacter >= 0, "sourceCharacter cannot be negative");
80726             enter();
80727             // If this location wasn't recorded or the location in source is going backwards, record the mapping
80728             if (isNewGeneratedPosition(generatedLine, generatedCharacter) ||
80729                 isBacktrackingSourcePosition(sourceIndex, sourceLine, sourceCharacter)) {
80730                 commitPendingMapping();
80731                 pendingGeneratedLine = generatedLine;
80732                 pendingGeneratedCharacter = generatedCharacter;
80733                 hasPendingSource = false;
80734                 hasPendingName = false;
80735                 hasPending = true;
80736             }
80737             if (sourceIndex !== undefined && sourceLine !== undefined && sourceCharacter !== undefined) {
80738                 pendingSourceIndex = sourceIndex;
80739                 pendingSourceLine = sourceLine;
80740                 pendingSourceCharacter = sourceCharacter;
80741                 hasPendingSource = true;
80742                 if (nameIndex !== undefined) {
80743                     pendingNameIndex = nameIndex;
80744                     hasPendingName = true;
80745                 }
80746             }
80747             exit();
80748         }
80749         function appendSourceMap(generatedLine, generatedCharacter, map, sourceMapPath, start, end) {
80750             ts.Debug.assert(generatedLine >= pendingGeneratedLine, "generatedLine cannot backtrack");
80751             ts.Debug.assert(generatedCharacter >= 0, "generatedCharacter cannot be negative");
80752             enter();
80753             // First, decode the old component sourcemap
80754             var sourceIndexToNewSourceIndexMap = [];
80755             var nameIndexToNewNameIndexMap;
80756             var mappingIterator = decodeMappings(map.mappings);
80757             for (var iterResult = mappingIterator.next(); !iterResult.done; iterResult = mappingIterator.next()) {
80758                 var raw = iterResult.value;
80759                 if (end && (raw.generatedLine > end.line ||
80760                     (raw.generatedLine === end.line && raw.generatedCharacter > end.character))) {
80761                     break;
80762                 }
80763                 if (start && (raw.generatedLine < start.line ||
80764                     (start.line === raw.generatedLine && raw.generatedCharacter < start.character))) {
80765                     continue;
80766                 }
80767                 // Then reencode all the updated mappings into the overall map
80768                 var newSourceIndex = void 0;
80769                 var newSourceLine = void 0;
80770                 var newSourceCharacter = void 0;
80771                 var newNameIndex = void 0;
80772                 if (raw.sourceIndex !== undefined) {
80773                     newSourceIndex = sourceIndexToNewSourceIndexMap[raw.sourceIndex];
80774                     if (newSourceIndex === undefined) {
80775                         // Apply offsets to each position and fixup source entries
80776                         var rawPath = map.sources[raw.sourceIndex];
80777                         var relativePath = map.sourceRoot ? ts.combinePaths(map.sourceRoot, rawPath) : rawPath;
80778                         var combinedPath = ts.combinePaths(ts.getDirectoryPath(sourceMapPath), relativePath);
80779                         sourceIndexToNewSourceIndexMap[raw.sourceIndex] = newSourceIndex = addSource(combinedPath);
80780                         if (map.sourcesContent && typeof map.sourcesContent[raw.sourceIndex] === "string") {
80781                             setSourceContent(newSourceIndex, map.sourcesContent[raw.sourceIndex]);
80782                         }
80783                     }
80784                     newSourceLine = raw.sourceLine;
80785                     newSourceCharacter = raw.sourceCharacter;
80786                     if (map.names && raw.nameIndex !== undefined) {
80787                         if (!nameIndexToNewNameIndexMap)
80788                             nameIndexToNewNameIndexMap = [];
80789                         newNameIndex = nameIndexToNewNameIndexMap[raw.nameIndex];
80790                         if (newNameIndex === undefined) {
80791                             nameIndexToNewNameIndexMap[raw.nameIndex] = newNameIndex = addName(map.names[raw.nameIndex]);
80792                         }
80793                     }
80794                 }
80795                 var rawGeneratedLine = raw.generatedLine - (start ? start.line : 0);
80796                 var newGeneratedLine = rawGeneratedLine + generatedLine;
80797                 var rawGeneratedCharacter = start && start.line === raw.generatedLine ? raw.generatedCharacter - start.character : raw.generatedCharacter;
80798                 var newGeneratedCharacter = rawGeneratedLine === 0 ? rawGeneratedCharacter + generatedCharacter : rawGeneratedCharacter;
80799                 addMapping(newGeneratedLine, newGeneratedCharacter, newSourceIndex, newSourceLine, newSourceCharacter, newNameIndex);
80800             }
80801             exit();
80802         }
80803         function shouldCommitMapping() {
80804             return !hasLast
80805                 || lastGeneratedLine !== pendingGeneratedLine
80806                 || lastGeneratedCharacter !== pendingGeneratedCharacter
80807                 || lastSourceIndex !== pendingSourceIndex
80808                 || lastSourceLine !== pendingSourceLine
80809                 || lastSourceCharacter !== pendingSourceCharacter
80810                 || lastNameIndex !== pendingNameIndex;
80811         }
80812         function commitPendingMapping() {
80813             if (!hasPending || !shouldCommitMapping()) {
80814                 return;
80815             }
80816             enter();
80817             // Line/Comma delimiters
80818             if (lastGeneratedLine < pendingGeneratedLine) {
80819                 // Emit line delimiters
80820                 do {
80821                     mappings += ";";
80822                     lastGeneratedLine++;
80823                     lastGeneratedCharacter = 0;
80824                 } while (lastGeneratedLine < pendingGeneratedLine);
80825             }
80826             else {
80827                 ts.Debug.assertEqual(lastGeneratedLine, pendingGeneratedLine, "generatedLine cannot backtrack");
80828                 // Emit comma to separate the entry
80829                 if (hasLast) {
80830                     mappings += ",";
80831                 }
80832             }
80833             // 1. Relative generated character
80834             mappings += base64VLQFormatEncode(pendingGeneratedCharacter - lastGeneratedCharacter);
80835             lastGeneratedCharacter = pendingGeneratedCharacter;
80836             if (hasPendingSource) {
80837                 // 2. Relative sourceIndex
80838                 mappings += base64VLQFormatEncode(pendingSourceIndex - lastSourceIndex);
80839                 lastSourceIndex = pendingSourceIndex;
80840                 // 3. Relative source line
80841                 mappings += base64VLQFormatEncode(pendingSourceLine - lastSourceLine);
80842                 lastSourceLine = pendingSourceLine;
80843                 // 4. Relative source character
80844                 mappings += base64VLQFormatEncode(pendingSourceCharacter - lastSourceCharacter);
80845                 lastSourceCharacter = pendingSourceCharacter;
80846                 if (hasPendingName) {
80847                     // 5. Relative nameIndex
80848                     mappings += base64VLQFormatEncode(pendingNameIndex - lastNameIndex);
80849                     lastNameIndex = pendingNameIndex;
80850                 }
80851             }
80852             hasLast = true;
80853             exit();
80854         }
80855         function toJSON() {
80856             commitPendingMapping();
80857             return {
80858                 version: 3,
80859                 file: file,
80860                 sourceRoot: sourceRoot,
80861                 sources: sources,
80862                 names: names,
80863                 mappings: mappings,
80864                 sourcesContent: sourcesContent,
80865             };
80866         }
80867     }
80868     ts.createSourceMapGenerator = createSourceMapGenerator;
80869     // Sometimes tools can see the following line as a source mapping url comment, so we mangle it a bit (the [M])
80870     var sourceMapCommentRegExp = /^\/\/[@#] source[M]appingURL=(.+)\s*$/;
80871     var whitespaceOrMapCommentRegExp = /^\s*(\/\/[@#] .*)?$/;
80872     function getLineInfo(text, lineStarts) {
80873         return {
80874             getLineCount: function () { return lineStarts.length; },
80875             getLineText: function (line) { return text.substring(lineStarts[line], lineStarts[line + 1]); }
80876         };
80877     }
80878     ts.getLineInfo = getLineInfo;
80879     /**
80880      * Tries to find the sourceMappingURL comment at the end of a file.
80881      */
80882     function tryGetSourceMappingURL(lineInfo) {
80883         for (var index = lineInfo.getLineCount() - 1; index >= 0; index--) {
80884             var line = lineInfo.getLineText(index);
80885             var comment = sourceMapCommentRegExp.exec(line);
80886             if (comment) {
80887                 return comment[1];
80888             }
80889             // If we see a non-whitespace/map comment-like line, break, to avoid scanning up the entire file
80890             else if (!line.match(whitespaceOrMapCommentRegExp)) {
80891                 break;
80892             }
80893         }
80894     }
80895     ts.tryGetSourceMappingURL = tryGetSourceMappingURL;
80896     /* eslint-disable no-null/no-null */
80897     function isStringOrNull(x) {
80898         return typeof x === "string" || x === null;
80899     }
80900     function isRawSourceMap(x) {
80901         return x !== null
80902             && typeof x === "object"
80903             && x.version === 3
80904             && typeof x.file === "string"
80905             && typeof x.mappings === "string"
80906             && ts.isArray(x.sources) && ts.every(x.sources, ts.isString)
80907             && (x.sourceRoot === undefined || x.sourceRoot === null || typeof x.sourceRoot === "string")
80908             && (x.sourcesContent === undefined || x.sourcesContent === null || ts.isArray(x.sourcesContent) && ts.every(x.sourcesContent, isStringOrNull))
80909             && (x.names === undefined || x.names === null || ts.isArray(x.names) && ts.every(x.names, ts.isString));
80910     }
80911     ts.isRawSourceMap = isRawSourceMap;
80912     /* eslint-enable no-null/no-null */
80913     function tryParseRawSourceMap(text) {
80914         try {
80915             var parsed = JSON.parse(text);
80916             if (isRawSourceMap(parsed)) {
80917                 return parsed;
80918             }
80919         }
80920         catch (_a) {
80921             // empty
80922         }
80923         return undefined;
80924     }
80925     ts.tryParseRawSourceMap = tryParseRawSourceMap;
80926     function decodeMappings(mappings) {
80927         var done = false;
80928         var pos = 0;
80929         var generatedLine = 0;
80930         var generatedCharacter = 0;
80931         var sourceIndex = 0;
80932         var sourceLine = 0;
80933         var sourceCharacter = 0;
80934         var nameIndex = 0;
80935         var error;
80936         return {
80937             get pos() { return pos; },
80938             get error() { return error; },
80939             get state() { return captureMapping(/*hasSource*/ true, /*hasName*/ true); },
80940             next: function () {
80941                 while (!done && pos < mappings.length) {
80942                     var ch = mappings.charCodeAt(pos);
80943                     if (ch === 59 /* semicolon */) {
80944                         // new line
80945                         generatedLine++;
80946                         generatedCharacter = 0;
80947                         pos++;
80948                         continue;
80949                     }
80950                     if (ch === 44 /* comma */) {
80951                         // Next entry is on same line - no action needed
80952                         pos++;
80953                         continue;
80954                     }
80955                     var hasSource = false;
80956                     var hasName = false;
80957                     generatedCharacter += base64VLQFormatDecode();
80958                     if (hasReportedError())
80959                         return stopIterating();
80960                     if (generatedCharacter < 0)
80961                         return setErrorAndStopIterating("Invalid generatedCharacter found");
80962                     if (!isSourceMappingSegmentEnd()) {
80963                         hasSource = true;
80964                         sourceIndex += base64VLQFormatDecode();
80965                         if (hasReportedError())
80966                             return stopIterating();
80967                         if (sourceIndex < 0)
80968                             return setErrorAndStopIterating("Invalid sourceIndex found");
80969                         if (isSourceMappingSegmentEnd())
80970                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceIndex");
80971                         sourceLine += base64VLQFormatDecode();
80972                         if (hasReportedError())
80973                             return stopIterating();
80974                         if (sourceLine < 0)
80975                             return setErrorAndStopIterating("Invalid sourceLine found");
80976                         if (isSourceMappingSegmentEnd())
80977                             return setErrorAndStopIterating("Unsupported Format: No entries after sourceLine");
80978                         sourceCharacter += base64VLQFormatDecode();
80979                         if (hasReportedError())
80980                             return stopIterating();
80981                         if (sourceCharacter < 0)
80982                             return setErrorAndStopIterating("Invalid sourceCharacter found");
80983                         if (!isSourceMappingSegmentEnd()) {
80984                             hasName = true;
80985                             nameIndex += base64VLQFormatDecode();
80986                             if (hasReportedError())
80987                                 return stopIterating();
80988                             if (nameIndex < 0)
80989                                 return setErrorAndStopIterating("Invalid nameIndex found");
80990                             if (!isSourceMappingSegmentEnd())
80991                                 return setErrorAndStopIterating("Unsupported Error Format: Entries after nameIndex");
80992                         }
80993                     }
80994                     return { value: captureMapping(hasSource, hasName), done: done };
80995                 }
80996                 return stopIterating();
80997             }
80998         };
80999         function captureMapping(hasSource, hasName) {
81000             return {
81001                 generatedLine: generatedLine,
81002                 generatedCharacter: generatedCharacter,
81003                 sourceIndex: hasSource ? sourceIndex : undefined,
81004                 sourceLine: hasSource ? sourceLine : undefined,
81005                 sourceCharacter: hasSource ? sourceCharacter : undefined,
81006                 nameIndex: hasName ? nameIndex : undefined
81007             };
81008         }
81009         function stopIterating() {
81010             done = true;
81011             return { value: undefined, done: true };
81012         }
81013         function setError(message) {
81014             if (error === undefined) {
81015                 error = message;
81016             }
81017         }
81018         function setErrorAndStopIterating(message) {
81019             setError(message);
81020             return stopIterating();
81021         }
81022         function hasReportedError() {
81023             return error !== undefined;
81024         }
81025         function isSourceMappingSegmentEnd() {
81026             return (pos === mappings.length ||
81027                 mappings.charCodeAt(pos) === 44 /* comma */ ||
81028                 mappings.charCodeAt(pos) === 59 /* semicolon */);
81029         }
81030         function base64VLQFormatDecode() {
81031             var moreDigits = true;
81032             var shiftCount = 0;
81033             var value = 0;
81034             for (; moreDigits; pos++) {
81035                 if (pos >= mappings.length)
81036                     return setError("Error in decoding base64VLQFormatDecode, past the mapping string"), -1;
81037                 // 6 digit number
81038                 var currentByte = base64FormatDecode(mappings.charCodeAt(pos));
81039                 if (currentByte === -1)
81040                     return setError("Invalid character in VLQ"), -1;
81041                 // If msb is set, we still have more bits to continue
81042                 moreDigits = (currentByte & 32) !== 0;
81043                 // least significant 5 bits are the next msbs in the final value.
81044                 value = value | ((currentByte & 31) << shiftCount);
81045                 shiftCount += 5;
81046             }
81047             // Least significant bit if 1 represents negative and rest of the msb is actual absolute value
81048             if ((value & 1) === 0) {
81049                 // + number
81050                 value = value >> 1;
81051             }
81052             else {
81053                 // - number
81054                 value = value >> 1;
81055                 value = -value;
81056             }
81057             return value;
81058         }
81059     }
81060     ts.decodeMappings = decodeMappings;
81061     function sameMapping(left, right) {
81062         return left === right
81063             || left.generatedLine === right.generatedLine
81064                 && left.generatedCharacter === right.generatedCharacter
81065                 && left.sourceIndex === right.sourceIndex
81066                 && left.sourceLine === right.sourceLine
81067                 && left.sourceCharacter === right.sourceCharacter
81068                 && left.nameIndex === right.nameIndex;
81069     }
81070     ts.sameMapping = sameMapping;
81071     function isSourceMapping(mapping) {
81072         return mapping.sourceIndex !== undefined
81073             && mapping.sourceLine !== undefined
81074             && mapping.sourceCharacter !== undefined;
81075     }
81076     ts.isSourceMapping = isSourceMapping;
81077     function base64FormatEncode(value) {
81078         return value >= 0 && value < 26 ? 65 /* A */ + value :
81079             value >= 26 && value < 52 ? 97 /* a */ + value - 26 :
81080                 value >= 52 && value < 62 ? 48 /* _0 */ + value - 52 :
81081                     value === 62 ? 43 /* plus */ :
81082                         value === 63 ? 47 /* slash */ :
81083                             ts.Debug.fail(value + ": not a base64 value");
81084     }
81085     function base64FormatDecode(ch) {
81086         return ch >= 65 /* A */ && ch <= 90 /* Z */ ? ch - 65 /* A */ :
81087             ch >= 97 /* a */ && ch <= 122 /* z */ ? ch - 97 /* a */ + 26 :
81088                 ch >= 48 /* _0 */ && ch <= 57 /* _9 */ ? ch - 48 /* _0 */ + 52 :
81089                     ch === 43 /* plus */ ? 62 :
81090                         ch === 47 /* slash */ ? 63 :
81091                             -1;
81092     }
81093     function base64VLQFormatEncode(inValue) {
81094         // Add a new least significant bit that has the sign of the value.
81095         // if negative number the least significant bit that gets added to the number has value 1
81096         // else least significant bit value that gets added is 0
81097         // eg. -1 changes to binary : 01 [1] => 3
81098         //     +1 changes to binary : 01 [0] => 2
81099         if (inValue < 0) {
81100             inValue = ((-inValue) << 1) + 1;
81101         }
81102         else {
81103             inValue = inValue << 1;
81104         }
81105         // Encode 5 bits at a time starting from least significant bits
81106         var encodedStr = "";
81107         do {
81108             var currentDigit = inValue & 31; // 11111
81109             inValue = inValue >> 5;
81110             if (inValue > 0) {
81111                 // There are still more digits to decode, set the msb (6th bit)
81112                 currentDigit = currentDigit | 32;
81113             }
81114             encodedStr = encodedStr + String.fromCharCode(base64FormatEncode(currentDigit));
81115         } while (inValue > 0);
81116         return encodedStr;
81117     }
81118     function isSourceMappedPosition(value) {
81119         return value.sourceIndex !== undefined
81120             && value.sourcePosition !== undefined;
81121     }
81122     function sameMappedPosition(left, right) {
81123         return left.generatedPosition === right.generatedPosition
81124             && left.sourceIndex === right.sourceIndex
81125             && left.sourcePosition === right.sourcePosition;
81126     }
81127     function compareSourcePositions(left, right) {
81128         // Compares sourcePosition without comparing sourceIndex
81129         // since the mappings are grouped by sourceIndex
81130         ts.Debug.assert(left.sourceIndex === right.sourceIndex);
81131         return ts.compareValues(left.sourcePosition, right.sourcePosition);
81132     }
81133     function compareGeneratedPositions(left, right) {
81134         return ts.compareValues(left.generatedPosition, right.generatedPosition);
81135     }
81136     function getSourcePositionOfMapping(value) {
81137         return value.sourcePosition;
81138     }
81139     function getGeneratedPositionOfMapping(value) {
81140         return value.generatedPosition;
81141     }
81142     function createDocumentPositionMapper(host, map, mapPath) {
81143         var mapDirectory = ts.getDirectoryPath(mapPath);
81144         var sourceRoot = map.sourceRoot ? ts.getNormalizedAbsolutePath(map.sourceRoot, mapDirectory) : mapDirectory;
81145         var generatedAbsoluteFilePath = ts.getNormalizedAbsolutePath(map.file, mapDirectory);
81146         var generatedFile = host.getSourceFileLike(generatedAbsoluteFilePath);
81147         var sourceFileAbsolutePaths = map.sources.map(function (source) { return ts.getNormalizedAbsolutePath(source, sourceRoot); });
81148         var sourceToSourceIndexMap = new ts.Map(sourceFileAbsolutePaths.map(function (source, i) { return [host.getCanonicalFileName(source), i]; }));
81149         var decodedMappings;
81150         var generatedMappings;
81151         var sourceMappings;
81152         return {
81153             getSourcePosition: getSourcePosition,
81154             getGeneratedPosition: getGeneratedPosition
81155         };
81156         function processMapping(mapping) {
81157             var generatedPosition = generatedFile !== undefined
81158                 ? ts.getPositionOfLineAndCharacter(generatedFile, mapping.generatedLine, mapping.generatedCharacter, /*allowEdits*/ true)
81159                 : -1;
81160             var source;
81161             var sourcePosition;
81162             if (isSourceMapping(mapping)) {
81163                 var sourceFile = host.getSourceFileLike(sourceFileAbsolutePaths[mapping.sourceIndex]);
81164                 source = map.sources[mapping.sourceIndex];
81165                 sourcePosition = sourceFile !== undefined
81166                     ? ts.getPositionOfLineAndCharacter(sourceFile, mapping.sourceLine, mapping.sourceCharacter, /*allowEdits*/ true)
81167                     : -1;
81168             }
81169             return {
81170                 generatedPosition: generatedPosition,
81171                 source: source,
81172                 sourceIndex: mapping.sourceIndex,
81173                 sourcePosition: sourcePosition,
81174                 nameIndex: mapping.nameIndex
81175             };
81176         }
81177         function getDecodedMappings() {
81178             if (decodedMappings === undefined) {
81179                 var decoder = decodeMappings(map.mappings);
81180                 var mappings = ts.arrayFrom(decoder, processMapping);
81181                 if (decoder.error !== undefined) {
81182                     if (host.log) {
81183                         host.log("Encountered error while decoding sourcemap: " + decoder.error);
81184                     }
81185                     decodedMappings = ts.emptyArray;
81186                 }
81187                 else {
81188                     decodedMappings = mappings;
81189                 }
81190             }
81191             return decodedMappings;
81192         }
81193         function getSourceMappings(sourceIndex) {
81194             if (sourceMappings === undefined) {
81195                 var lists = [];
81196                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
81197                     var mapping = _a[_i];
81198                     if (!isSourceMappedPosition(mapping))
81199                         continue;
81200                     var list = lists[mapping.sourceIndex];
81201                     if (!list)
81202                         lists[mapping.sourceIndex] = list = [];
81203                     list.push(mapping);
81204                 }
81205                 sourceMappings = lists.map(function (list) { return ts.sortAndDeduplicate(list, compareSourcePositions, sameMappedPosition); });
81206             }
81207             return sourceMappings[sourceIndex];
81208         }
81209         function getGeneratedMappings() {
81210             if (generatedMappings === undefined) {
81211                 var list = [];
81212                 for (var _i = 0, _a = getDecodedMappings(); _i < _a.length; _i++) {
81213                     var mapping = _a[_i];
81214                     list.push(mapping);
81215                 }
81216                 generatedMappings = ts.sortAndDeduplicate(list, compareGeneratedPositions, sameMappedPosition);
81217             }
81218             return generatedMappings;
81219         }
81220         function getGeneratedPosition(loc) {
81221             var sourceIndex = sourceToSourceIndexMap.get(host.getCanonicalFileName(loc.fileName));
81222             if (sourceIndex === undefined)
81223                 return loc;
81224             var sourceMappings = getSourceMappings(sourceIndex);
81225             if (!ts.some(sourceMappings))
81226                 return loc;
81227             var targetIndex = ts.binarySearchKey(sourceMappings, loc.pos, getSourcePositionOfMapping, ts.compareValues);
81228             if (targetIndex < 0) {
81229                 // if no exact match, closest is 2's complement of result
81230                 targetIndex = ~targetIndex;
81231             }
81232             var mapping = sourceMappings[targetIndex];
81233             if (mapping === undefined || mapping.sourceIndex !== sourceIndex) {
81234                 return loc;
81235             }
81236             return { fileName: generatedAbsoluteFilePath, pos: mapping.generatedPosition }; // Closest pos
81237         }
81238         function getSourcePosition(loc) {
81239             var generatedMappings = getGeneratedMappings();
81240             if (!ts.some(generatedMappings))
81241                 return loc;
81242             var targetIndex = ts.binarySearchKey(generatedMappings, loc.pos, getGeneratedPositionOfMapping, ts.compareValues);
81243             if (targetIndex < 0) {
81244                 // if no exact match, closest is 2's complement of result
81245                 targetIndex = ~targetIndex;
81246             }
81247             var mapping = generatedMappings[targetIndex];
81248             if (mapping === undefined || !isSourceMappedPosition(mapping)) {
81249                 return loc;
81250             }
81251             return { fileName: sourceFileAbsolutePaths[mapping.sourceIndex], pos: mapping.sourcePosition }; // Closest pos
81252         }
81253     }
81254     ts.createDocumentPositionMapper = createDocumentPositionMapper;
81255     ts.identitySourceMapConsumer = {
81256         getSourcePosition: ts.identity,
81257         getGeneratedPosition: ts.identity
81258     };
81259 })(ts || (ts = {}));
81260 /* @internal */
81261 var ts;
81262 (function (ts) {
81263     function getOriginalNodeId(node) {
81264         node = ts.getOriginalNode(node);
81265         return node ? ts.getNodeId(node) : 0;
81266     }
81267     ts.getOriginalNodeId = getOriginalNodeId;
81268     function containsDefaultReference(node) {
81269         if (!node)
81270             return false;
81271         if (!ts.isNamedImports(node))
81272             return false;
81273         return ts.some(node.elements, isNamedDefaultReference);
81274     }
81275     function isNamedDefaultReference(e) {
81276         return e.propertyName !== undefined && e.propertyName.escapedText === "default" /* Default */;
81277     }
81278     function chainBundle(context, transformSourceFile) {
81279         return transformSourceFileOrBundle;
81280         function transformSourceFileOrBundle(node) {
81281             return node.kind === 297 /* SourceFile */ ? transformSourceFile(node) : transformBundle(node);
81282         }
81283         function transformBundle(node) {
81284             return context.factory.createBundle(ts.map(node.sourceFiles, transformSourceFile), node.prepends);
81285         }
81286     }
81287     ts.chainBundle = chainBundle;
81288     function getExportNeedsImportStarHelper(node) {
81289         return !!ts.getNamespaceDeclarationNode(node);
81290     }
81291     ts.getExportNeedsImportStarHelper = getExportNeedsImportStarHelper;
81292     function getImportNeedsImportStarHelper(node) {
81293         if (!!ts.getNamespaceDeclarationNode(node)) {
81294             return true;
81295         }
81296         var bindings = node.importClause && node.importClause.namedBindings;
81297         if (!bindings) {
81298             return false;
81299         }
81300         if (!ts.isNamedImports(bindings))
81301             return false;
81302         var defaultRefCount = 0;
81303         for (var _i = 0, _a = bindings.elements; _i < _a.length; _i++) {
81304             var binding = _a[_i];
81305             if (isNamedDefaultReference(binding)) {
81306                 defaultRefCount++;
81307             }
81308         }
81309         // 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
81310         return (defaultRefCount > 0 && defaultRefCount !== bindings.elements.length) || (!!(bindings.elements.length - defaultRefCount) && ts.isDefaultImport(node));
81311     }
81312     ts.getImportNeedsImportStarHelper = getImportNeedsImportStarHelper;
81313     function getImportNeedsImportDefaultHelper(node) {
81314         // 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)
81315         return !getImportNeedsImportStarHelper(node) && (ts.isDefaultImport(node) || (!!node.importClause && ts.isNamedImports(node.importClause.namedBindings) && containsDefaultReference(node.importClause.namedBindings))); // TODO: GH#18217
81316     }
81317     ts.getImportNeedsImportDefaultHelper = getImportNeedsImportDefaultHelper;
81318     function collectExternalModuleInfo(context, sourceFile, resolver, compilerOptions) {
81319         var externalImports = [];
81320         var exportSpecifiers = ts.createMultiMap();
81321         var exportedBindings = [];
81322         var uniqueExports = new ts.Map();
81323         var exportedNames;
81324         var hasExportDefault = false;
81325         var exportEquals;
81326         var hasExportStarsToExportValues = false;
81327         var hasImportStar = false;
81328         var hasImportDefault = false;
81329         for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
81330             var node = _a[_i];
81331             switch (node.kind) {
81332                 case 261 /* ImportDeclaration */:
81333                     // import "mod"
81334                     // import x from "mod"
81335                     // import * as x from "mod"
81336                     // import { x, y } from "mod"
81337                     externalImports.push(node);
81338                     if (!hasImportStar && getImportNeedsImportStarHelper(node)) {
81339                         hasImportStar = true;
81340                     }
81341                     if (!hasImportDefault && getImportNeedsImportDefaultHelper(node)) {
81342                         hasImportDefault = true;
81343                     }
81344                     break;
81345                 case 260 /* ImportEqualsDeclaration */:
81346                     if (node.moduleReference.kind === 272 /* ExternalModuleReference */) {
81347                         // import x = require("mod")
81348                         externalImports.push(node);
81349                     }
81350                     break;
81351                 case 267 /* ExportDeclaration */:
81352                     if (node.moduleSpecifier) {
81353                         if (!node.exportClause) {
81354                             // export * from "mod"
81355                             externalImports.push(node);
81356                             hasExportStarsToExportValues = true;
81357                         }
81358                         else {
81359                             // export * as ns from "mod"
81360                             // export { x, y } from "mod"
81361                             externalImports.push(node);
81362                             if (ts.isNamedExports(node.exportClause)) {
81363                                 addExportedNamesForExportDeclaration(node);
81364                             }
81365                             else {
81366                                 var name = node.exportClause.name;
81367                                 if (!uniqueExports.get(ts.idText(name))) {
81368                                     multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
81369                                     uniqueExports.set(ts.idText(name), true);
81370                                     exportedNames = ts.append(exportedNames, name);
81371                                 }
81372                                 // we use the same helpers for `export * as ns` as we do for `import * as ns`
81373                                 hasImportStar = true;
81374                             }
81375                         }
81376                     }
81377                     else {
81378                         // export { x, y }
81379                         addExportedNamesForExportDeclaration(node);
81380                     }
81381                     break;
81382                 case 266 /* ExportAssignment */:
81383                     if (node.isExportEquals && !exportEquals) {
81384                         // export = x
81385                         exportEquals = node;
81386                     }
81387                     break;
81388                 case 232 /* VariableStatement */:
81389                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
81390                         for (var _b = 0, _c = node.declarationList.declarations; _b < _c.length; _b++) {
81391                             var decl = _c[_b];
81392                             exportedNames = collectExportedVariableInfo(decl, uniqueExports, exportedNames);
81393                         }
81394                     }
81395                     break;
81396                 case 251 /* FunctionDeclaration */:
81397                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
81398                         if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
81399                             // export default function() { }
81400                             if (!hasExportDefault) {
81401                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
81402                                 hasExportDefault = true;
81403                             }
81404                         }
81405                         else {
81406                             // export function x() { }
81407                             var name = node.name;
81408                             if (!uniqueExports.get(ts.idText(name))) {
81409                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
81410                                 uniqueExports.set(ts.idText(name), true);
81411                                 exportedNames = ts.append(exportedNames, name);
81412                             }
81413                         }
81414                     }
81415                     break;
81416                 case 252 /* ClassDeclaration */:
81417                     if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
81418                         if (ts.hasSyntacticModifier(node, 512 /* Default */)) {
81419                             // export default class { }
81420                             if (!hasExportDefault) {
81421                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), context.factory.getDeclarationName(node));
81422                                 hasExportDefault = true;
81423                             }
81424                         }
81425                         else {
81426                             // export class x { }
81427                             var name = node.name;
81428                             if (name && !uniqueExports.get(ts.idText(name))) {
81429                                 multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(node), name);
81430                                 uniqueExports.set(ts.idText(name), true);
81431                                 exportedNames = ts.append(exportedNames, name);
81432                             }
81433                         }
81434                     }
81435                     break;
81436             }
81437         }
81438         var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(context.factory, context.getEmitHelperFactory(), sourceFile, compilerOptions, hasExportStarsToExportValues, hasImportStar, hasImportDefault);
81439         if (externalHelpersImportDeclaration) {
81440             externalImports.unshift(externalHelpersImportDeclaration);
81441         }
81442         return { externalImports: externalImports, exportSpecifiers: exportSpecifiers, exportEquals: exportEquals, hasExportStarsToExportValues: hasExportStarsToExportValues, exportedBindings: exportedBindings, exportedNames: exportedNames, externalHelpersImportDeclaration: externalHelpersImportDeclaration };
81443         function addExportedNamesForExportDeclaration(node) {
81444             for (var _i = 0, _a = ts.cast(node.exportClause, ts.isNamedExports).elements; _i < _a.length; _i++) {
81445                 var specifier = _a[_i];
81446                 if (!uniqueExports.get(ts.idText(specifier.name))) {
81447                     var name = specifier.propertyName || specifier.name;
81448                     if (!node.moduleSpecifier) {
81449                         exportSpecifiers.add(ts.idText(name), specifier);
81450                     }
81451                     var decl = resolver.getReferencedImportDeclaration(name)
81452                         || resolver.getReferencedValueDeclaration(name);
81453                     if (decl) {
81454                         multiMapSparseArrayAdd(exportedBindings, getOriginalNodeId(decl), specifier.name);
81455                     }
81456                     uniqueExports.set(ts.idText(specifier.name), true);
81457                     exportedNames = ts.append(exportedNames, specifier.name);
81458                 }
81459             }
81460         }
81461     }
81462     ts.collectExternalModuleInfo = collectExternalModuleInfo;
81463     function collectExportedVariableInfo(decl, uniqueExports, exportedNames) {
81464         if (ts.isBindingPattern(decl.name)) {
81465             for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
81466                 var element = _a[_i];
81467                 if (!ts.isOmittedExpression(element)) {
81468                     exportedNames = collectExportedVariableInfo(element, uniqueExports, exportedNames);
81469                 }
81470             }
81471         }
81472         else if (!ts.isGeneratedIdentifier(decl.name)) {
81473             var text = ts.idText(decl.name);
81474             if (!uniqueExports.get(text)) {
81475                 uniqueExports.set(text, true);
81476                 exportedNames = ts.append(exportedNames, decl.name);
81477             }
81478         }
81479         return exportedNames;
81480     }
81481     /** Use a sparse array as a multi-map. */
81482     function multiMapSparseArrayAdd(map, key, value) {
81483         var values = map[key];
81484         if (values) {
81485             values.push(value);
81486         }
81487         else {
81488             map[key] = values = [value];
81489         }
81490         return values;
81491     }
81492     /**
81493      * Used in the module transformer to check if an expression is reasonably without sideeffect,
81494      *  and thus better to copy into multiple places rather than to cache in a temporary variable
81495      *  - this is mostly subjective beyond the requirement that the expression not be sideeffecting
81496      */
81497     function isSimpleCopiableExpression(expression) {
81498         return ts.isStringLiteralLike(expression) ||
81499             expression.kind === 8 /* NumericLiteral */ ||
81500             ts.isKeyword(expression.kind) ||
81501             ts.isIdentifier(expression);
81502     }
81503     ts.isSimpleCopiableExpression = isSimpleCopiableExpression;
81504     /**
81505      * A simple inlinable expression is an expression which can be copied into multiple locations
81506      * without risk of repeating any sideeffects and whose value could not possibly change between
81507      * any such locations
81508      */
81509     function isSimpleInlineableExpression(expression) {
81510         return !ts.isIdentifier(expression) && isSimpleCopiableExpression(expression) ||
81511             ts.isWellKnownSymbolSyntactically(expression);
81512     }
81513     ts.isSimpleInlineableExpression = isSimpleInlineableExpression;
81514     function isCompoundAssignment(kind) {
81515         return kind >= 63 /* FirstCompoundAssignment */
81516             && kind <= 77 /* LastCompoundAssignment */;
81517     }
81518     ts.isCompoundAssignment = isCompoundAssignment;
81519     function getNonAssignmentOperatorForCompoundAssignment(kind) {
81520         switch (kind) {
81521             case 63 /* PlusEqualsToken */: return 39 /* PlusToken */;
81522             case 64 /* MinusEqualsToken */: return 40 /* MinusToken */;
81523             case 65 /* AsteriskEqualsToken */: return 41 /* AsteriskToken */;
81524             case 66 /* AsteriskAsteriskEqualsToken */: return 42 /* AsteriskAsteriskToken */;
81525             case 67 /* SlashEqualsToken */: return 43 /* SlashToken */;
81526             case 68 /* PercentEqualsToken */: return 44 /* PercentToken */;
81527             case 69 /* LessThanLessThanEqualsToken */: return 47 /* LessThanLessThanToken */;
81528             case 70 /* GreaterThanGreaterThanEqualsToken */: return 48 /* GreaterThanGreaterThanToken */;
81529             case 71 /* GreaterThanGreaterThanGreaterThanEqualsToken */: return 49 /* GreaterThanGreaterThanGreaterThanToken */;
81530             case 72 /* AmpersandEqualsToken */: return 50 /* AmpersandToken */;
81531             case 73 /* BarEqualsToken */: return 51 /* BarToken */;
81532             case 77 /* CaretEqualsToken */: return 52 /* CaretToken */;
81533             case 74 /* BarBarEqualsToken */: return 56 /* BarBarToken */;
81534             case 75 /* AmpersandAmpersandEqualsToken */: return 55 /* AmpersandAmpersandToken */;
81535             case 76 /* QuestionQuestionEqualsToken */: return 60 /* QuestionQuestionToken */;
81536         }
81537     }
81538     ts.getNonAssignmentOperatorForCompoundAssignment = getNonAssignmentOperatorForCompoundAssignment;
81539     /**
81540      * Adds super call and preceding prologue directives into the list of statements.
81541      *
81542      * @param ctor The constructor node.
81543      * @param result The list of statements.
81544      * @param visitor The visitor to apply to each node added to the result array.
81545      * @returns index of the statement that follows super call
81546      */
81547     function addPrologueDirectivesAndInitialSuperCall(factory, ctor, result, visitor) {
81548         if (ctor.body) {
81549             var statements = ctor.body.statements;
81550             // add prologue directives to the list (if any)
81551             var index = factory.copyPrologue(statements, result, /*ensureUseStrict*/ false, visitor);
81552             if (index === statements.length) {
81553                 // list contains nothing but prologue directives (or empty) - exit
81554                 return index;
81555             }
81556             var superIndex = ts.findIndex(statements, function (s) { return ts.isExpressionStatement(s) && ts.isSuperCall(s.expression); }, index);
81557             if (superIndex > -1) {
81558                 for (var i = index; i <= superIndex; i++) {
81559                     result.push(ts.visitNode(statements[i], visitor, ts.isStatement));
81560                 }
81561                 return superIndex + 1;
81562             }
81563             return index;
81564         }
81565         return 0;
81566     }
81567     ts.addPrologueDirectivesAndInitialSuperCall = addPrologueDirectivesAndInitialSuperCall;
81568     function getProperties(node, requireInitializer, isStatic) {
81569         return ts.filter(node.members, function (m) { return isInitializedOrStaticProperty(m, requireInitializer, isStatic); });
81570     }
81571     ts.getProperties = getProperties;
81572     /**
81573      * Is a class element either a static or an instance property declaration with an initializer?
81574      *
81575      * @param member The class element node.
81576      * @param isStatic A value indicating whether the member should be a static or instance member.
81577      */
81578     function isInitializedOrStaticProperty(member, requireInitializer, isStatic) {
81579         return ts.isPropertyDeclaration(member)
81580             && (!!member.initializer || !requireInitializer)
81581             && ts.hasStaticModifier(member) === isStatic;
81582     }
81583     /**
81584      * Gets a value indicating whether a class element is either a static or an instance property declaration with an initializer.
81585      *
81586      * @param member The class element node.
81587      * @param isStatic A value indicating whether the member should be a static or instance member.
81588      */
81589     function isInitializedProperty(member) {
81590         return member.kind === 163 /* PropertyDeclaration */
81591             && member.initializer !== undefined;
81592     }
81593     ts.isInitializedProperty = isInitializedProperty;
81594 })(ts || (ts = {}));
81595 /*@internal*/
81596 var ts;
81597 (function (ts) {
81598     var FlattenLevel;
81599     (function (FlattenLevel) {
81600         FlattenLevel[FlattenLevel["All"] = 0] = "All";
81601         FlattenLevel[FlattenLevel["ObjectRest"] = 1] = "ObjectRest";
81602     })(FlattenLevel = ts.FlattenLevel || (ts.FlattenLevel = {}));
81603     /**
81604      * Flattens a DestructuringAssignment or a VariableDeclaration to an expression.
81605      *
81606      * @param node The node to flatten.
81607      * @param visitor An optional visitor used to visit initializers.
81608      * @param context The transformation context.
81609      * @param level Indicates the extent to which flattening should occur.
81610      * @param needsValue An optional value indicating whether the value from the right-hand-side of
81611      * the destructuring assignment is needed as part of a larger expression.
81612      * @param createAssignmentCallback An optional callback used to create the assignment expression.
81613      */
81614     function flattenDestructuringAssignment(node, visitor, context, level, needsValue, createAssignmentCallback) {
81615         var location = node;
81616         var value;
81617         if (ts.isDestructuringAssignment(node)) {
81618             value = node.right;
81619             while (ts.isEmptyArrayLiteral(node.left) || ts.isEmptyObjectLiteral(node.left)) {
81620                 if (ts.isDestructuringAssignment(value)) {
81621                     location = node = value;
81622                     value = node.right;
81623                 }
81624                 else {
81625                     return ts.visitNode(value, visitor, ts.isExpression);
81626                 }
81627             }
81628         }
81629         var expressions;
81630         var flattenContext = {
81631             context: context,
81632             level: level,
81633             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
81634             hoistTempVariables: true,
81635             emitExpression: emitExpression,
81636             emitBindingOrAssignment: emitBindingOrAssignment,
81637             createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayAssignmentPattern(context.factory, elements); },
81638             createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectAssignmentPattern(context.factory, elements); },
81639             createArrayBindingOrAssignmentElement: makeAssignmentElement,
81640             visitor: visitor
81641         };
81642         if (value) {
81643             value = ts.visitNode(value, visitor, ts.isExpression);
81644             if (ts.isIdentifier(value) && bindingOrAssignmentElementAssignsToName(node, value.escapedText) ||
81645                 bindingOrAssignmentElementContainsNonLiteralComputedName(node)) {
81646                 // If the right-hand value of the assignment is also an assignment target then
81647                 // we need to cache the right-hand value.
81648                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ false, location);
81649             }
81650             else if (needsValue) {
81651                 // If the right-hand value of the destructuring assignment needs to be preserved (as
81652                 // is the case when the destructuring assignment is part of a larger expression),
81653                 // then we need to cache the right-hand value.
81654                 //
81655                 // The source map location for the assignment should point to the entire binary
81656                 // expression.
81657                 value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
81658             }
81659             else if (ts.nodeIsSynthesized(node)) {
81660                 // Generally, the source map location for a destructuring assignment is the root
81661                 // expression.
81662                 //
81663                 // However, if the root expression is synthesized (as in the case
81664                 // of the initializer when transforming a ForOfStatement), then the source map
81665                 // location should point to the right-hand value of the expression.
81666                 location = value;
81667             }
81668         }
81669         flattenBindingOrAssignmentElement(flattenContext, node, value, location, /*skipInitializer*/ ts.isDestructuringAssignment(node));
81670         if (value && needsValue) {
81671             if (!ts.some(expressions)) {
81672                 return value;
81673             }
81674             expressions.push(value);
81675         }
81676         return context.factory.inlineExpressions(expressions) || context.factory.createOmittedExpression();
81677         function emitExpression(expression) {
81678             expressions = ts.append(expressions, expression);
81679         }
81680         function emitBindingOrAssignment(target, value, location, original) {
81681             ts.Debug.assertNode(target, createAssignmentCallback ? ts.isIdentifier : ts.isExpression);
81682             var expression = createAssignmentCallback
81683                 ? createAssignmentCallback(target, value, location)
81684                 : ts.setTextRange(context.factory.createAssignment(ts.visitNode(target, visitor, ts.isExpression), value), location);
81685             expression.original = original;
81686             emitExpression(expression);
81687         }
81688     }
81689     ts.flattenDestructuringAssignment = flattenDestructuringAssignment;
81690     function bindingOrAssignmentElementAssignsToName(element, escapedName) {
81691         var target = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
81692         if (ts.isBindingOrAssignmentPattern(target)) {
81693             return bindingOrAssignmentPatternAssignsToName(target, escapedName);
81694         }
81695         else if (ts.isIdentifier(target)) {
81696             return target.escapedText === escapedName;
81697         }
81698         return false;
81699     }
81700     function bindingOrAssignmentPatternAssignsToName(pattern, escapedName) {
81701         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
81702         for (var _i = 0, elements_3 = elements; _i < elements_3.length; _i++) {
81703             var element = elements_3[_i];
81704             if (bindingOrAssignmentElementAssignsToName(element, escapedName)) {
81705                 return true;
81706             }
81707         }
81708         return false;
81709     }
81710     function bindingOrAssignmentElementContainsNonLiteralComputedName(element) {
81711         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
81712         if (propertyName && ts.isComputedPropertyName(propertyName) && !ts.isLiteralExpression(propertyName.expression)) {
81713             return true;
81714         }
81715         var target = ts.getTargetOfBindingOrAssignmentElement(element);
81716         return !!target && ts.isBindingOrAssignmentPattern(target) && bindingOrAssignmentPatternContainsNonLiteralComputedName(target);
81717     }
81718     function bindingOrAssignmentPatternContainsNonLiteralComputedName(pattern) {
81719         return !!ts.forEach(ts.getElementsOfBindingOrAssignmentPattern(pattern), bindingOrAssignmentElementContainsNonLiteralComputedName);
81720     }
81721     /**
81722      * Flattens a VariableDeclaration or ParameterDeclaration to one or more variable declarations.
81723      *
81724      * @param node The node to flatten.
81725      * @param visitor An optional visitor used to visit initializers.
81726      * @param context The transformation context.
81727      * @param boundValue The value bound to the declaration.
81728      * @param skipInitializer A value indicating whether to ignore the initializer of `node`.
81729      * @param hoistTempVariables Indicates whether temporary variables should not be recorded in-line.
81730      * @param level Indicates the extent to which flattening should occur.
81731      */
81732     function flattenDestructuringBinding(node, visitor, context, level, rval, hoistTempVariables, skipInitializer) {
81733         if (hoistTempVariables === void 0) { hoistTempVariables = false; }
81734         var pendingExpressions;
81735         var pendingDeclarations = [];
81736         var declarations = [];
81737         var flattenContext = {
81738             context: context,
81739             level: level,
81740             downlevelIteration: !!context.getCompilerOptions().downlevelIteration,
81741             hoistTempVariables: hoistTempVariables,
81742             emitExpression: emitExpression,
81743             emitBindingOrAssignment: emitBindingOrAssignment,
81744             createArrayBindingOrAssignmentPattern: function (elements) { return makeArrayBindingPattern(context.factory, elements); },
81745             createObjectBindingOrAssignmentPattern: function (elements) { return makeObjectBindingPattern(context.factory, elements); },
81746             createArrayBindingOrAssignmentElement: function (name) { return makeBindingElement(context.factory, name); },
81747             visitor: visitor
81748         };
81749         if (ts.isVariableDeclaration(node)) {
81750             var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
81751             if (initializer && (ts.isIdentifier(initializer) && bindingOrAssignmentElementAssignsToName(node, initializer.escapedText) ||
81752                 bindingOrAssignmentElementContainsNonLiteralComputedName(node))) {
81753                 // If the right-hand value of the assignment is also an assignment target then
81754                 // we need to cache the right-hand value.
81755                 initializer = ensureIdentifier(flattenContext, initializer, /*reuseIdentifierExpressions*/ false, initializer);
81756                 node = context.factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, initializer);
81757             }
81758         }
81759         flattenBindingOrAssignmentElement(flattenContext, node, rval, node, skipInitializer);
81760         if (pendingExpressions) {
81761             var temp = context.factory.createTempVariable(/*recordTempVariable*/ undefined);
81762             if (hoistTempVariables) {
81763                 var value = context.factory.inlineExpressions(pendingExpressions);
81764                 pendingExpressions = undefined;
81765                 emitBindingOrAssignment(temp, value, /*location*/ undefined, /*original*/ undefined);
81766             }
81767             else {
81768                 context.hoistVariableDeclaration(temp);
81769                 var pendingDeclaration = ts.last(pendingDeclarations);
81770                 pendingDeclaration.pendingExpressions = ts.append(pendingDeclaration.pendingExpressions, context.factory.createAssignment(temp, pendingDeclaration.value));
81771                 ts.addRange(pendingDeclaration.pendingExpressions, pendingExpressions);
81772                 pendingDeclaration.value = temp;
81773             }
81774         }
81775         for (var _i = 0, pendingDeclarations_1 = pendingDeclarations; _i < pendingDeclarations_1.length; _i++) {
81776             var _a = pendingDeclarations_1[_i], pendingExpressions_1 = _a.pendingExpressions, name = _a.name, value = _a.value, location = _a.location, original = _a.original;
81777             var variable = context.factory.createVariableDeclaration(name, 
81778             /*exclamationToken*/ undefined, 
81779             /*type*/ undefined, pendingExpressions_1 ? context.factory.inlineExpressions(ts.append(pendingExpressions_1, value)) : value);
81780             variable.original = original;
81781             ts.setTextRange(variable, location);
81782             declarations.push(variable);
81783         }
81784         return declarations;
81785         function emitExpression(value) {
81786             pendingExpressions = ts.append(pendingExpressions, value);
81787         }
81788         function emitBindingOrAssignment(target, value, location, original) {
81789             ts.Debug.assertNode(target, ts.isBindingName);
81790             if (pendingExpressions) {
81791                 value = context.factory.inlineExpressions(ts.append(pendingExpressions, value));
81792                 pendingExpressions = undefined;
81793             }
81794             pendingDeclarations.push({ pendingExpressions: pendingExpressions, name: target, value: value, location: location, original: original });
81795         }
81796     }
81797     ts.flattenDestructuringBinding = flattenDestructuringBinding;
81798     /**
81799      * Flattens a BindingOrAssignmentElement into zero or more bindings or assignments.
81800      *
81801      * @param flattenContext Options used to control flattening.
81802      * @param element The element to flatten.
81803      * @param value The current RHS value to assign to the element.
81804      * @param location The location to use for source maps and comments.
81805      * @param skipInitializer An optional value indicating whether to include the initializer
81806      * for the element.
81807      */
81808     function flattenBindingOrAssignmentElement(flattenContext, element, value, location, skipInitializer) {
81809         var bindingTarget = ts.getTargetOfBindingOrAssignmentElement(element); // TODO: GH#18217
81810         if (!skipInitializer) {
81811             var initializer = ts.visitNode(ts.getInitializerOfBindingOrAssignmentElement(element), flattenContext.visitor, ts.isExpression);
81812             if (initializer) {
81813                 // Combine value and initializer
81814                 if (value) {
81815                     value = createDefaultValueCheck(flattenContext, value, initializer, location);
81816                     // If 'value' is not a simple expression, it could contain side-effecting code that should evaluate before an object or array binding pattern.
81817                     if (!ts.isSimpleInlineableExpression(initializer) && ts.isBindingOrAssignmentPattern(bindingTarget)) {
81818                         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
81819                     }
81820                 }
81821                 else {
81822                     value = initializer;
81823                 }
81824             }
81825             else if (!value) {
81826                 // Use 'void 0' in absence of value and initializer
81827                 value = flattenContext.context.factory.createVoidZero();
81828             }
81829         }
81830         if (ts.isObjectBindingOrAssignmentPattern(bindingTarget)) {
81831             flattenObjectBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
81832         }
81833         else if (ts.isArrayBindingOrAssignmentPattern(bindingTarget)) {
81834             flattenArrayBindingOrAssignmentPattern(flattenContext, element, bindingTarget, value, location);
81835         }
81836         else {
81837             flattenContext.emitBindingOrAssignment(bindingTarget, value, location, /*original*/ element); // TODO: GH#18217
81838         }
81839     }
81840     /**
81841      * Flattens an ObjectBindingOrAssignmentPattern into zero or more bindings or assignments.
81842      *
81843      * @param flattenContext Options used to control flattening.
81844      * @param parent The parent element of the pattern.
81845      * @param pattern The ObjectBindingOrAssignmentPattern to flatten.
81846      * @param value The current RHS value to assign to the element.
81847      * @param location The location to use for source maps and comments.
81848      */
81849     function flattenObjectBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
81850         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
81851         var numElements = elements.length;
81852         if (numElements !== 1) {
81853             // For anything other than a single-element destructuring we need to generate a temporary
81854             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
81855             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
81856             // so in that case, we'll intentionally create that temporary.
81857             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
81858             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
81859         }
81860         var bindingElements;
81861         var computedTempVariables;
81862         for (var i = 0; i < numElements; i++) {
81863             var element = elements[i];
81864             if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
81865                 var propertyName = ts.getPropertyNameOfBindingOrAssignmentElement(element);
81866                 if (flattenContext.level >= 1 /* ObjectRest */
81867                     && !(element.transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
81868                     && !(ts.getTargetOfBindingOrAssignmentElement(element).transformFlags & (8192 /* ContainsRestOrSpread */ | 16384 /* ContainsObjectRestOrSpread */))
81869                     && !ts.isComputedPropertyName(propertyName)) {
81870                     bindingElements = ts.append(bindingElements, ts.visitNode(element, flattenContext.visitor));
81871                 }
81872                 else {
81873                     if (bindingElements) {
81874                         flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
81875                         bindingElements = undefined;
81876                     }
81877                     var rhsValue = createDestructuringPropertyAccess(flattenContext, value, propertyName);
81878                     if (ts.isComputedPropertyName(propertyName)) {
81879                         computedTempVariables = ts.append(computedTempVariables, rhsValue.argumentExpression);
81880                     }
81881                     flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
81882                 }
81883             }
81884             else if (i === numElements - 1) {
81885                 if (bindingElements) {
81886                     flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
81887                     bindingElements = undefined;
81888                 }
81889                 var rhsValue = flattenContext.context.getEmitHelperFactory().createRestHelper(value, elements, computedTempVariables, pattern);
81890                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, element);
81891             }
81892         }
81893         if (bindingElements) {
81894             flattenContext.emitBindingOrAssignment(flattenContext.createObjectBindingOrAssignmentPattern(bindingElements), value, location, pattern);
81895         }
81896     }
81897     /**
81898      * Flattens an ArrayBindingOrAssignmentPattern into zero or more bindings or assignments.
81899      *
81900      * @param flattenContext Options used to control flattening.
81901      * @param parent The parent element of the pattern.
81902      * @param pattern The ArrayBindingOrAssignmentPattern to flatten.
81903      * @param value The current RHS value to assign to the element.
81904      * @param location The location to use for source maps and comments.
81905      */
81906     function flattenArrayBindingOrAssignmentPattern(flattenContext, parent, pattern, value, location) {
81907         var elements = ts.getElementsOfBindingOrAssignmentPattern(pattern);
81908         var numElements = elements.length;
81909         if (flattenContext.level < 1 /* ObjectRest */ && flattenContext.downlevelIteration) {
81910             // Read the elements of the iterable into an array
81911             value = ensureIdentifier(flattenContext, ts.setTextRange(flattenContext.context.getEmitHelperFactory().createReadHelper(value, numElements > 0 && ts.getRestIndicatorOfBindingOrAssignmentElement(elements[numElements - 1])
81912                 ? undefined
81913                 : numElements), location), 
81914             /*reuseIdentifierExpressions*/ false, location);
81915         }
81916         else if (numElements !== 1 && (flattenContext.level < 1 /* ObjectRest */ || numElements === 0)
81917             || ts.every(elements, ts.isOmittedExpression)) {
81918             // For anything other than a single-element destructuring we need to generate a temporary
81919             // to ensure value is evaluated exactly once. Additionally, if we have zero elements
81920             // we need to emit *something* to ensure that in case a 'var' keyword was already emitted,
81921             // so in that case, we'll intentionally create that temporary.
81922             // Or all the elements of the binding pattern are omitted expression such as "var [,] = [1,2]",
81923             // then we will create temporary variable.
81924             var reuseIdentifierExpressions = !ts.isDeclarationBindingElement(parent) || numElements !== 0;
81925             value = ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location);
81926         }
81927         var bindingElements;
81928         var restContainingElements;
81929         for (var i = 0; i < numElements; i++) {
81930             var element = elements[i];
81931             if (flattenContext.level >= 1 /* ObjectRest */) {
81932                 // If an array pattern contains an ObjectRest, we must cache the result so that we
81933                 // can perform the ObjectRest destructuring in a different declaration
81934                 if (element.transformFlags & 16384 /* ContainsObjectRestOrSpread */ || flattenContext.hasTransformedPriorElement && !isSimpleBindingOrAssignmentElement(element)) {
81935                     flattenContext.hasTransformedPriorElement = true;
81936                     var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
81937                     if (flattenContext.hoistTempVariables) {
81938                         flattenContext.context.hoistVariableDeclaration(temp);
81939                     }
81940                     restContainingElements = ts.append(restContainingElements, [temp, element]);
81941                     bindingElements = ts.append(bindingElements, flattenContext.createArrayBindingOrAssignmentElement(temp));
81942                 }
81943                 else {
81944                     bindingElements = ts.append(bindingElements, element);
81945                 }
81946             }
81947             else if (ts.isOmittedExpression(element)) {
81948                 continue;
81949             }
81950             else if (!ts.getRestIndicatorOfBindingOrAssignmentElement(element)) {
81951                 var rhsValue = flattenContext.context.factory.createElementAccessExpression(value, i);
81952                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
81953             }
81954             else if (i === numElements - 1) {
81955                 var rhsValue = flattenContext.context.factory.createArraySliceCall(value, i);
81956                 flattenBindingOrAssignmentElement(flattenContext, element, rhsValue, /*location*/ element);
81957             }
81958         }
81959         if (bindingElements) {
81960             flattenContext.emitBindingOrAssignment(flattenContext.createArrayBindingOrAssignmentPattern(bindingElements), value, location, pattern);
81961         }
81962         if (restContainingElements) {
81963             for (var _i = 0, restContainingElements_1 = restContainingElements; _i < restContainingElements_1.length; _i++) {
81964                 var _a = restContainingElements_1[_i], id = _a[0], element = _a[1];
81965                 flattenBindingOrAssignmentElement(flattenContext, element, id, element);
81966             }
81967         }
81968     }
81969     function isSimpleBindingOrAssignmentElement(element) {
81970         var target = ts.getTargetOfBindingOrAssignmentElement(element);
81971         if (!target || ts.isOmittedExpression(target))
81972             return true;
81973         var propertyName = ts.tryGetPropertyNameOfBindingOrAssignmentElement(element);
81974         if (propertyName && !ts.isPropertyNameLiteral(propertyName))
81975             return false;
81976         var initializer = ts.getInitializerOfBindingOrAssignmentElement(element);
81977         if (initializer && !ts.isSimpleInlineableExpression(initializer))
81978             return false;
81979         if (ts.isBindingOrAssignmentPattern(target))
81980             return ts.every(ts.getElementsOfBindingOrAssignmentPattern(target), isSimpleBindingOrAssignmentElement);
81981         return ts.isIdentifier(target);
81982     }
81983     /**
81984      * Creates an expression used to provide a default value if a value is `undefined` at runtime.
81985      *
81986      * @param flattenContext Options used to control flattening.
81987      * @param value The RHS value to test.
81988      * @param defaultValue The default value to use if `value` is `undefined` at runtime.
81989      * @param location The location to use for source maps and comments.
81990      */
81991     function createDefaultValueCheck(flattenContext, value, defaultValue, location) {
81992         value = ensureIdentifier(flattenContext, value, /*reuseIdentifierExpressions*/ true, location);
81993         return flattenContext.context.factory.createConditionalExpression(flattenContext.context.factory.createTypeCheck(value, "undefined"), /*questionToken*/ undefined, defaultValue, /*colonToken*/ undefined, value);
81994     }
81995     /**
81996      * Creates either a PropertyAccessExpression or an ElementAccessExpression for the
81997      * right-hand side of a transformed destructuring assignment.
81998      *
81999      * @link https://tc39.github.io/ecma262/#sec-runtime-semantics-keyeddestructuringassignmentevaluation
82000      *
82001      * @param flattenContext Options used to control flattening.
82002      * @param value The RHS value that is the source of the property.
82003      * @param propertyName The destructuring property name.
82004      */
82005     function createDestructuringPropertyAccess(flattenContext, value, propertyName) {
82006         if (ts.isComputedPropertyName(propertyName)) {
82007             var argumentExpression = ensureIdentifier(flattenContext, ts.visitNode(propertyName.expression, flattenContext.visitor), /*reuseIdentifierExpressions*/ false, /*location*/ propertyName);
82008             return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
82009         }
82010         else if (ts.isStringOrNumericLiteralLike(propertyName)) {
82011             var argumentExpression = ts.factory.cloneNode(propertyName);
82012             return flattenContext.context.factory.createElementAccessExpression(value, argumentExpression);
82013         }
82014         else {
82015             var name = flattenContext.context.factory.createIdentifier(ts.idText(propertyName));
82016             return flattenContext.context.factory.createPropertyAccessExpression(value, name);
82017         }
82018     }
82019     /**
82020      * Ensures that there exists a declared identifier whose value holds the given expression.
82021      * This function is useful to ensure that the expression's value can be read from in subsequent expressions.
82022      * Unless 'reuseIdentifierExpressions' is false, 'value' will be returned if it is just an identifier.
82023      *
82024      * @param flattenContext Options used to control flattening.
82025      * @param value the expression whose value needs to be bound.
82026      * @param reuseIdentifierExpressions true if identifier expressions can simply be returned;
82027      * false if it is necessary to always emit an identifier.
82028      * @param location The location to use for source maps and comments.
82029      */
82030     function ensureIdentifier(flattenContext, value, reuseIdentifierExpressions, location) {
82031         if (ts.isIdentifier(value) && reuseIdentifierExpressions) {
82032             return value;
82033         }
82034         else {
82035             var temp = flattenContext.context.factory.createTempVariable(/*recordTempVariable*/ undefined);
82036             if (flattenContext.hoistTempVariables) {
82037                 flattenContext.context.hoistVariableDeclaration(temp);
82038                 flattenContext.emitExpression(ts.setTextRange(flattenContext.context.factory.createAssignment(temp, value), location));
82039             }
82040             else {
82041                 flattenContext.emitBindingOrAssignment(temp, value, location, /*original*/ undefined);
82042             }
82043             return temp;
82044         }
82045     }
82046     function makeArrayBindingPattern(factory, elements) {
82047         ts.Debug.assertEachNode(elements, ts.isArrayBindingElement);
82048         return factory.createArrayBindingPattern(elements);
82049     }
82050     function makeArrayAssignmentPattern(factory, elements) {
82051         return factory.createArrayLiteralExpression(ts.map(elements, factory.converters.convertToArrayAssignmentElement));
82052     }
82053     function makeObjectBindingPattern(factory, elements) {
82054         ts.Debug.assertEachNode(elements, ts.isBindingElement);
82055         return factory.createObjectBindingPattern(elements);
82056     }
82057     function makeObjectAssignmentPattern(factory, elements) {
82058         return factory.createObjectLiteralExpression(ts.map(elements, factory.converters.convertToObjectAssignmentElement));
82059     }
82060     function makeBindingElement(factory, name) {
82061         return factory.createBindingElement(/*dotDotDotToken*/ undefined, /*propertyName*/ undefined, name);
82062     }
82063     function makeAssignmentElement(name) {
82064         return name;
82065     }
82066 })(ts || (ts = {}));
82067 /*@internal*/
82068 var ts;
82069 (function (ts) {
82070     var ProcessLevel;
82071     (function (ProcessLevel) {
82072         ProcessLevel[ProcessLevel["LiftRestriction"] = 0] = "LiftRestriction";
82073         ProcessLevel[ProcessLevel["All"] = 1] = "All";
82074     })(ProcessLevel = ts.ProcessLevel || (ts.ProcessLevel = {}));
82075     function processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, level) {
82076         // Visit the tag expression
82077         var tag = ts.visitNode(node.tag, visitor, ts.isExpression);
82078         // Build up the template arguments and the raw and cooked strings for the template.
82079         // We start out with 'undefined' for the first argument and revisit later
82080         // to avoid walking over the template string twice and shifting all our arguments over after the fact.
82081         var templateArguments = [undefined];
82082         var cookedStrings = [];
82083         var rawStrings = [];
82084         var template = node.template;
82085         if (level === ProcessLevel.LiftRestriction && !ts.hasInvalidEscape(template)) {
82086             return ts.visitEachChild(node, visitor, context);
82087         }
82088         if (ts.isNoSubstitutionTemplateLiteral(template)) {
82089             cookedStrings.push(createTemplateCooked(template));
82090             rawStrings.push(getRawLiteral(template, currentSourceFile));
82091         }
82092         else {
82093             cookedStrings.push(createTemplateCooked(template.head));
82094             rawStrings.push(getRawLiteral(template.head, currentSourceFile));
82095             for (var _i = 0, _a = template.templateSpans; _i < _a.length; _i++) {
82096                 var templateSpan = _a[_i];
82097                 cookedStrings.push(createTemplateCooked(templateSpan.literal));
82098                 rawStrings.push(getRawLiteral(templateSpan.literal, currentSourceFile));
82099                 templateArguments.push(ts.visitNode(templateSpan.expression, visitor, ts.isExpression));
82100             }
82101         }
82102         var helperCall = context.getEmitHelperFactory().createTemplateObjectHelper(ts.factory.createArrayLiteralExpression(cookedStrings), ts.factory.createArrayLiteralExpression(rawStrings));
82103         // Create a variable to cache the template object if we're in a module.
82104         // Do not do this in the global scope, as any variable we currently generate could conflict with
82105         // variables from outside of the current compilation. In the future, we can revisit this behavior.
82106         if (ts.isExternalModule(currentSourceFile)) {
82107             var tempVar = ts.factory.createUniqueName("templateObject");
82108             recordTaggedTemplateString(tempVar);
82109             templateArguments[0] = ts.factory.createLogicalOr(tempVar, ts.factory.createAssignment(tempVar, helperCall));
82110         }
82111         else {
82112             templateArguments[0] = helperCall;
82113         }
82114         return ts.factory.createCallExpression(tag, /*typeArguments*/ undefined, templateArguments);
82115     }
82116     ts.processTaggedTemplateExpression = processTaggedTemplateExpression;
82117     function createTemplateCooked(template) {
82118         return template.templateFlags ? ts.factory.createVoidZero() : ts.factory.createStringLiteral(template.text);
82119     }
82120     /**
82121      * Creates an ES5 compatible literal from an ES6 template literal.
82122      *
82123      * @param node The ES6 template literal.
82124      */
82125     function getRawLiteral(node, currentSourceFile) {
82126         // Find original source text, since we need to emit the raw strings of the tagged template.
82127         // The raw strings contain the (escaped) strings of what the user wrote.
82128         // Examples: `\n` is converted to "\\n", a template string with a newline to "\n".
82129         var text = node.rawText;
82130         if (text === undefined) {
82131             text = ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node);
82132             // text contains the original source, it will also contain quotes ("`"), dolar signs and braces ("${" and "}"),
82133             // thus we need to remove those characters.
82134             // First template piece starts with "`", others with "}"
82135             // Last template piece ends with "`", others with "${"
82136             var isLast = node.kind === 14 /* NoSubstitutionTemplateLiteral */ || node.kind === 17 /* TemplateTail */;
82137             text = text.substring(1, text.length - (isLast ? 1 : 2));
82138         }
82139         // Newline normalization:
82140         // ES6 Spec 11.8.6.1 - Static Semantics of TV's and TRV's
82141         // <CR><LF> and <CR> LineTerminatorSequences are normalized to <LF> for both TV and TRV.
82142         text = text.replace(/\r\n?/g, "\n");
82143         return ts.setTextRange(ts.factory.createStringLiteral(text), node);
82144     }
82145 })(ts || (ts = {}));
82146 /*@internal*/
82147 var ts;
82148 (function (ts) {
82149     /**
82150      * Indicates whether to emit type metadata in the new format.
82151      */
82152     var USE_NEW_TYPE_METADATA_FORMAT = false;
82153     var TypeScriptSubstitutionFlags;
82154     (function (TypeScriptSubstitutionFlags) {
82155         /** Enables substitutions for decorated classes. */
82156         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
82157         /** Enables substitutions for namespace exports. */
82158         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NamespaceExports"] = 2] = "NamespaceExports";
82159         /* Enables substitutions for unqualified enum members */
82160         TypeScriptSubstitutionFlags[TypeScriptSubstitutionFlags["NonQualifiedEnumMembers"] = 8] = "NonQualifiedEnumMembers";
82161     })(TypeScriptSubstitutionFlags || (TypeScriptSubstitutionFlags = {}));
82162     var ClassFacts;
82163     (function (ClassFacts) {
82164         ClassFacts[ClassFacts["None"] = 0] = "None";
82165         ClassFacts[ClassFacts["HasStaticInitializedProperties"] = 1] = "HasStaticInitializedProperties";
82166         ClassFacts[ClassFacts["HasConstructorDecorators"] = 2] = "HasConstructorDecorators";
82167         ClassFacts[ClassFacts["HasMemberDecorators"] = 4] = "HasMemberDecorators";
82168         ClassFacts[ClassFacts["IsExportOfNamespace"] = 8] = "IsExportOfNamespace";
82169         ClassFacts[ClassFacts["IsNamedExternalExport"] = 16] = "IsNamedExternalExport";
82170         ClassFacts[ClassFacts["IsDefaultExternalExport"] = 32] = "IsDefaultExternalExport";
82171         ClassFacts[ClassFacts["IsDerivedClass"] = 64] = "IsDerivedClass";
82172         ClassFacts[ClassFacts["UseImmediatelyInvokedFunctionExpression"] = 128] = "UseImmediatelyInvokedFunctionExpression";
82173         ClassFacts[ClassFacts["HasAnyDecorators"] = 6] = "HasAnyDecorators";
82174         ClassFacts[ClassFacts["NeedsName"] = 5] = "NeedsName";
82175         ClassFacts[ClassFacts["MayNeedImmediatelyInvokedFunctionExpression"] = 7] = "MayNeedImmediatelyInvokedFunctionExpression";
82176         ClassFacts[ClassFacts["IsExported"] = 56] = "IsExported";
82177     })(ClassFacts || (ClassFacts = {}));
82178     function transformTypeScript(context) {
82179         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
82180         var resolver = context.getEmitResolver();
82181         var compilerOptions = context.getCompilerOptions();
82182         var strictNullChecks = ts.getStrictOptionValue(compilerOptions, "strictNullChecks");
82183         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
82184         var moduleKind = ts.getEmitModuleKind(compilerOptions);
82185         // Save the previous transformation hooks.
82186         var previousOnEmitNode = context.onEmitNode;
82187         var previousOnSubstituteNode = context.onSubstituteNode;
82188         // Set new transformation hooks.
82189         context.onEmitNode = onEmitNode;
82190         context.onSubstituteNode = onSubstituteNode;
82191         // Enable substitution for property/element access to emit const enum values.
82192         context.enableSubstitution(201 /* PropertyAccessExpression */);
82193         context.enableSubstitution(202 /* ElementAccessExpression */);
82194         // These variables contain state that changes as we descend into the tree.
82195         var currentSourceFile;
82196         var currentNamespace;
82197         var currentNamespaceContainerName;
82198         var currentLexicalScope;
82199         var currentNameScope;
82200         var currentScopeFirstDeclarationsOfName;
82201         var currentClassHasParameterProperties;
82202         /**
82203          * Keeps track of whether expression substitution has been enabled for specific edge cases.
82204          * They are persisted between each SourceFile transformation and should not be reset.
82205          */
82206         var enabledSubstitutions;
82207         /**
82208          * A map that keeps track of aliases created for classes with decorators to avoid issues
82209          * with the double-binding behavior of classes.
82210          */
82211         var classAliases;
82212         /**
82213          * Keeps track of whether we are within any containing namespaces when performing
82214          * just-in-time substitution while printing an expression identifier.
82215          */
82216         var applicableSubstitutions;
82217         return transformSourceFileOrBundle;
82218         function transformSourceFileOrBundle(node) {
82219             if (node.kind === 298 /* Bundle */) {
82220                 return transformBundle(node);
82221             }
82222             return transformSourceFile(node);
82223         }
82224         function transformBundle(node) {
82225             return factory.createBundle(node.sourceFiles.map(transformSourceFile), ts.mapDefined(node.prepends, function (prepend) {
82226                 if (prepend.kind === 300 /* InputFiles */) {
82227                     return ts.createUnparsedSourceFile(prepend, "js");
82228                 }
82229                 return prepend;
82230             }));
82231         }
82232         /**
82233          * Transform TypeScript-specific syntax in a SourceFile.
82234          *
82235          * @param node A SourceFile node.
82236          */
82237         function transformSourceFile(node) {
82238             if (node.isDeclarationFile) {
82239                 return node;
82240             }
82241             currentSourceFile = node;
82242             var visited = saveStateAndInvoke(node, visitSourceFile);
82243             ts.addEmitHelpers(visited, context.readEmitHelpers());
82244             currentSourceFile = undefined;
82245             return visited;
82246         }
82247         /**
82248          * Visits a node, saving and restoring state variables on the stack.
82249          *
82250          * @param node The node to visit.
82251          */
82252         function saveStateAndInvoke(node, f) {
82253             // Save state
82254             var savedCurrentScope = currentLexicalScope;
82255             var savedCurrentNameScope = currentNameScope;
82256             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
82257             var savedCurrentClassHasParameterProperties = currentClassHasParameterProperties;
82258             // Handle state changes before visiting a node.
82259             onBeforeVisitNode(node);
82260             var visited = f(node);
82261             // Restore state
82262             if (currentLexicalScope !== savedCurrentScope) {
82263                 currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
82264             }
82265             currentLexicalScope = savedCurrentScope;
82266             currentNameScope = savedCurrentNameScope;
82267             currentClassHasParameterProperties = savedCurrentClassHasParameterProperties;
82268             return visited;
82269         }
82270         /**
82271          * Performs actions that should always occur immediately before visiting a node.
82272          *
82273          * @param node The node to visit.
82274          */
82275         function onBeforeVisitNode(node) {
82276             switch (node.kind) {
82277                 case 297 /* SourceFile */:
82278                 case 258 /* CaseBlock */:
82279                 case 257 /* ModuleBlock */:
82280                 case 230 /* Block */:
82281                     currentLexicalScope = node;
82282                     currentNameScope = undefined;
82283                     currentScopeFirstDeclarationsOfName = undefined;
82284                     break;
82285                 case 252 /* ClassDeclaration */:
82286                 case 251 /* FunctionDeclaration */:
82287                     if (ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
82288                         break;
82289                     }
82290                     // Record these declarations provided that they have a name.
82291                     if (node.name) {
82292                         recordEmittedDeclarationInScope(node);
82293                     }
82294                     else {
82295                         // These nodes should always have names unless they are default-exports;
82296                         // however, class declaration parsing allows for undefined names, so syntactically invalid
82297                         // programs may also have an undefined name.
82298                         ts.Debug.assert(node.kind === 252 /* ClassDeclaration */ || ts.hasSyntacticModifier(node, 512 /* Default */));
82299                     }
82300                     if (ts.isClassDeclaration(node)) {
82301                         // XXX: should probably also cover interfaces and type aliases that can have type variables?
82302                         currentNameScope = node;
82303                     }
82304                     break;
82305             }
82306         }
82307         /**
82308          * General-purpose node visitor.
82309          *
82310          * @param node The node to visit.
82311          */
82312         function visitor(node) {
82313             return saveStateAndInvoke(node, visitorWorker);
82314         }
82315         /**
82316          * Visits and possibly transforms any node.
82317          *
82318          * @param node The node to visit.
82319          */
82320         function visitorWorker(node) {
82321             if (node.transformFlags & 1 /* ContainsTypeScript */) {
82322                 return visitTypeScript(node);
82323             }
82324             return node;
82325         }
82326         /**
82327          * Specialized visitor that visits the immediate children of a SourceFile.
82328          *
82329          * @param node The node to visit.
82330          */
82331         function sourceElementVisitor(node) {
82332             return saveStateAndInvoke(node, sourceElementVisitorWorker);
82333         }
82334         /**
82335          * Specialized visitor that visits the immediate children of a SourceFile.
82336          *
82337          * @param node The node to visit.
82338          */
82339         function sourceElementVisitorWorker(node) {
82340             switch (node.kind) {
82341                 case 261 /* ImportDeclaration */:
82342                 case 260 /* ImportEqualsDeclaration */:
82343                 case 266 /* ExportAssignment */:
82344                 case 267 /* ExportDeclaration */:
82345                     return visitElidableStatement(node);
82346                 default:
82347                     return visitorWorker(node);
82348             }
82349         }
82350         function visitElidableStatement(node) {
82351             var parsed = ts.getParseTreeNode(node);
82352             if (parsed !== node) {
82353                 // If the node has been transformed by a `before` transformer, perform no ellision on it
82354                 // As the type information we would attempt to lookup to perform ellision is potentially unavailable for the synthesized nodes
82355                 // We do not reuse `visitorWorker`, as the ellidable statement syntax kinds are technically unrecognized by the switch-case in `visitTypeScript`,
82356                 // and will trigger debug failures when debug verbosity is turned up
82357                 if (node.transformFlags & 1 /* ContainsTypeScript */) {
82358                     // This node contains TypeScript, so we should visit its children.
82359                     return ts.visitEachChild(node, visitor, context);
82360                 }
82361                 // Otherwise, we can just return the node
82362                 return node;
82363             }
82364             switch (node.kind) {
82365                 case 261 /* ImportDeclaration */:
82366                     return visitImportDeclaration(node);
82367                 case 260 /* ImportEqualsDeclaration */:
82368                     return visitImportEqualsDeclaration(node);
82369                 case 266 /* ExportAssignment */:
82370                     return visitExportAssignment(node);
82371                 case 267 /* ExportDeclaration */:
82372                     return visitExportDeclaration(node);
82373                 default:
82374                     ts.Debug.fail("Unhandled ellided statement");
82375             }
82376         }
82377         /**
82378          * Specialized visitor that visits the immediate children of a namespace.
82379          *
82380          * @param node The node to visit.
82381          */
82382         function namespaceElementVisitor(node) {
82383             return saveStateAndInvoke(node, namespaceElementVisitorWorker);
82384         }
82385         /**
82386          * Specialized visitor that visits the immediate children of a namespace.
82387          *
82388          * @param node The node to visit.
82389          */
82390         function namespaceElementVisitorWorker(node) {
82391             if (node.kind === 267 /* ExportDeclaration */ ||
82392                 node.kind === 261 /* ImportDeclaration */ ||
82393                 node.kind === 262 /* ImportClause */ ||
82394                 (node.kind === 260 /* ImportEqualsDeclaration */ &&
82395                     node.moduleReference.kind === 272 /* ExternalModuleReference */)) {
82396                 // do not emit ES6 imports and exports since they are illegal inside a namespace
82397                 return undefined;
82398             }
82399             else if (node.transformFlags & 1 /* ContainsTypeScript */ || ts.hasSyntacticModifier(node, 1 /* Export */)) {
82400                 return visitTypeScript(node);
82401             }
82402             return node;
82403         }
82404         /**
82405          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
82406          *
82407          * @param node The node to visit.
82408          */
82409         function classElementVisitor(node) {
82410             return saveStateAndInvoke(node, classElementVisitorWorker);
82411         }
82412         /**
82413          * Specialized visitor that visits the immediate children of a class with TypeScript syntax.
82414          *
82415          * @param node The node to visit.
82416          */
82417         function classElementVisitorWorker(node) {
82418             switch (node.kind) {
82419                 case 166 /* Constructor */:
82420                     return visitConstructor(node);
82421                 case 163 /* PropertyDeclaration */:
82422                     // Property declarations are not TypeScript syntax, but they must be visited
82423                     // for the decorator transformation.
82424                     return visitPropertyDeclaration(node);
82425                 case 171 /* IndexSignature */:
82426                 case 167 /* GetAccessor */:
82427                 case 168 /* SetAccessor */:
82428                 case 165 /* MethodDeclaration */:
82429                     // Fallback to the default visit behavior.
82430                     return visitorWorker(node);
82431                 case 229 /* SemicolonClassElement */:
82432                     return node;
82433                 default:
82434                     return ts.Debug.failBadSyntaxKind(node);
82435             }
82436         }
82437         function modifierVisitor(node) {
82438             if (ts.modifierToFlag(node.kind) & 2270 /* TypeScriptModifier */) {
82439                 return undefined;
82440             }
82441             else if (currentNamespace && node.kind === 92 /* ExportKeyword */) {
82442                 return undefined;
82443             }
82444             return node;
82445         }
82446         /**
82447          * Branching visitor, visits a TypeScript syntax node.
82448          *
82449          * @param node The node to visit.
82450          */
82451         function visitTypeScript(node) {
82452             if (ts.isStatement(node) && ts.hasSyntacticModifier(node, 2 /* Ambient */)) {
82453                 // TypeScript ambient declarations are elided, but some comments may be preserved.
82454                 // See the implementation of `getLeadingComments` in comments.ts for more details.
82455                 return factory.createNotEmittedStatement(node);
82456             }
82457             switch (node.kind) {
82458                 case 92 /* ExportKeyword */:
82459                 case 87 /* DefaultKeyword */:
82460                     // ES6 export and default modifiers are elided when inside a namespace.
82461                     return currentNamespace ? undefined : node;
82462                 case 122 /* PublicKeyword */:
82463                 case 120 /* PrivateKeyword */:
82464                 case 121 /* ProtectedKeyword */:
82465                 case 125 /* AbstractKeyword */:
82466                 case 84 /* ConstKeyword */:
82467                 case 133 /* DeclareKeyword */:
82468                 case 142 /* ReadonlyKeyword */:
82469                 // TypeScript accessibility and readonly modifiers are elided
82470                 // falls through
82471                 case 178 /* ArrayType */:
82472                 case 179 /* TupleType */:
82473                 case 180 /* OptionalType */:
82474                 case 181 /* RestType */:
82475                 case 177 /* TypeLiteral */:
82476                 case 172 /* TypePredicate */:
82477                 case 159 /* TypeParameter */:
82478                 case 128 /* AnyKeyword */:
82479                 case 152 /* UnknownKeyword */:
82480                 case 131 /* BooleanKeyword */:
82481                 case 147 /* StringKeyword */:
82482                 case 144 /* NumberKeyword */:
82483                 case 141 /* NeverKeyword */:
82484                 case 113 /* VoidKeyword */:
82485                 case 148 /* SymbolKeyword */:
82486                 case 175 /* ConstructorType */:
82487                 case 174 /* FunctionType */:
82488                 case 176 /* TypeQuery */:
82489                 case 173 /* TypeReference */:
82490                 case 182 /* UnionType */:
82491                 case 183 /* IntersectionType */:
82492                 case 184 /* ConditionalType */:
82493                 case 186 /* ParenthesizedType */:
82494                 case 187 /* ThisType */:
82495                 case 188 /* TypeOperator */:
82496                 case 189 /* IndexedAccessType */:
82497                 case 190 /* MappedType */:
82498                 case 191 /* LiteralType */:
82499                 // TypeScript type nodes are elided.
82500                 // falls through
82501                 case 171 /* IndexSignature */:
82502                 // TypeScript index signatures are elided.
82503                 // falls through
82504                 case 161 /* Decorator */:
82505                 // TypeScript decorators are elided. They will be emitted as part of visitClassDeclaration.
82506                 // falls through
82507                 case 254 /* TypeAliasDeclaration */:
82508                     // TypeScript type-only declarations are elided.
82509                     return undefined;
82510                 case 163 /* PropertyDeclaration */:
82511                     // TypeScript property declarations are elided. However their names are still visited, and can potentially be retained if they could have sideeffects
82512                     return visitPropertyDeclaration(node);
82513                 case 259 /* NamespaceExportDeclaration */:
82514                     // TypeScript namespace export declarations are elided.
82515                     return undefined;
82516                 case 166 /* Constructor */:
82517                     return visitConstructor(node);
82518                 case 253 /* InterfaceDeclaration */:
82519                     // TypeScript interfaces are elided, but some comments may be preserved.
82520                     // See the implementation of `getLeadingComments` in comments.ts for more details.
82521                     return factory.createNotEmittedStatement(node);
82522                 case 252 /* ClassDeclaration */:
82523                     // This may be a class declaration with TypeScript syntax extensions.
82524                     //
82525                     // TypeScript class syntax extensions include:
82526                     // - decorators
82527                     // - optional `implements` heritage clause
82528                     // - parameter property assignments in the constructor
82529                     // - index signatures
82530                     // - method overload signatures
82531                     return visitClassDeclaration(node);
82532                 case 221 /* ClassExpression */:
82533                     // This may be a class expression with TypeScript syntax extensions.
82534                     //
82535                     // TypeScript class syntax extensions include:
82536                     // - decorators
82537                     // - optional `implements` heritage clause
82538                     // - parameter property assignments in the constructor
82539                     // - index signatures
82540                     // - method overload signatures
82541                     return visitClassExpression(node);
82542                 case 286 /* HeritageClause */:
82543                     // This may be a heritage clause with TypeScript syntax extensions.
82544                     //
82545                     // TypeScript heritage clause extensions include:
82546                     // - `implements` clause
82547                     return visitHeritageClause(node);
82548                 case 223 /* ExpressionWithTypeArguments */:
82549                     // TypeScript supports type arguments on an expression in an `extends` heritage clause.
82550                     return visitExpressionWithTypeArguments(node);
82551                 case 165 /* MethodDeclaration */:
82552                     // TypeScript method declarations may have decorators, modifiers
82553                     // or type annotations.
82554                     return visitMethodDeclaration(node);
82555                 case 167 /* GetAccessor */:
82556                     // Get Accessors can have TypeScript modifiers, decorators, and type annotations.
82557                     return visitGetAccessor(node);
82558                 case 168 /* SetAccessor */:
82559                     // Set Accessors can have TypeScript modifiers and type annotations.
82560                     return visitSetAccessor(node);
82561                 case 251 /* FunctionDeclaration */:
82562                     // Typescript function declarations can have modifiers, decorators, and type annotations.
82563                     return visitFunctionDeclaration(node);
82564                 case 208 /* FunctionExpression */:
82565                     // TypeScript function expressions can have modifiers and type annotations.
82566                     return visitFunctionExpression(node);
82567                 case 209 /* ArrowFunction */:
82568                     // TypeScript arrow functions can have modifiers and type annotations.
82569                     return visitArrowFunction(node);
82570                 case 160 /* Parameter */:
82571                     // This may be a parameter declaration with TypeScript syntax extensions.
82572                     //
82573                     // TypeScript parameter declaration syntax extensions include:
82574                     // - decorators
82575                     // - accessibility modifiers
82576                     // - the question mark (?) token for optional parameters
82577                     // - type annotations
82578                     // - this parameters
82579                     return visitParameter(node);
82580                 case 207 /* ParenthesizedExpression */:
82581                     // ParenthesizedExpressions are TypeScript if their expression is a
82582                     // TypeAssertion or AsExpression
82583                     return visitParenthesizedExpression(node);
82584                 case 206 /* TypeAssertionExpression */:
82585                 case 224 /* AsExpression */:
82586                     // TypeScript type assertions are removed, but their subtrees are preserved.
82587                     return visitAssertionExpression(node);
82588                 case 203 /* CallExpression */:
82589                     return visitCallExpression(node);
82590                 case 204 /* NewExpression */:
82591                     return visitNewExpression(node);
82592                 case 205 /* TaggedTemplateExpression */:
82593                     return visitTaggedTemplateExpression(node);
82594                 case 225 /* NonNullExpression */:
82595                     // TypeScript non-null expressions are removed, but their subtrees are preserved.
82596                     return visitNonNullExpression(node);
82597                 case 255 /* EnumDeclaration */:
82598                     // TypeScript enum declarations do not exist in ES6 and must be rewritten.
82599                     return visitEnumDeclaration(node);
82600                 case 232 /* VariableStatement */:
82601                     // TypeScript namespace exports for variable statements must be transformed.
82602                     return visitVariableStatement(node);
82603                 case 249 /* VariableDeclaration */:
82604                     return visitVariableDeclaration(node);
82605                 case 256 /* ModuleDeclaration */:
82606                     // TypeScript namespace declarations must be transformed.
82607                     return visitModuleDeclaration(node);
82608                 case 260 /* ImportEqualsDeclaration */:
82609                     // TypeScript namespace or external module import.
82610                     return visitImportEqualsDeclaration(node);
82611                 case 274 /* JsxSelfClosingElement */:
82612                     return visitJsxSelfClosingElement(node);
82613                 case 275 /* JsxOpeningElement */:
82614                     return visitJsxJsxOpeningElement(node);
82615                 default:
82616                     // node contains some other TypeScript syntax
82617                     return ts.visitEachChild(node, visitor, context);
82618             }
82619         }
82620         function visitSourceFile(node) {
82621             var alwaysStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") &&
82622                 !(ts.isExternalModule(node) && moduleKind >= ts.ModuleKind.ES2015) &&
82623                 !ts.isJsonSourceFile(node);
82624             return factory.updateSourceFile(node, ts.visitLexicalEnvironment(node.statements, sourceElementVisitor, context, /*start*/ 0, alwaysStrict));
82625         }
82626         /**
82627          * Tests whether we should emit a __decorate call for a class declaration.
82628          */
82629         function shouldEmitDecorateCallForClass(node) {
82630             if (node.decorators && node.decorators.length > 0) {
82631                 return true;
82632             }
82633             var constructor = ts.getFirstConstructorWithBody(node);
82634             if (constructor) {
82635                 return ts.forEach(constructor.parameters, shouldEmitDecorateCallForParameter);
82636             }
82637             return false;
82638         }
82639         /**
82640          * Tests whether we should emit a __decorate call for a parameter declaration.
82641          */
82642         function shouldEmitDecorateCallForParameter(parameter) {
82643             return parameter.decorators !== undefined && parameter.decorators.length > 0;
82644         }
82645         function getClassFacts(node, staticProperties) {
82646             var facts = 0 /* None */;
82647             if (ts.some(staticProperties))
82648                 facts |= 1 /* HasStaticInitializedProperties */;
82649             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
82650             if (extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */)
82651                 facts |= 64 /* IsDerivedClass */;
82652             if (shouldEmitDecorateCallForClass(node))
82653                 facts |= 2 /* HasConstructorDecorators */;
82654             if (ts.childIsDecorated(node))
82655                 facts |= 4 /* HasMemberDecorators */;
82656             if (isExportOfNamespace(node))
82657                 facts |= 8 /* IsExportOfNamespace */;
82658             else if (isDefaultExternalModuleExport(node))
82659                 facts |= 32 /* IsDefaultExternalExport */;
82660             else if (isNamedExternalModuleExport(node))
82661                 facts |= 16 /* IsNamedExternalExport */;
82662             if (languageVersion <= 1 /* ES5 */ && (facts & 7 /* MayNeedImmediatelyInvokedFunctionExpression */))
82663                 facts |= 128 /* UseImmediatelyInvokedFunctionExpression */;
82664             return facts;
82665         }
82666         function hasTypeScriptClassSyntax(node) {
82667             return !!(node.transformFlags & 2048 /* ContainsTypeScriptClassSyntax */);
82668         }
82669         function isClassLikeDeclarationWithTypeScriptSyntax(node) {
82670             return ts.some(node.decorators)
82671                 || ts.some(node.typeParameters)
82672                 || ts.some(node.heritageClauses, hasTypeScriptClassSyntax)
82673                 || ts.some(node.members, hasTypeScriptClassSyntax);
82674         }
82675         function visitClassDeclaration(node) {
82676             if (!isClassLikeDeclarationWithTypeScriptSyntax(node) && !(currentNamespace && ts.hasSyntacticModifier(node, 1 /* Export */))) {
82677                 return ts.visitEachChild(node, visitor, context);
82678             }
82679             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
82680             var facts = getClassFacts(node, staticProperties);
82681             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
82682                 context.startLexicalEnvironment();
82683             }
82684             var name = node.name || (facts & 5 /* NeedsName */ ? factory.getGeneratedNameForNode(node) : undefined);
82685             var classStatement = facts & 2 /* HasConstructorDecorators */
82686                 ? createClassDeclarationHeadWithDecorators(node, name)
82687                 : createClassDeclarationHeadWithoutDecorators(node, name, facts);
82688             var statements = [classStatement];
82689             // Write any decorators of the node.
82690             addClassElementDecorationStatements(statements, node, /*isStatic*/ false);
82691             addClassElementDecorationStatements(statements, node, /*isStatic*/ true);
82692             addConstructorDecorationStatement(statements, node);
82693             if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */) {
82694                 // When we emit a TypeScript class down to ES5, we must wrap it in an IIFE so that the
82695                 // 'es2015' transformer can properly nest static initializers and decorators. The result
82696                 // looks something like:
82697                 //
82698                 //  var C = function () {
82699                 //      class C {
82700                 //      }
82701                 //      C.static_prop = 1;
82702                 //      return C;
82703                 //  }();
82704                 //
82705                 var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentSourceFile.text, node.members.end), 19 /* CloseBraceToken */);
82706                 var localName = factory.getInternalName(node);
82707                 // The following partially-emitted expression exists purely to align our sourcemap
82708                 // emit with the original emitter.
82709                 var outer = factory.createPartiallyEmittedExpression(localName);
82710                 ts.setTextRangeEnd(outer, closingBraceLocation.end);
82711                 ts.setEmitFlags(outer, 1536 /* NoComments */);
82712                 var statement = factory.createReturnStatement(outer);
82713                 ts.setTextRangePos(statement, closingBraceLocation.pos);
82714                 ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
82715                 statements.push(statement);
82716                 ts.insertStatementsAfterStandardPrologue(statements, context.endLexicalEnvironment());
82717                 var iife = factory.createImmediatelyInvokedArrowFunction(statements);
82718                 ts.setEmitFlags(iife, 33554432 /* TypeScriptClassWrapper */);
82719                 var varStatement = factory.createVariableStatement(
82720                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
82721                     factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ false), 
82722                     /*exclamationToken*/ undefined, 
82723                     /*type*/ undefined, iife)
82724                 ]));
82725                 ts.setOriginalNode(varStatement, node);
82726                 ts.setCommentRange(varStatement, node);
82727                 ts.setSourceMapRange(varStatement, ts.moveRangePastDecorators(node));
82728                 ts.startOnNewLine(varStatement);
82729                 statements = [varStatement];
82730             }
82731             // If the class is exported as part of a TypeScript namespace, emit the namespace export.
82732             // Otherwise, if the class was exported at the top level and was decorated, emit an export
82733             // declaration or export default for the class.
82734             if (facts & 8 /* IsExportOfNamespace */) {
82735                 addExportMemberAssignment(statements, node);
82736             }
82737             else if (facts & 128 /* UseImmediatelyInvokedFunctionExpression */ || facts & 2 /* HasConstructorDecorators */) {
82738                 if (facts & 32 /* IsDefaultExternalExport */) {
82739                     statements.push(factory.createExportDefault(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
82740                 }
82741                 else if (facts & 16 /* IsNamedExternalExport */) {
82742                     statements.push(factory.createExternalModuleExport(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true)));
82743                 }
82744             }
82745             if (statements.length > 1) {
82746                 // Add a DeclarationMarker as a marker for the end of the declaration
82747                 statements.push(factory.createEndOfDeclarationMarker(node));
82748                 ts.setEmitFlags(classStatement, ts.getEmitFlags(classStatement) | 4194304 /* HasEndOfDeclarationMarker */);
82749             }
82750             return ts.singleOrMany(statements);
82751         }
82752         /**
82753          * Transforms a non-decorated class declaration and appends the resulting statements.
82754          *
82755          * @param node A ClassDeclaration node.
82756          * @param name The name of the class.
82757          * @param facts Precomputed facts about the class.
82758          */
82759         function createClassDeclarationHeadWithoutDecorators(node, name, facts) {
82760             //  ${modifiers} class ${name} ${heritageClauses} {
82761             //      ${members}
82762             //  }
82763             // we do not emit modifiers on the declaration if we are emitting an IIFE
82764             var modifiers = !(facts & 128 /* UseImmediatelyInvokedFunctionExpression */)
82765                 ? ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier)
82766                 : undefined;
82767             var classDeclaration = factory.createClassDeclaration(
82768             /*decorators*/ undefined, modifiers, name, 
82769             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
82770             // To better align with the old emitter, we should not emit a trailing source map
82771             // entry if the class has static properties.
82772             var emitFlags = ts.getEmitFlags(node);
82773             if (facts & 1 /* HasStaticInitializedProperties */) {
82774                 emitFlags |= 32 /* NoTrailingSourceMap */;
82775             }
82776             ts.setTextRange(classDeclaration, node);
82777             ts.setOriginalNode(classDeclaration, node);
82778             ts.setEmitFlags(classDeclaration, emitFlags);
82779             return classDeclaration;
82780         }
82781         /**
82782          * Transforms a decorated class declaration and appends the resulting statements. If
82783          * the class requires an alias to avoid issues with double-binding, the alias is returned.
82784          */
82785         function createClassDeclarationHeadWithDecorators(node, name) {
82786             // When we emit an ES6 class that has a class decorator, we must tailor the
82787             // emit to certain specific cases.
82788             //
82789             // In the simplest case, we emit the class declaration as a let declaration, and
82790             // evaluate decorators after the close of the class body:
82791             //
82792             //  [Example 1]
82793             //  ---------------------------------------------------------------------
82794             //  TypeScript                      | Javascript
82795             //  ---------------------------------------------------------------------
82796             //  @dec                            | let C = class C {
82797             //  class C {                       | }
82798             //  }                               | C = __decorate([dec], C);
82799             //  ---------------------------------------------------------------------
82800             //  @dec                            | let C = class C {
82801             //  export class C {                | }
82802             //  }                               | C = __decorate([dec], C);
82803             //                                  | export { C };
82804             //  ---------------------------------------------------------------------
82805             //
82806             // If a class declaration contains a reference to itself *inside* of the class body,
82807             // this introduces two bindings to the class: One outside of the class body, and one
82808             // inside of the class body. If we apply decorators as in [Example 1] above, there
82809             // is the possibility that the decorator `dec` will return a new value for the
82810             // constructor, which would result in the binding inside of the class no longer
82811             // pointing to the same reference as the binding outside of the class.
82812             //
82813             // As a result, we must instead rewrite all references to the class *inside* of the
82814             // class body to instead point to a local temporary alias for the class:
82815             //
82816             //  [Example 2]
82817             //  ---------------------------------------------------------------------
82818             //  TypeScript                      | Javascript
82819             //  ---------------------------------------------------------------------
82820             //  @dec                            | let C = C_1 = class C {
82821             //  class C {                       |   static x() { return C_1.y; }
82822             //    static x() { return C.y; }    | }
82823             //    static y = 1;                 | C.y = 1;
82824             //  }                               | C = C_1 = __decorate([dec], C);
82825             //                                  | var C_1;
82826             //  ---------------------------------------------------------------------
82827             //  @dec                            | let C = class C {
82828             //  export class C {                |   static x() { return C_1.y; }
82829             //    static x() { return C.y; }    | }
82830             //    static y = 1;                 | C.y = 1;
82831             //  }                               | C = C_1 = __decorate([dec], C);
82832             //                                  | export { C };
82833             //                                  | var C_1;
82834             //  ---------------------------------------------------------------------
82835             //
82836             // If a class declaration is the default export of a module, we instead emit
82837             // the export after the decorated declaration:
82838             //
82839             //  [Example 3]
82840             //  ---------------------------------------------------------------------
82841             //  TypeScript                      | Javascript
82842             //  ---------------------------------------------------------------------
82843             //  @dec                            | let default_1 = class {
82844             //  export default class {          | }
82845             //  }                               | default_1 = __decorate([dec], default_1);
82846             //                                  | export default default_1;
82847             //  ---------------------------------------------------------------------
82848             //  @dec                            | let C = class C {
82849             //  export default class C {        | }
82850             //  }                               | C = __decorate([dec], C);
82851             //                                  | export default C;
82852             //  ---------------------------------------------------------------------
82853             //
82854             // If the class declaration is the default export and a reference to itself
82855             // inside of the class body, we must emit both an alias for the class *and*
82856             // move the export after the declaration:
82857             //
82858             //  [Example 4]
82859             //  ---------------------------------------------------------------------
82860             //  TypeScript                      | Javascript
82861             //  ---------------------------------------------------------------------
82862             //  @dec                            | let C = class C {
82863             //  export default class C {        |   static x() { return C_1.y; }
82864             //    static x() { return C.y; }    | }
82865             //    static y = 1;                 | C.y = 1;
82866             //  }                               | C = C_1 = __decorate([dec], C);
82867             //                                  | export default C;
82868             //                                  | var C_1;
82869             //  ---------------------------------------------------------------------
82870             //
82871             var location = ts.moveRangePastDecorators(node);
82872             var classAlias = getClassAliasIfNeeded(node);
82873             var declName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
82874             //  ... = class ${name} ${heritageClauses} {
82875             //      ${members}
82876             //  }
82877             var heritageClauses = ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause);
82878             var members = transformClassMembers(node);
82879             var classExpression = factory.createClassExpression(/*decorators*/ undefined, /*modifiers*/ undefined, name, /*typeParameters*/ undefined, heritageClauses, members);
82880             ts.setOriginalNode(classExpression, node);
82881             ts.setTextRange(classExpression, location);
82882             //  let ${name} = ${classExpression} where name is either declaredName if the class doesn't contain self-reference
82883             //                                         or decoratedClassAlias if the class contain self-reference.
82884             var statement = factory.createVariableStatement(
82885             /*modifiers*/ undefined, factory.createVariableDeclarationList([
82886                 factory.createVariableDeclaration(declName, 
82887                 /*exclamationToken*/ undefined, 
82888                 /*type*/ undefined, classAlias ? factory.createAssignment(classAlias, classExpression) : classExpression)
82889             ], 1 /* Let */));
82890             ts.setOriginalNode(statement, node);
82891             ts.setTextRange(statement, location);
82892             ts.setCommentRange(statement, node);
82893             return statement;
82894         }
82895         function visitClassExpression(node) {
82896             if (!isClassLikeDeclarationWithTypeScriptSyntax(node)) {
82897                 return ts.visitEachChild(node, visitor, context);
82898             }
82899             var classExpression = factory.createClassExpression(
82900             /*decorators*/ undefined, 
82901             /*modifiers*/ undefined, node.name, 
82902             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node));
82903             ts.setOriginalNode(classExpression, node);
82904             ts.setTextRange(classExpression, node);
82905             return classExpression;
82906         }
82907         /**
82908          * Transforms the members of a class.
82909          *
82910          * @param node The current class.
82911          */
82912         function transformClassMembers(node) {
82913             var members = [];
82914             var constructor = ts.getFirstConstructorWithBody(node);
82915             var parametersWithPropertyAssignments = constructor &&
82916                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
82917             if (parametersWithPropertyAssignments) {
82918                 for (var _i = 0, parametersWithPropertyAssignments_1 = parametersWithPropertyAssignments; _i < parametersWithPropertyAssignments_1.length; _i++) {
82919                     var parameter = parametersWithPropertyAssignments_1[_i];
82920                     if (ts.isIdentifier(parameter.name)) {
82921                         members.push(ts.setOriginalNode(factory.createPropertyDeclaration(
82922                         /*decorators*/ undefined, 
82923                         /*modifiers*/ undefined, parameter.name, 
82924                         /*questionOrExclamationToken*/ undefined, 
82925                         /*type*/ undefined, 
82926                         /*initializer*/ undefined), parameter));
82927                     }
82928                 }
82929             }
82930             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
82931             return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
82932         }
82933         /**
82934          * Gets either the static or instance members of a class that are decorated, or have
82935          * parameters that are decorated.
82936          *
82937          * @param node The class containing the member.
82938          * @param isStatic A value indicating whether to retrieve static or instance members of
82939          *                 the class.
82940          */
82941         function getDecoratedClassElements(node, isStatic) {
82942             return ts.filter(node.members, isStatic ? function (m) { return isStaticDecoratedClassElement(m, node); } : function (m) { return isInstanceDecoratedClassElement(m, node); });
82943         }
82944         /**
82945          * Determines whether a class member is a static member of a class that is decorated, or
82946          * has parameters that are decorated.
82947          *
82948          * @param member The class member.
82949          */
82950         function isStaticDecoratedClassElement(member, parent) {
82951             return isDecoratedClassElement(member, /*isStatic*/ true, parent);
82952         }
82953         /**
82954          * Determines whether a class member is an instance member of a class that is decorated,
82955          * or has parameters that are decorated.
82956          *
82957          * @param member The class member.
82958          */
82959         function isInstanceDecoratedClassElement(member, parent) {
82960             return isDecoratedClassElement(member, /*isStatic*/ false, parent);
82961         }
82962         /**
82963          * Determines whether a class member is either a static or an instance member of a class
82964          * that is decorated, or has parameters that are decorated.
82965          *
82966          * @param member The class member.
82967          */
82968         function isDecoratedClassElement(member, isStatic, parent) {
82969             return ts.nodeOrChildIsDecorated(member, parent)
82970                 && isStatic === ts.hasSyntacticModifier(member, 32 /* Static */);
82971         }
82972         /**
82973          * Gets an array of arrays of decorators for the parameters of a function-like node.
82974          * The offset into the result array should correspond to the offset of the parameter.
82975          *
82976          * @param node The function-like node.
82977          */
82978         function getDecoratorsOfParameters(node) {
82979             var decorators;
82980             if (node) {
82981                 var parameters = node.parameters;
82982                 var firstParameterIsThis = parameters.length > 0 && ts.parameterIsThisKeyword(parameters[0]);
82983                 var firstParameterOffset = firstParameterIsThis ? 1 : 0;
82984                 var numParameters = firstParameterIsThis ? parameters.length - 1 : parameters.length;
82985                 for (var i = 0; i < numParameters; i++) {
82986                     var parameter = parameters[i + firstParameterOffset];
82987                     if (decorators || parameter.decorators) {
82988                         if (!decorators) {
82989                             decorators = new Array(numParameters);
82990                         }
82991                         decorators[i] = parameter.decorators;
82992                     }
82993                 }
82994             }
82995             return decorators;
82996         }
82997         /**
82998          * Gets an AllDecorators object containing the decorators for the class and the decorators for the
82999          * parameters of the constructor of the class.
83000          *
83001          * @param node The class node.
83002          */
83003         function getAllDecoratorsOfConstructor(node) {
83004             var decorators = node.decorators;
83005             var parameters = getDecoratorsOfParameters(ts.getFirstConstructorWithBody(node));
83006             if (!decorators && !parameters) {
83007                 return undefined;
83008             }
83009             return {
83010                 decorators: decorators,
83011                 parameters: parameters
83012             };
83013         }
83014         /**
83015          * Gets an AllDecorators object containing the decorators for the member and its parameters.
83016          *
83017          * @param node The class node that contains the member.
83018          * @param member The class member.
83019          */
83020         function getAllDecoratorsOfClassElement(node, member) {
83021             switch (member.kind) {
83022                 case 167 /* GetAccessor */:
83023                 case 168 /* SetAccessor */:
83024                     return getAllDecoratorsOfAccessors(node, member);
83025                 case 165 /* MethodDeclaration */:
83026                     return getAllDecoratorsOfMethod(member);
83027                 case 163 /* PropertyDeclaration */:
83028                     return getAllDecoratorsOfProperty(member);
83029                 default:
83030                     return undefined;
83031             }
83032         }
83033         /**
83034          * Gets an AllDecorators object containing the decorators for the accessor and its parameters.
83035          *
83036          * @param node The class node that contains the accessor.
83037          * @param accessor The class accessor member.
83038          */
83039         function getAllDecoratorsOfAccessors(node, accessor) {
83040             if (!accessor.body) {
83041                 return undefined;
83042             }
83043             var _a = ts.getAllAccessorDeclarations(node.members, accessor), firstAccessor = _a.firstAccessor, secondAccessor = _a.secondAccessor, setAccessor = _a.setAccessor;
83044             var firstAccessorWithDecorators = firstAccessor.decorators ? firstAccessor : secondAccessor && secondAccessor.decorators ? secondAccessor : undefined;
83045             if (!firstAccessorWithDecorators || accessor !== firstAccessorWithDecorators) {
83046                 return undefined;
83047             }
83048             var decorators = firstAccessorWithDecorators.decorators;
83049             var parameters = getDecoratorsOfParameters(setAccessor);
83050             if (!decorators && !parameters) {
83051                 return undefined;
83052             }
83053             return { decorators: decorators, parameters: parameters };
83054         }
83055         /**
83056          * Gets an AllDecorators object containing the decorators for the method and its parameters.
83057          *
83058          * @param method The class method member.
83059          */
83060         function getAllDecoratorsOfMethod(method) {
83061             if (!method.body) {
83062                 return undefined;
83063             }
83064             var decorators = method.decorators;
83065             var parameters = getDecoratorsOfParameters(method);
83066             if (!decorators && !parameters) {
83067                 return undefined;
83068             }
83069             return { decorators: decorators, parameters: parameters };
83070         }
83071         /**
83072          * Gets an AllDecorators object containing the decorators for the property.
83073          *
83074          * @param property The class property member.
83075          */
83076         function getAllDecoratorsOfProperty(property) {
83077             var decorators = property.decorators;
83078             if (!decorators) {
83079                 return undefined;
83080             }
83081             return { decorators: decorators };
83082         }
83083         /**
83084          * Transforms all of the decorators for a declaration into an array of expressions.
83085          *
83086          * @param node The declaration node.
83087          * @param allDecorators An object containing all of the decorators for the declaration.
83088          */
83089         function transformAllDecoratorsOfDeclaration(node, container, allDecorators) {
83090             if (!allDecorators) {
83091                 return undefined;
83092             }
83093             var decoratorExpressions = [];
83094             ts.addRange(decoratorExpressions, ts.map(allDecorators.decorators, transformDecorator));
83095             ts.addRange(decoratorExpressions, ts.flatMap(allDecorators.parameters, transformDecoratorsOfParameter));
83096             addTypeMetadata(node, container, decoratorExpressions);
83097             return decoratorExpressions;
83098         }
83099         /**
83100          * Generates statements used to apply decorators to either the static or instance members
83101          * of a class.
83102          *
83103          * @param node The class node.
83104          * @param isStatic A value indicating whether to generate statements for static or
83105          *                 instance members.
83106          */
83107         function addClassElementDecorationStatements(statements, node, isStatic) {
83108             ts.addRange(statements, ts.map(generateClassElementDecorationExpressions(node, isStatic), expressionToStatement));
83109         }
83110         /**
83111          * Generates expressions used to apply decorators to either the static or instance members
83112          * of a class.
83113          *
83114          * @param node The class node.
83115          * @param isStatic A value indicating whether to generate expressions for static or
83116          *                 instance members.
83117          */
83118         function generateClassElementDecorationExpressions(node, isStatic) {
83119             var members = getDecoratedClassElements(node, isStatic);
83120             var expressions;
83121             for (var _i = 0, members_6 = members; _i < members_6.length; _i++) {
83122                 var member = members_6[_i];
83123                 var expression = generateClassElementDecorationExpression(node, member);
83124                 if (expression) {
83125                     if (!expressions) {
83126                         expressions = [expression];
83127                     }
83128                     else {
83129                         expressions.push(expression);
83130                     }
83131                 }
83132             }
83133             return expressions;
83134         }
83135         /**
83136          * Generates an expression used to evaluate class element decorators at runtime.
83137          *
83138          * @param node The class node that contains the member.
83139          * @param member The class member.
83140          */
83141         function generateClassElementDecorationExpression(node, member) {
83142             var allDecorators = getAllDecoratorsOfClassElement(node, member);
83143             var decoratorExpressions = transformAllDecoratorsOfDeclaration(member, node, allDecorators);
83144             if (!decoratorExpressions) {
83145                 return undefined;
83146             }
83147             // Emit the call to __decorate. Given the following:
83148             //
83149             //   class C {
83150             //     @dec method(@dec2 x) {}
83151             //     @dec get accessor() {}
83152             //     @dec prop;
83153             //   }
83154             //
83155             // The emit for a method is:
83156             //
83157             //   __decorate([
83158             //       dec,
83159             //       __param(0, dec2),
83160             //       __metadata("design:type", Function),
83161             //       __metadata("design:paramtypes", [Object]),
83162             //       __metadata("design:returntype", void 0)
83163             //   ], C.prototype, "method", null);
83164             //
83165             // The emit for an accessor is:
83166             //
83167             //   __decorate([
83168             //       dec
83169             //   ], C.prototype, "accessor", null);
83170             //
83171             // The emit for a property is:
83172             //
83173             //   __decorate([
83174             //       dec
83175             //   ], C.prototype, "prop");
83176             //
83177             var prefix = getClassMemberPrefix(node, member);
83178             var memberName = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ true);
83179             var descriptor = languageVersion > 0 /* ES3 */
83180                 ? member.kind === 163 /* PropertyDeclaration */
83181                     // We emit `void 0` here to indicate to `__decorate` that it can invoke `Object.defineProperty` directly, but that it
83182                     // should not invoke `Object.getOwnPropertyDescriptor`.
83183                     ? factory.createVoidZero()
83184                     // We emit `null` here to indicate to `__decorate` that it can invoke `Object.getOwnPropertyDescriptor` directly.
83185                     // We have this extra argument here so that we can inject an explicit property descriptor at a later date.
83186                     : factory.createNull()
83187                 : undefined;
83188             var helper = emitHelpers().createDecorateHelper(decoratorExpressions, prefix, memberName, descriptor);
83189             ts.setTextRange(helper, ts.moveRangePastDecorators(member));
83190             ts.setEmitFlags(helper, 1536 /* NoComments */);
83191             return helper;
83192         }
83193         /**
83194          * Generates a __decorate helper call for a class constructor.
83195          *
83196          * @param node The class node.
83197          */
83198         function addConstructorDecorationStatement(statements, node) {
83199             var expression = generateConstructorDecorationExpression(node);
83200             if (expression) {
83201                 statements.push(ts.setOriginalNode(factory.createExpressionStatement(expression), node));
83202             }
83203         }
83204         /**
83205          * Generates a __decorate helper call for a class constructor.
83206          *
83207          * @param node The class node.
83208          */
83209         function generateConstructorDecorationExpression(node) {
83210             var allDecorators = getAllDecoratorsOfConstructor(node);
83211             var decoratorExpressions = transformAllDecoratorsOfDeclaration(node, node, allDecorators);
83212             if (!decoratorExpressions) {
83213                 return undefined;
83214             }
83215             var classAlias = classAliases && classAliases[ts.getOriginalNodeId(node)];
83216             var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
83217             var decorate = emitHelpers().createDecorateHelper(decoratorExpressions, localName);
83218             var expression = factory.createAssignment(localName, classAlias ? factory.createAssignment(classAlias, decorate) : decorate);
83219             ts.setEmitFlags(expression, 1536 /* NoComments */);
83220             ts.setSourceMapRange(expression, ts.moveRangePastDecorators(node));
83221             return expression;
83222         }
83223         /**
83224          * Transforms a decorator into an expression.
83225          *
83226          * @param decorator The decorator node.
83227          */
83228         function transformDecorator(decorator) {
83229             return ts.visitNode(decorator.expression, visitor, ts.isExpression);
83230         }
83231         /**
83232          * Transforms the decorators of a parameter.
83233          *
83234          * @param decorators The decorators for the parameter at the provided offset.
83235          * @param parameterOffset The offset of the parameter.
83236          */
83237         function transformDecoratorsOfParameter(decorators, parameterOffset) {
83238             var expressions;
83239             if (decorators) {
83240                 expressions = [];
83241                 for (var _i = 0, decorators_1 = decorators; _i < decorators_1.length; _i++) {
83242                     var decorator = decorators_1[_i];
83243                     var helper = emitHelpers().createParamHelper(transformDecorator(decorator), parameterOffset);
83244                     ts.setTextRange(helper, decorator.expression);
83245                     ts.setEmitFlags(helper, 1536 /* NoComments */);
83246                     expressions.push(helper);
83247                 }
83248             }
83249             return expressions;
83250         }
83251         /**
83252          * Adds optional type metadata for a declaration.
83253          *
83254          * @param node The declaration node.
83255          * @param decoratorExpressions The destination array to which to add new decorator expressions.
83256          */
83257         function addTypeMetadata(node, container, decoratorExpressions) {
83258             if (USE_NEW_TYPE_METADATA_FORMAT) {
83259                 addNewTypeMetadata(node, container, decoratorExpressions);
83260             }
83261             else {
83262                 addOldTypeMetadata(node, container, decoratorExpressions);
83263             }
83264         }
83265         function addOldTypeMetadata(node, container, decoratorExpressions) {
83266             if (compilerOptions.emitDecoratorMetadata) {
83267                 if (shouldAddTypeMetadata(node)) {
83268                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:type", serializeTypeOfNode(node)));
83269                 }
83270                 if (shouldAddParamTypesMetadata(node)) {
83271                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:paramtypes", serializeParameterTypesOfNode(node, container)));
83272                 }
83273                 if (shouldAddReturnTypeMetadata(node)) {
83274                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:returntype", serializeReturnTypeOfNode(node)));
83275                 }
83276             }
83277         }
83278         function addNewTypeMetadata(node, container, decoratorExpressions) {
83279             if (compilerOptions.emitDecoratorMetadata) {
83280                 var properties = void 0;
83281                 if (shouldAddTypeMetadata(node)) {
83282                     (properties || (properties = [])).push(factory.createPropertyAssignment("type", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeTypeOfNode(node))));
83283                 }
83284                 if (shouldAddParamTypesMetadata(node)) {
83285                     (properties || (properties = [])).push(factory.createPropertyAssignment("paramTypes", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeParameterTypesOfNode(node, container))));
83286                 }
83287                 if (shouldAddReturnTypeMetadata(node)) {
83288                     (properties || (properties = [])).push(factory.createPropertyAssignment("returnType", factory.createArrowFunction(/*modifiers*/ undefined, /*typeParameters*/ undefined, [], /*type*/ undefined, factory.createToken(38 /* EqualsGreaterThanToken */), serializeReturnTypeOfNode(node))));
83289                 }
83290                 if (properties) {
83291                     decoratorExpressions.push(emitHelpers().createMetadataHelper("design:typeinfo", factory.createObjectLiteralExpression(properties, /*multiLine*/ true)));
83292                 }
83293             }
83294         }
83295         /**
83296          * Determines whether to emit the "design:type" metadata based on the node's kind.
83297          * The caller should have already tested whether the node has decorators and whether the
83298          * emitDecoratorMetadata compiler option is set.
83299          *
83300          * @param node The node to test.
83301          */
83302         function shouldAddTypeMetadata(node) {
83303             var kind = node.kind;
83304             return kind === 165 /* MethodDeclaration */
83305                 || kind === 167 /* GetAccessor */
83306                 || kind === 168 /* SetAccessor */
83307                 || kind === 163 /* PropertyDeclaration */;
83308         }
83309         /**
83310          * Determines whether to emit the "design:returntype" metadata based on the node's kind.
83311          * The caller should have already tested whether the node has decorators and whether the
83312          * emitDecoratorMetadata compiler option is set.
83313          *
83314          * @param node The node to test.
83315          */
83316         function shouldAddReturnTypeMetadata(node) {
83317             return node.kind === 165 /* MethodDeclaration */;
83318         }
83319         /**
83320          * Determines whether to emit the "design:paramtypes" metadata based on the node's kind.
83321          * The caller should have already tested whether the node has decorators and whether the
83322          * emitDecoratorMetadata compiler option is set.
83323          *
83324          * @param node The node to test.
83325          */
83326         function shouldAddParamTypesMetadata(node) {
83327             switch (node.kind) {
83328                 case 252 /* ClassDeclaration */:
83329                 case 221 /* ClassExpression */:
83330                     return ts.getFirstConstructorWithBody(node) !== undefined;
83331                 case 165 /* MethodDeclaration */:
83332                 case 167 /* GetAccessor */:
83333                 case 168 /* SetAccessor */:
83334                     return true;
83335             }
83336             return false;
83337         }
83338         function getAccessorTypeNode(node) {
83339             var accessors = resolver.getAllAccessorDeclarations(node);
83340             return accessors.setAccessor && ts.getSetAccessorTypeAnnotationNode(accessors.setAccessor)
83341                 || accessors.getAccessor && ts.getEffectiveReturnTypeNode(accessors.getAccessor);
83342         }
83343         /**
83344          * Serializes the type of a node for use with decorator type metadata.
83345          *
83346          * @param node The node that should have its type serialized.
83347          */
83348         function serializeTypeOfNode(node) {
83349             switch (node.kind) {
83350                 case 163 /* PropertyDeclaration */:
83351                 case 160 /* Parameter */:
83352                     return serializeTypeNode(node.type);
83353                 case 168 /* SetAccessor */:
83354                 case 167 /* GetAccessor */:
83355                     return serializeTypeNode(getAccessorTypeNode(node));
83356                 case 252 /* ClassDeclaration */:
83357                 case 221 /* ClassExpression */:
83358                 case 165 /* MethodDeclaration */:
83359                     return factory.createIdentifier("Function");
83360                 default:
83361                     return factory.createVoidZero();
83362             }
83363         }
83364         /**
83365          * Serializes the types of the parameters of a node for use with decorator type metadata.
83366          *
83367          * @param node The node that should have its parameter types serialized.
83368          */
83369         function serializeParameterTypesOfNode(node, container) {
83370             var valueDeclaration = ts.isClassLike(node)
83371                 ? ts.getFirstConstructorWithBody(node)
83372                 : ts.isFunctionLike(node) && ts.nodeIsPresent(node.body)
83373                     ? node
83374                     : undefined;
83375             var expressions = [];
83376             if (valueDeclaration) {
83377                 var parameters = getParametersOfDecoratedDeclaration(valueDeclaration, container);
83378                 var numParameters = parameters.length;
83379                 for (var i = 0; i < numParameters; i++) {
83380                     var parameter = parameters[i];
83381                     if (i === 0 && ts.isIdentifier(parameter.name) && parameter.name.escapedText === "this") {
83382                         continue;
83383                     }
83384                     if (parameter.dotDotDotToken) {
83385                         expressions.push(serializeTypeNode(ts.getRestParameterElementType(parameter.type)));
83386                     }
83387                     else {
83388                         expressions.push(serializeTypeOfNode(parameter));
83389                     }
83390                 }
83391             }
83392             return factory.createArrayLiteralExpression(expressions);
83393         }
83394         function getParametersOfDecoratedDeclaration(node, container) {
83395             if (container && node.kind === 167 /* GetAccessor */) {
83396                 var setAccessor = ts.getAllAccessorDeclarations(container.members, node).setAccessor;
83397                 if (setAccessor) {
83398                     return setAccessor.parameters;
83399                 }
83400             }
83401             return node.parameters;
83402         }
83403         /**
83404          * Serializes the return type of a node for use with decorator type metadata.
83405          *
83406          * @param node The node that should have its return type serialized.
83407          */
83408         function serializeReturnTypeOfNode(node) {
83409             if (ts.isFunctionLike(node) && node.type) {
83410                 return serializeTypeNode(node.type);
83411             }
83412             else if (ts.isAsyncFunction(node)) {
83413                 return factory.createIdentifier("Promise");
83414             }
83415             return factory.createVoidZero();
83416         }
83417         /**
83418          * Serializes a type node for use with decorator type metadata.
83419          *
83420          * Types are serialized in the following fashion:
83421          * - Void types point to "undefined" (e.g. "void 0")
83422          * - Function and Constructor types point to the global "Function" constructor.
83423          * - Interface types with a call or construct signature types point to the global
83424          *   "Function" constructor.
83425          * - Array and Tuple types point to the global "Array" constructor.
83426          * - Type predicates and booleans point to the global "Boolean" constructor.
83427          * - String literal types and strings point to the global "String" constructor.
83428          * - Enum and number types point to the global "Number" constructor.
83429          * - Symbol types point to the global "Symbol" constructor.
83430          * - Type references to classes (or class-like variables) point to the constructor for the class.
83431          * - Anything else points to the global "Object" constructor.
83432          *
83433          * @param node The type node to serialize.
83434          */
83435         function serializeTypeNode(node) {
83436             if (node === undefined) {
83437                 return factory.createIdentifier("Object");
83438             }
83439             switch (node.kind) {
83440                 case 113 /* VoidKeyword */:
83441                 case 150 /* UndefinedKeyword */:
83442                 case 141 /* NeverKeyword */:
83443                     return factory.createVoidZero();
83444                 case 186 /* ParenthesizedType */:
83445                     return serializeTypeNode(node.type);
83446                 case 174 /* FunctionType */:
83447                 case 175 /* ConstructorType */:
83448                     return factory.createIdentifier("Function");
83449                 case 178 /* ArrayType */:
83450                 case 179 /* TupleType */:
83451                     return factory.createIdentifier("Array");
83452                 case 172 /* TypePredicate */:
83453                 case 131 /* BooleanKeyword */:
83454                     return factory.createIdentifier("Boolean");
83455                 case 147 /* StringKeyword */:
83456                     return factory.createIdentifier("String");
83457                 case 145 /* ObjectKeyword */:
83458                     return factory.createIdentifier("Object");
83459                 case 191 /* LiteralType */:
83460                     switch (node.literal.kind) {
83461                         case 10 /* StringLiteral */:
83462                         case 14 /* NoSubstitutionTemplateLiteral */:
83463                             return factory.createIdentifier("String");
83464                         case 214 /* PrefixUnaryExpression */:
83465                         case 8 /* NumericLiteral */:
83466                             return factory.createIdentifier("Number");
83467                         case 9 /* BigIntLiteral */:
83468                             return getGlobalBigIntNameWithFallback();
83469                         case 109 /* TrueKeyword */:
83470                         case 94 /* FalseKeyword */:
83471                             return factory.createIdentifier("Boolean");
83472                         case 103 /* NullKeyword */:
83473                             return factory.createVoidZero();
83474                         default:
83475                             return ts.Debug.failBadSyntaxKind(node.literal);
83476                     }
83477                 case 144 /* NumberKeyword */:
83478                     return factory.createIdentifier("Number");
83479                 case 155 /* BigIntKeyword */:
83480                     return getGlobalBigIntNameWithFallback();
83481                 case 148 /* SymbolKeyword */:
83482                     return languageVersion < 2 /* ES2015 */
83483                         ? getGlobalSymbolNameWithFallback()
83484                         : factory.createIdentifier("Symbol");
83485                 case 173 /* TypeReference */:
83486                     return serializeTypeReferenceNode(node);
83487                 case 183 /* IntersectionType */:
83488                 case 182 /* UnionType */:
83489                     return serializeTypeList(node.types);
83490                 case 184 /* ConditionalType */:
83491                     return serializeTypeList([node.trueType, node.falseType]);
83492                 case 188 /* TypeOperator */:
83493                     if (node.operator === 142 /* ReadonlyKeyword */) {
83494                         return serializeTypeNode(node.type);
83495                     }
83496                     break;
83497                 case 176 /* TypeQuery */:
83498                 case 189 /* IndexedAccessType */:
83499                 case 190 /* MappedType */:
83500                 case 177 /* TypeLiteral */:
83501                 case 128 /* AnyKeyword */:
83502                 case 152 /* UnknownKeyword */:
83503                 case 187 /* ThisType */:
83504                 case 195 /* ImportType */:
83505                     break;
83506                 // handle JSDoc types from an invalid parse
83507                 case 303 /* JSDocAllType */:
83508                 case 304 /* JSDocUnknownType */:
83509                 case 308 /* JSDocFunctionType */:
83510                 case 309 /* JSDocVariadicType */:
83511                 case 310 /* JSDocNamepathType */:
83512                     break;
83513                 case 305 /* JSDocNullableType */:
83514                 case 306 /* JSDocNonNullableType */:
83515                 case 307 /* JSDocOptionalType */:
83516                     return serializeTypeNode(node.type);
83517                 default:
83518                     return ts.Debug.failBadSyntaxKind(node);
83519             }
83520             return factory.createIdentifier("Object");
83521         }
83522         function serializeTypeList(types) {
83523             // Note when updating logic here also update getEntityNameForDecoratorMetadata
83524             // so that aliases can be marked as referenced
83525             var serializedUnion;
83526             for (var _i = 0, types_22 = types; _i < types_22.length; _i++) {
83527                 var typeNode = types_22[_i];
83528                 while (typeNode.kind === 186 /* ParenthesizedType */) {
83529                     typeNode = typeNode.type; // Skip parens if need be
83530                 }
83531                 if (typeNode.kind === 141 /* NeverKeyword */) {
83532                     continue; // Always elide `never` from the union/intersection if possible
83533                 }
83534                 if (!strictNullChecks && (typeNode.kind === 191 /* LiteralType */ && typeNode.literal.kind === 103 /* NullKeyword */ || typeNode.kind === 150 /* UndefinedKeyword */)) {
83535                     continue; // Elide null and undefined from unions for metadata, just like what we did prior to the implementation of strict null checks
83536                 }
83537                 var serializedIndividual = serializeTypeNode(typeNode);
83538                 if (ts.isIdentifier(serializedIndividual) && serializedIndividual.escapedText === "Object") {
83539                     // One of the individual is global object, return immediately
83540                     return serializedIndividual;
83541                 }
83542                 // If there exists union that is not void 0 expression, check if the the common type is identifier.
83543                 // anything more complex and we will just default to Object
83544                 else if (serializedUnion) {
83545                     // Different types
83546                     if (!ts.isIdentifier(serializedUnion) ||
83547                         !ts.isIdentifier(serializedIndividual) ||
83548                         serializedUnion.escapedText !== serializedIndividual.escapedText) {
83549                         return factory.createIdentifier("Object");
83550                     }
83551                 }
83552                 else {
83553                     // Initialize the union type
83554                     serializedUnion = serializedIndividual;
83555                 }
83556             }
83557             // If we were able to find common type, use it
83558             return serializedUnion || factory.createVoidZero(); // Fallback is only hit if all union constituients are null/undefined/never
83559         }
83560         /**
83561          * Serializes a TypeReferenceNode to an appropriate JS constructor value for use with
83562          * decorator type metadata.
83563          *
83564          * @param node The type reference node.
83565          */
83566         function serializeTypeReferenceNode(node) {
83567             var kind = resolver.getTypeReferenceSerializationKind(node.typeName, currentNameScope || currentLexicalScope);
83568             switch (kind) {
83569                 case ts.TypeReferenceSerializationKind.Unknown:
83570                     // From conditional type type reference that cannot be resolved is Similar to any or unknown
83571                     if (ts.findAncestor(node, function (n) { return n.parent && ts.isConditionalTypeNode(n.parent) && (n.parent.trueType === n || n.parent.falseType === n); })) {
83572                         return factory.createIdentifier("Object");
83573                     }
83574                     var serialized = serializeEntityNameAsExpressionFallback(node.typeName);
83575                     var temp = factory.createTempVariable(hoistVariableDeclaration);
83576                     return factory.createConditionalExpression(factory.createTypeCheck(factory.createAssignment(temp, serialized), "function"), 
83577                     /*questionToken*/ undefined, temp, 
83578                     /*colonToken*/ undefined, factory.createIdentifier("Object"));
83579                 case ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue:
83580                     return serializeEntityNameAsExpression(node.typeName);
83581                 case ts.TypeReferenceSerializationKind.VoidNullableOrNeverType:
83582                     return factory.createVoidZero();
83583                 case ts.TypeReferenceSerializationKind.BigIntLikeType:
83584                     return getGlobalBigIntNameWithFallback();
83585                 case ts.TypeReferenceSerializationKind.BooleanType:
83586                     return factory.createIdentifier("Boolean");
83587                 case ts.TypeReferenceSerializationKind.NumberLikeType:
83588                     return factory.createIdentifier("Number");
83589                 case ts.TypeReferenceSerializationKind.StringLikeType:
83590                     return factory.createIdentifier("String");
83591                 case ts.TypeReferenceSerializationKind.ArrayLikeType:
83592                     return factory.createIdentifier("Array");
83593                 case ts.TypeReferenceSerializationKind.ESSymbolType:
83594                     return languageVersion < 2 /* ES2015 */
83595                         ? getGlobalSymbolNameWithFallback()
83596                         : factory.createIdentifier("Symbol");
83597                 case ts.TypeReferenceSerializationKind.TypeWithCallSignature:
83598                     return factory.createIdentifier("Function");
83599                 case ts.TypeReferenceSerializationKind.Promise:
83600                     return factory.createIdentifier("Promise");
83601                 case ts.TypeReferenceSerializationKind.ObjectType:
83602                     return factory.createIdentifier("Object");
83603                 default:
83604                     return ts.Debug.assertNever(kind);
83605             }
83606         }
83607         function createCheckedValue(left, right) {
83608             return factory.createLogicalAnd(factory.createStrictInequality(factory.createTypeOfExpression(left), factory.createStringLiteral("undefined")), right);
83609         }
83610         /**
83611          * Serializes an entity name which may not exist at runtime, but whose access shouldn't throw
83612          *
83613          * @param node The entity name to serialize.
83614          */
83615         function serializeEntityNameAsExpressionFallback(node) {
83616             if (node.kind === 78 /* Identifier */) {
83617                 // A -> typeof A !== undefined && A
83618                 var copied = serializeEntityNameAsExpression(node);
83619                 return createCheckedValue(copied, copied);
83620             }
83621             if (node.left.kind === 78 /* Identifier */) {
83622                 // A.B -> typeof A !== undefined && A.B
83623                 return createCheckedValue(serializeEntityNameAsExpression(node.left), serializeEntityNameAsExpression(node));
83624             }
83625             // A.B.C -> typeof A !== undefined && (_a = A.B) !== void 0 && _a.C
83626             var left = serializeEntityNameAsExpressionFallback(node.left);
83627             var temp = factory.createTempVariable(hoistVariableDeclaration);
83628             return factory.createLogicalAnd(factory.createLogicalAnd(left.left, factory.createStrictInequality(factory.createAssignment(temp, left.right), factory.createVoidZero())), factory.createPropertyAccessExpression(temp, node.right));
83629         }
83630         /**
83631          * Serializes an entity name as an expression for decorator type metadata.
83632          *
83633          * @param node The entity name to serialize.
83634          */
83635         function serializeEntityNameAsExpression(node) {
83636             switch (node.kind) {
83637                 case 78 /* Identifier */:
83638                     // Create a clone of the name with a new parent, and treat it as if it were
83639                     // a source tree node for the purposes of the checker.
83640                     var name = ts.setParent(ts.setTextRange(ts.parseNodeFactory.cloneNode(node), node), node.parent);
83641                     name.original = undefined;
83642                     ts.setParent(name, ts.getParseTreeNode(currentLexicalScope)); // ensure the parent is set to a parse tree node.
83643                     return name;
83644                 case 157 /* QualifiedName */:
83645                     return serializeQualifiedNameAsExpression(node);
83646             }
83647         }
83648         /**
83649          * Serializes an qualified name as an expression for decorator type metadata.
83650          *
83651          * @param node The qualified name to serialize.
83652          * @param useFallback A value indicating whether to use logical operators to test for the
83653          *                    qualified name at runtime.
83654          */
83655         function serializeQualifiedNameAsExpression(node) {
83656             return factory.createPropertyAccessExpression(serializeEntityNameAsExpression(node.left), node.right);
83657         }
83658         /**
83659          * Gets an expression that points to the global "Symbol" constructor at runtime if it is
83660          * available.
83661          */
83662         function getGlobalSymbolNameWithFallback() {
83663             return factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("Symbol"), "function"), 
83664             /*questionToken*/ undefined, factory.createIdentifier("Symbol"), 
83665             /*colonToken*/ undefined, factory.createIdentifier("Object"));
83666         }
83667         /**
83668          * Gets an expression that points to the global "BigInt" constructor at runtime if it is
83669          * available.
83670          */
83671         function getGlobalBigIntNameWithFallback() {
83672             return languageVersion < 99 /* ESNext */
83673                 ? factory.createConditionalExpression(factory.createTypeCheck(factory.createIdentifier("BigInt"), "function"), 
83674                 /*questionToken*/ undefined, factory.createIdentifier("BigInt"), 
83675                 /*colonToken*/ undefined, factory.createIdentifier("Object"))
83676                 : factory.createIdentifier("BigInt");
83677         }
83678         /**
83679          * Gets an expression that represents a property name (for decorated properties or enums).
83680          * For a computed property, a name is generated for the node.
83681          *
83682          * @param member The member whose name should be converted into an expression.
83683          */
83684         function getExpressionForPropertyName(member, generateNameForComputedPropertyName) {
83685             var name = member.name;
83686             if (ts.isPrivateIdentifier(name)) {
83687                 return factory.createIdentifier("");
83688             }
83689             else if (ts.isComputedPropertyName(name)) {
83690                 return generateNameForComputedPropertyName && !ts.isSimpleInlineableExpression(name.expression)
83691                     ? factory.getGeneratedNameForNode(name)
83692                     : name.expression;
83693             }
83694             else if (ts.isIdentifier(name)) {
83695                 return factory.createStringLiteral(ts.idText(name));
83696             }
83697             else {
83698                 return factory.cloneNode(name);
83699             }
83700         }
83701         /**
83702          * Visits the property name of a class element, for use when emitting property
83703          * initializers. For a computed property on a node with decorators, a temporary
83704          * value is stored for later use.
83705          *
83706          * @param member The member whose name should be visited.
83707          */
83708         function visitPropertyNameOfClassElement(member) {
83709             var name = member.name;
83710             // Computed property names need to be transformed into a hoisted variable when they are used more than once.
83711             // The names are used more than once when:
83712             //   - the property is non-static and its initializer is moved to the constructor (when there are parameter property assignments).
83713             //   - the property has a decorator.
83714             if (ts.isComputedPropertyName(name) && ((!ts.hasStaticModifier(member) && currentClassHasParameterProperties) || ts.some(member.decorators))) {
83715                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
83716                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
83717                 if (!ts.isSimpleInlineableExpression(innerExpression)) {
83718                     var generatedName = factory.getGeneratedNameForNode(name);
83719                     hoistVariableDeclaration(generatedName);
83720                     return factory.updateComputedPropertyName(name, factory.createAssignment(generatedName, expression));
83721                 }
83722             }
83723             return ts.visitNode(name, visitor, ts.isPropertyName);
83724         }
83725         /**
83726          * Transforms a HeritageClause with TypeScript syntax.
83727          *
83728          * This function will only be called when one of the following conditions are met:
83729          * - The node is a non-`extends` heritage clause that should be elided.
83730          * - The node is an `extends` heritage clause that should be visited, but only allow a single type.
83731          *
83732          * @param node The HeritageClause to transform.
83733          */
83734         function visitHeritageClause(node) {
83735             if (node.token === 116 /* ImplementsKeyword */) {
83736                 // implements clauses are elided
83737                 return undefined;
83738             }
83739             return ts.visitEachChild(node, visitor, context);
83740         }
83741         /**
83742          * Transforms an ExpressionWithTypeArguments with TypeScript syntax.
83743          *
83744          * This function will only be called when one of the following conditions are met:
83745          * - The node contains type arguments that should be elided.
83746          *
83747          * @param node The ExpressionWithTypeArguments to transform.
83748          */
83749         function visitExpressionWithTypeArguments(node) {
83750             return factory.updateExpressionWithTypeArguments(node, ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression), 
83751             /*typeArguments*/ undefined);
83752         }
83753         /**
83754          * Determines whether to emit a function-like declaration. We should not emit the
83755          * declaration if it does not have a body.
83756          *
83757          * @param node The declaration node.
83758          */
83759         function shouldEmitFunctionLikeDeclaration(node) {
83760             return !ts.nodeIsMissing(node.body);
83761         }
83762         function visitPropertyDeclaration(node) {
83763             if (node.flags & 8388608 /* Ambient */) {
83764                 return undefined;
83765             }
83766             var updated = factory.updatePropertyDeclaration(node, 
83767             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), visitPropertyNameOfClassElement(node), 
83768             /*questionOrExclamationToken*/ undefined, 
83769             /*type*/ undefined, ts.visitNode(node.initializer, visitor));
83770             if (updated !== node) {
83771                 // While we emit the source map for the node after skipping decorators and modifiers,
83772                 // we need to emit the comments for the original range.
83773                 ts.setCommentRange(updated, node);
83774                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
83775             }
83776             return updated;
83777         }
83778         function visitConstructor(node) {
83779             if (!shouldEmitFunctionLikeDeclaration(node)) {
83780                 return undefined;
83781             }
83782             return factory.updateConstructorDeclaration(node, 
83783             /*decorators*/ undefined, 
83784             /*modifiers*/ undefined, ts.visitParameterList(node.parameters, visitor, context), transformConstructorBody(node.body, node));
83785         }
83786         function transformConstructorBody(body, constructor) {
83787             var parametersWithPropertyAssignments = constructor &&
83788                 ts.filter(constructor.parameters, function (p) { return ts.isParameterPropertyDeclaration(p, constructor); });
83789             if (!ts.some(parametersWithPropertyAssignments)) {
83790                 return ts.visitFunctionBody(body, visitor, context);
83791             }
83792             var statements = [];
83793             var indexOfFirstStatement = 0;
83794             resumeLexicalEnvironment();
83795             indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
83796             // Add parameters with property assignments. Transforms this:
83797             //
83798             //  constructor (public x, public y) {
83799             //  }
83800             //
83801             // Into this:
83802             //
83803             //  constructor (x, y) {
83804             //      this.x = x;
83805             //      this.y = y;
83806             //  }
83807             //
83808             ts.addRange(statements, ts.map(parametersWithPropertyAssignments, transformParameterWithPropertyAssignment));
83809             // Add the existing statements, skipping the initial super call.
83810             ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, indexOfFirstStatement));
83811             // End the lexical environment.
83812             statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
83813             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), body.statements), /*multiLine*/ true);
83814             ts.setTextRange(block, /*location*/ body);
83815             ts.setOriginalNode(block, body);
83816             return block;
83817         }
83818         /**
83819          * Transforms a parameter into a property assignment statement.
83820          *
83821          * @param node The parameter declaration.
83822          */
83823         function transformParameterWithPropertyAssignment(node) {
83824             var name = node.name;
83825             if (!ts.isIdentifier(name)) {
83826                 return undefined;
83827             }
83828             // TODO(rbuckton): Does this need to be parented?
83829             var propertyName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
83830             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 48 /* NoSourceMap */);
83831             // TODO(rbuckton): Does this need to be parented?
83832             var localName = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
83833             ts.setEmitFlags(localName, 1536 /* NoComments */);
83834             return ts.startOnNewLine(ts.removeAllComments(ts.setTextRange(ts.setOriginalNode(factory.createExpressionStatement(factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createThis(), propertyName), node.name), localName)), node), ts.moveRangePos(node, -1))));
83835         }
83836         function visitMethodDeclaration(node) {
83837             if (!shouldEmitFunctionLikeDeclaration(node)) {
83838                 return undefined;
83839             }
83840             var updated = factory.updateMethodDeclaration(node, 
83841             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, visitPropertyNameOfClassElement(node), 
83842             /*questionToken*/ undefined, 
83843             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
83844             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context));
83845             if (updated !== node) {
83846                 // While we emit the source map for the node after skipping decorators and modifiers,
83847                 // we need to emit the comments for the original range.
83848                 ts.setCommentRange(updated, node);
83849                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
83850             }
83851             return updated;
83852         }
83853         /**
83854          * Determines whether to emit an accessor declaration. We should not emit the
83855          * declaration if it does not have a body and is abstract.
83856          *
83857          * @param node The declaration node.
83858          */
83859         function shouldEmitAccessorDeclaration(node) {
83860             return !(ts.nodeIsMissing(node.body) && ts.hasSyntacticModifier(node, 128 /* Abstract */));
83861         }
83862         function visitGetAccessor(node) {
83863             if (!shouldEmitAccessorDeclaration(node)) {
83864                 return undefined;
83865             }
83866             var updated = factory.updateGetAccessorDeclaration(node, 
83867             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), 
83868             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
83869             if (updated !== node) {
83870                 // While we emit the source map for the node after skipping decorators and modifiers,
83871                 // we need to emit the comments for the original range.
83872                 ts.setCommentRange(updated, node);
83873                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
83874             }
83875             return updated;
83876         }
83877         function visitSetAccessor(node) {
83878             if (!shouldEmitAccessorDeclaration(node)) {
83879                 return undefined;
83880             }
83881             var updated = factory.updateSetAccessorDeclaration(node, 
83882             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), visitPropertyNameOfClassElement(node), ts.visitParameterList(node.parameters, visitor, context), ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
83883             if (updated !== node) {
83884                 // While we emit the source map for the node after skipping decorators and modifiers,
83885                 // we need to emit the comments for the original range.
83886                 ts.setCommentRange(updated, node);
83887                 ts.setSourceMapRange(updated, ts.moveRangePastDecorators(node));
83888             }
83889             return updated;
83890         }
83891         function visitFunctionDeclaration(node) {
83892             if (!shouldEmitFunctionLikeDeclaration(node)) {
83893                 return factory.createNotEmittedStatement(node);
83894             }
83895             var updated = factory.updateFunctionDeclaration(node, 
83896             /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
83897             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
83898             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
83899             if (isExportOfNamespace(node)) {
83900                 var statements = [updated];
83901                 addExportMemberAssignment(statements, node);
83902                 return statements;
83903             }
83904             return updated;
83905         }
83906         function visitFunctionExpression(node) {
83907             if (!shouldEmitFunctionLikeDeclaration(node)) {
83908                 return factory.createOmittedExpression();
83909             }
83910             var updated = factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, node.name, 
83911             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
83912             /*type*/ undefined, ts.visitFunctionBody(node.body, visitor, context) || factory.createBlock([]));
83913             return updated;
83914         }
83915         function visitArrowFunction(node) {
83916             var updated = factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), 
83917             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
83918             /*type*/ undefined, node.equalsGreaterThanToken, ts.visitFunctionBody(node.body, visitor, context));
83919             return updated;
83920         }
83921         function visitParameter(node) {
83922             if (ts.parameterIsThisKeyword(node)) {
83923                 return undefined;
83924             }
83925             var updated = factory.updateParameterDeclaration(node, 
83926             /*decorators*/ undefined, 
83927             /*modifiers*/ undefined, node.dotDotDotToken, ts.visitNode(node.name, visitor, ts.isBindingName), 
83928             /*questionToken*/ undefined, 
83929             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
83930             if (updated !== node) {
83931                 // While we emit the source map for the node after skipping decorators and modifiers,
83932                 // we need to emit the comments for the original range.
83933                 ts.setCommentRange(updated, node);
83934                 ts.setTextRange(updated, ts.moveRangePastModifiers(node));
83935                 ts.setSourceMapRange(updated, ts.moveRangePastModifiers(node));
83936                 ts.setEmitFlags(updated.name, 32 /* NoTrailingSourceMap */);
83937             }
83938             return updated;
83939         }
83940         function visitVariableStatement(node) {
83941             if (isExportOfNamespace(node)) {
83942                 var variables = ts.getInitializedVariables(node.declarationList);
83943                 if (variables.length === 0) {
83944                     // elide statement if there are no initialized variables.
83945                     return undefined;
83946                 }
83947                 return ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
83948             }
83949             else {
83950                 return ts.visitEachChild(node, visitor, context);
83951             }
83952         }
83953         function transformInitializedVariable(node) {
83954             var name = node.name;
83955             if (ts.isBindingPattern(name)) {
83956                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, 
83957                 /*needsValue*/ false, createNamespaceExportExpression);
83958             }
83959             else {
83960                 return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(name), ts.visitNode(node.initializer, visitor, ts.isExpression)), 
83961                 /*location*/ node);
83962             }
83963         }
83964         function visitVariableDeclaration(node) {
83965             return factory.updateVariableDeclaration(node, ts.visitNode(node.name, visitor, ts.isBindingName), 
83966             /*exclamationToken*/ undefined, 
83967             /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
83968         }
83969         function visitParenthesizedExpression(node) {
83970             var innerExpression = ts.skipOuterExpressions(node.expression, ~6 /* Assertions */);
83971             if (ts.isAssertionExpression(innerExpression)) {
83972                 // Make sure we consider all nested cast expressions, e.g.:
83973                 // (<any><number><any>-A).x;
83974                 var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
83975                 // We have an expression of the form: (<Type>SubExpr). Emitting this as (SubExpr)
83976                 // is really not desirable. We would like to emit the subexpression as-is. Omitting
83977                 // the parentheses, however, could cause change in the semantics of the generated
83978                 // code if the casted expression has a lower precedence than the rest of the
83979                 // expression.
83980                 //
83981                 // To preserve comments, we return a "PartiallyEmittedExpression" here which will
83982                 // preserve the position information of the original expression.
83983                 //
83984                 // Due to the auto-parenthesization rules used by the visitor and factory functions
83985                 // we can safely elide the parentheses here, as a new synthetic
83986                 // ParenthesizedExpression will be inserted if we remove parentheses too
83987                 // aggressively.
83988                 // HOWEVER - if there are leading comments on the expression itself, to handle ASI
83989                 // correctly for return and throw, we must keep the parenthesis
83990                 if (ts.length(ts.getLeadingCommentRangesOfNode(expression, currentSourceFile))) {
83991                     return factory.updateParenthesizedExpression(node, expression);
83992                 }
83993                 return factory.createPartiallyEmittedExpression(expression, node);
83994             }
83995             return ts.visitEachChild(node, visitor, context);
83996         }
83997         function visitAssertionExpression(node) {
83998             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
83999             return factory.createPartiallyEmittedExpression(expression, node);
84000         }
84001         function visitNonNullExpression(node) {
84002             var expression = ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression);
84003             return factory.createPartiallyEmittedExpression(expression, node);
84004         }
84005         function visitCallExpression(node) {
84006             return factory.updateCallExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
84007             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
84008         }
84009         function visitNewExpression(node) {
84010             return factory.updateNewExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression), 
84011             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
84012         }
84013         function visitTaggedTemplateExpression(node) {
84014             return factory.updateTaggedTemplateExpression(node, ts.visitNode(node.tag, visitor, ts.isExpression), 
84015             /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isExpression));
84016         }
84017         function visitJsxSelfClosingElement(node) {
84018             return factory.updateJsxSelfClosingElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
84019             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
84020         }
84021         function visitJsxJsxOpeningElement(node) {
84022             return factory.updateJsxOpeningElement(node, ts.visitNode(node.tagName, visitor, ts.isJsxTagNameExpression), 
84023             /*typeArguments*/ undefined, ts.visitNode(node.attributes, visitor, ts.isJsxAttributes));
84024         }
84025         /**
84026          * Determines whether to emit an enum declaration.
84027          *
84028          * @param node The enum declaration node.
84029          */
84030         function shouldEmitEnumDeclaration(node) {
84031             return !ts.isEnumConst(node)
84032                 || compilerOptions.preserveConstEnums
84033                 || compilerOptions.isolatedModules;
84034         }
84035         /**
84036          * Visits an enum declaration.
84037          *
84038          * This function will be called any time a TypeScript enum is encountered.
84039          *
84040          * @param node The enum declaration node.
84041          */
84042         function visitEnumDeclaration(node) {
84043             if (!shouldEmitEnumDeclaration(node)) {
84044                 return factory.createNotEmittedStatement(node);
84045             }
84046             var statements = [];
84047             // We request to be advised when the printer is about to print this node. This allows
84048             // us to set up the correct state for later substitutions.
84049             var emitFlags = 2 /* AdviseOnEmitNode */;
84050             // If needed, we should emit a variable declaration for the enum. If we emit
84051             // a leading variable declaration, we should not emit leading comments for the
84052             // enum body.
84053             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
84054             if (varAdded) {
84055                 // We should still emit the comments if we are emitting a system module.
84056                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
84057                     emitFlags |= 512 /* NoLeadingComments */;
84058                 }
84059             }
84060             // `parameterName` is the declaration name used inside of the enum.
84061             var parameterName = getNamespaceParameterName(node);
84062             // `containerName` is the expression used inside of the enum for assignments.
84063             var containerName = getNamespaceContainerName(node);
84064             // `exportName` is the expression used within this node's container for any exported references.
84065             var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
84066                 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
84067                 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
84068             //  x || (x = {})
84069             //  exports.x || (exports.x = {})
84070             var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
84071             if (hasNamespaceQualifiedExportName(node)) {
84072                 // `localName` is the expression used within this node's containing scope for any local references.
84073                 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
84074                 //  x = (exports.x || (exports.x = {}))
84075                 moduleArg = factory.createAssignment(localName, moduleArg);
84076             }
84077             //  (function (x) {
84078             //      x[x["y"] = 0] = "y";
84079             //      ...
84080             //  })(x || (x = {}));
84081             var enumStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
84082             /*modifiers*/ undefined, 
84083             /*asteriskToken*/ undefined, 
84084             /*name*/ undefined, 
84085             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
84086             /*type*/ undefined, transformEnumBody(node, containerName)), 
84087             /*typeArguments*/ undefined, [moduleArg]));
84088             ts.setOriginalNode(enumStatement, node);
84089             if (varAdded) {
84090                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
84091                 ts.setSyntheticLeadingComments(enumStatement, undefined);
84092                 ts.setSyntheticTrailingComments(enumStatement, undefined);
84093             }
84094             ts.setTextRange(enumStatement, node);
84095             ts.addEmitFlags(enumStatement, emitFlags);
84096             statements.push(enumStatement);
84097             // Add a DeclarationMarker for the enum to preserve trailing comments and mark
84098             // the end of the declaration.
84099             statements.push(factory.createEndOfDeclarationMarker(node));
84100             return statements;
84101         }
84102         /**
84103          * Transforms the body of an enum declaration.
84104          *
84105          * @param node The enum declaration node.
84106          */
84107         function transformEnumBody(node, localName) {
84108             var savedCurrentNamespaceLocalName = currentNamespaceContainerName;
84109             currentNamespaceContainerName = localName;
84110             var statements = [];
84111             startLexicalEnvironment();
84112             var members = ts.map(node.members, transformEnumMember);
84113             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
84114             ts.addRange(statements, members);
84115             currentNamespaceContainerName = savedCurrentNamespaceLocalName;
84116             return factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members), 
84117             /*multiLine*/ true);
84118         }
84119         /**
84120          * Transforms an enum member into a statement.
84121          *
84122          * @param member The enum member node.
84123          */
84124         function transformEnumMember(member) {
84125             // enums don't support computed properties
84126             // we pass false as 'generateNameForComputedPropertyName' for a backward compatibility purposes
84127             // old emitter always generate 'expression' part of the name as-is.
84128             var name = getExpressionForPropertyName(member, /*generateNameForComputedPropertyName*/ false);
84129             var valueExpression = transformEnumMemberDeclarationValue(member);
84130             var innerAssignment = factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, name), valueExpression);
84131             var outerAssignment = valueExpression.kind === 10 /* StringLiteral */ ?
84132                 innerAssignment :
84133                 factory.createAssignment(factory.createElementAccessExpression(currentNamespaceContainerName, innerAssignment), name);
84134             return ts.setTextRange(factory.createExpressionStatement(ts.setTextRange(outerAssignment, member)), member);
84135         }
84136         /**
84137          * Transforms the value of an enum member.
84138          *
84139          * @param member The enum member node.
84140          */
84141         function transformEnumMemberDeclarationValue(member) {
84142             var value = resolver.getConstantValue(member);
84143             if (value !== undefined) {
84144                 return typeof value === "string" ? factory.createStringLiteral(value) : factory.createNumericLiteral(value);
84145             }
84146             else {
84147                 enableSubstitutionForNonQualifiedEnumMembers();
84148                 if (member.initializer) {
84149                     return ts.visitNode(member.initializer, visitor, ts.isExpression);
84150                 }
84151                 else {
84152                     return factory.createVoidZero();
84153                 }
84154             }
84155         }
84156         /**
84157          * Determines whether to elide a module declaration.
84158          *
84159          * @param node The module declaration node.
84160          */
84161         function shouldEmitModuleDeclaration(nodeIn) {
84162             var node = ts.getParseTreeNode(nodeIn, ts.isModuleDeclaration);
84163             if (!node) {
84164                 // If we can't find a parse tree node, assume the node is instantiated.
84165                 return true;
84166             }
84167             return ts.isInstantiatedModule(node, !!compilerOptions.preserveConstEnums || !!compilerOptions.isolatedModules);
84168         }
84169         /**
84170          * Determines whether an exported declaration will have a qualified export name (e.g. `f.x`
84171          * or `exports.x`).
84172          */
84173         function hasNamespaceQualifiedExportName(node) {
84174             return isExportOfNamespace(node)
84175                 || (isExternalModuleExport(node)
84176                     && moduleKind !== ts.ModuleKind.ES2015
84177                     && moduleKind !== ts.ModuleKind.ES2020
84178                     && moduleKind !== ts.ModuleKind.ESNext
84179                     && moduleKind !== ts.ModuleKind.System);
84180         }
84181         /**
84182          * Records that a declaration was emitted in the current scope, if it was the first
84183          * declaration for the provided symbol.
84184          */
84185         function recordEmittedDeclarationInScope(node) {
84186             if (!currentScopeFirstDeclarationsOfName) {
84187                 currentScopeFirstDeclarationsOfName = new ts.Map();
84188             }
84189             var name = declaredNameInScope(node);
84190             if (!currentScopeFirstDeclarationsOfName.has(name)) {
84191                 currentScopeFirstDeclarationsOfName.set(name, node);
84192             }
84193         }
84194         /**
84195          * Determines whether a declaration is the first declaration with
84196          * the same name emitted in the current scope.
84197          */
84198         function isFirstEmittedDeclarationInScope(node) {
84199             if (currentScopeFirstDeclarationsOfName) {
84200                 var name = declaredNameInScope(node);
84201                 return currentScopeFirstDeclarationsOfName.get(name) === node;
84202             }
84203             return true;
84204         }
84205         function declaredNameInScope(node) {
84206             ts.Debug.assertNode(node.name, ts.isIdentifier);
84207             return node.name.escapedText;
84208         }
84209         /**
84210          * Adds a leading VariableStatement for a enum or module declaration.
84211          */
84212         function addVarForEnumOrModuleDeclaration(statements, node) {
84213             // Emit a variable statement for the module. We emit top-level enums as a `var`
84214             // declaration to avoid static errors in global scripts scripts due to redeclaration.
84215             // enums in any other scope are emitted as a `let` declaration.
84216             var statement = factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
84217                 factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true))
84218             ], currentLexicalScope.kind === 297 /* SourceFile */ ? 0 /* None */ : 1 /* Let */));
84219             ts.setOriginalNode(statement, node);
84220             recordEmittedDeclarationInScope(node);
84221             if (isFirstEmittedDeclarationInScope(node)) {
84222                 // Adjust the source map emit to match the old emitter.
84223                 if (node.kind === 255 /* EnumDeclaration */) {
84224                     ts.setSourceMapRange(statement.declarationList, node);
84225                 }
84226                 else {
84227                     ts.setSourceMapRange(statement, node);
84228                 }
84229                 // Trailing comments for module declaration should be emitted after the function closure
84230                 // instead of the variable statement:
84231                 //
84232                 //     /** Module comment*/
84233                 //     module m1 {
84234                 //         function foo4Export() {
84235                 //         }
84236                 //     } // trailing comment module
84237                 //
84238                 // Should emit:
84239                 //
84240                 //     /** Module comment*/
84241                 //     var m1;
84242                 //     (function (m1) {
84243                 //         function foo4Export() {
84244                 //         }
84245                 //     })(m1 || (m1 = {})); // trailing comment module
84246                 //
84247                 ts.setCommentRange(statement, node);
84248                 ts.addEmitFlags(statement, 1024 /* NoTrailingComments */ | 4194304 /* HasEndOfDeclarationMarker */);
84249                 statements.push(statement);
84250                 return true;
84251             }
84252             else {
84253                 // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
84254                 // declaration we do not emit a leading variable declaration. To preserve the
84255                 // begin/end semantics of the declararation and to properly handle exports
84256                 // we wrap the leading variable declaration in a `MergeDeclarationMarker`.
84257                 var mergeMarker = factory.createMergeDeclarationMarker(statement);
84258                 ts.setEmitFlags(mergeMarker, 1536 /* NoComments */ | 4194304 /* HasEndOfDeclarationMarker */);
84259                 statements.push(mergeMarker);
84260                 return false;
84261             }
84262         }
84263         /**
84264          * Visits a module declaration node.
84265          *
84266          * This function will be called any time a TypeScript namespace (ModuleDeclaration) is encountered.
84267          *
84268          * @param node The module declaration node.
84269          */
84270         function visitModuleDeclaration(node) {
84271             if (!shouldEmitModuleDeclaration(node)) {
84272                 return factory.createNotEmittedStatement(node);
84273             }
84274             ts.Debug.assertNode(node.name, ts.isIdentifier, "A TypeScript namespace should have an Identifier name.");
84275             enableSubstitutionForNamespaceExports();
84276             var statements = [];
84277             // We request to be advised when the printer is about to print this node. This allows
84278             // us to set up the correct state for later substitutions.
84279             var emitFlags = 2 /* AdviseOnEmitNode */;
84280             // If needed, we should emit a variable declaration for the module. If we emit
84281             // a leading variable declaration, we should not emit leading comments for the
84282             // module body.
84283             var varAdded = addVarForEnumOrModuleDeclaration(statements, node);
84284             if (varAdded) {
84285                 // We should still emit the comments if we are emitting a system module.
84286                 if (moduleKind !== ts.ModuleKind.System || currentLexicalScope !== currentSourceFile) {
84287                     emitFlags |= 512 /* NoLeadingComments */;
84288                 }
84289             }
84290             // `parameterName` is the declaration name used inside of the namespace.
84291             var parameterName = getNamespaceParameterName(node);
84292             // `containerName` is the expression used inside of the namespace for exports.
84293             var containerName = getNamespaceContainerName(node);
84294             // `exportName` is the expression used within this node's container for any exported references.
84295             var exportName = ts.hasSyntacticModifier(node, 1 /* Export */)
84296                 ? factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true)
84297                 : factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
84298             //  x || (x = {})
84299             //  exports.x || (exports.x = {})
84300             var moduleArg = factory.createLogicalOr(exportName, factory.createAssignment(exportName, factory.createObjectLiteralExpression()));
84301             if (hasNamespaceQualifiedExportName(node)) {
84302                 // `localName` is the expression used within this node's containing scope for any local references.
84303                 var localName = factory.getLocalName(node, /*allowComments*/ false, /*allowSourceMaps*/ true);
84304                 //  x = (exports.x || (exports.x = {}))
84305                 moduleArg = factory.createAssignment(localName, moduleArg);
84306             }
84307             //  (function (x_1) {
84308             //      x_1.y = ...;
84309             //  })(x || (x = {}));
84310             var moduleStatement = factory.createExpressionStatement(factory.createCallExpression(factory.createFunctionExpression(
84311             /*modifiers*/ undefined, 
84312             /*asteriskToken*/ undefined, 
84313             /*name*/ undefined, 
84314             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
84315             /*type*/ undefined, transformModuleBody(node, containerName)), 
84316             /*typeArguments*/ undefined, [moduleArg]));
84317             ts.setOriginalNode(moduleStatement, node);
84318             if (varAdded) {
84319                 // If a variable was added, synthetic comments are emitted on it, not on the moduleStatement.
84320                 ts.setSyntheticLeadingComments(moduleStatement, undefined);
84321                 ts.setSyntheticTrailingComments(moduleStatement, undefined);
84322             }
84323             ts.setTextRange(moduleStatement, node);
84324             ts.addEmitFlags(moduleStatement, emitFlags);
84325             statements.push(moduleStatement);
84326             // Add a DeclarationMarker for the namespace to preserve trailing comments and mark
84327             // the end of the declaration.
84328             statements.push(factory.createEndOfDeclarationMarker(node));
84329             return statements;
84330         }
84331         /**
84332          * Transforms the body of a module declaration.
84333          *
84334          * @param node The module declaration node.
84335          */
84336         function transformModuleBody(node, namespaceLocalName) {
84337             var savedCurrentNamespaceContainerName = currentNamespaceContainerName;
84338             var savedCurrentNamespace = currentNamespace;
84339             var savedCurrentScopeFirstDeclarationsOfName = currentScopeFirstDeclarationsOfName;
84340             currentNamespaceContainerName = namespaceLocalName;
84341             currentNamespace = node;
84342             currentScopeFirstDeclarationsOfName = undefined;
84343             var statements = [];
84344             startLexicalEnvironment();
84345             var statementsLocation;
84346             var blockLocation;
84347             if (node.body) {
84348                 if (node.body.kind === 257 /* ModuleBlock */) {
84349                     saveStateAndInvoke(node.body, function (body) { return ts.addRange(statements, ts.visitNodes(body.statements, namespaceElementVisitor, ts.isStatement)); });
84350                     statementsLocation = node.body.statements;
84351                     blockLocation = node.body;
84352                 }
84353                 else {
84354                     var result = visitModuleDeclaration(node.body);
84355                     if (result) {
84356                         if (ts.isArray(result)) {
84357                             ts.addRange(statements, result);
84358                         }
84359                         else {
84360                             statements.push(result);
84361                         }
84362                     }
84363                     var moduleBlock = getInnerMostModuleDeclarationFromDottedModule(node).body;
84364                     statementsLocation = ts.moveRangePos(moduleBlock.statements, -1);
84365                 }
84366             }
84367             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
84368             currentNamespaceContainerName = savedCurrentNamespaceContainerName;
84369             currentNamespace = savedCurrentNamespace;
84370             currentScopeFirstDeclarationsOfName = savedCurrentScopeFirstDeclarationsOfName;
84371             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), 
84372             /*location*/ statementsLocation), 
84373             /*multiLine*/ true);
84374             ts.setTextRange(block, blockLocation);
84375             // namespace hello.hi.world {
84376             //      function foo() {}
84377             //
84378             //      // TODO, blah
84379             // }
84380             //
84381             // should be emitted as
84382             //
84383             // var hello;
84384             // (function (hello) {
84385             //     var hi;
84386             //     (function (hi) {
84387             //         var world;
84388             //         (function (world) {
84389             //             function foo() { }
84390             //             // TODO, blah
84391             //         })(world = hi.world || (hi.world = {}));
84392             //     })(hi = hello.hi || (hello.hi = {}));
84393             // })(hello || (hello = {}));
84394             // We only want to emit comment on the namespace which contains block body itself, not the containing namespaces.
84395             if (!node.body || node.body.kind !== 257 /* ModuleBlock */) {
84396                 ts.setEmitFlags(block, ts.getEmitFlags(block) | 1536 /* NoComments */);
84397             }
84398             return block;
84399         }
84400         function getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration) {
84401             if (moduleDeclaration.body.kind === 256 /* ModuleDeclaration */) {
84402                 var recursiveInnerModule = getInnerMostModuleDeclarationFromDottedModule(moduleDeclaration.body);
84403                 return recursiveInnerModule || moduleDeclaration.body;
84404             }
84405         }
84406         /**
84407          * Visits an import declaration, eliding it if it is not referenced and `importsNotUsedAsValues` is not 'preserve'.
84408          *
84409          * @param node The import declaration node.
84410          */
84411         function visitImportDeclaration(node) {
84412             if (!node.importClause) {
84413                 // Do not elide a side-effect only import declaration.
84414                 //  import "foo";
84415                 return node;
84416             }
84417             if (node.importClause.isTypeOnly) {
84418                 // Always elide type-only imports
84419                 return undefined;
84420             }
84421             // Elide the declaration if the import clause was elided.
84422             var importClause = ts.visitNode(node.importClause, visitImportClause, ts.isImportClause);
84423             return importClause ||
84424                 compilerOptions.importsNotUsedAsValues === 1 /* Preserve */ ||
84425                 compilerOptions.importsNotUsedAsValues === 2 /* Error */
84426                 ? factory.updateImportDeclaration(node, 
84427                 /*decorators*/ undefined, 
84428                 /*modifiers*/ undefined, importClause, node.moduleSpecifier)
84429                 : undefined;
84430         }
84431         /**
84432          * Visits an import clause, eliding it if it is not referenced.
84433          *
84434          * @param node The import clause node.
84435          */
84436         function visitImportClause(node) {
84437             if (node.isTypeOnly) {
84438                 return undefined;
84439             }
84440             // Elide the import clause if we elide both its name and its named bindings.
84441             var name = resolver.isReferencedAliasDeclaration(node) ? node.name : undefined;
84442             var namedBindings = ts.visitNode(node.namedBindings, visitNamedImportBindings, ts.isNamedImportBindings);
84443             return (name || namedBindings) ? factory.updateImportClause(node, /*isTypeOnly*/ false, name, namedBindings) : undefined;
84444         }
84445         /**
84446          * Visits named import bindings, eliding it if it is not referenced.
84447          *
84448          * @param node The named import bindings node.
84449          */
84450         function visitNamedImportBindings(node) {
84451             if (node.kind === 263 /* NamespaceImport */) {
84452                 // Elide a namespace import if it is not referenced.
84453                 return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
84454             }
84455             else {
84456                 // Elide named imports if all of its import specifiers are elided.
84457                 var elements = ts.visitNodes(node.elements, visitImportSpecifier, ts.isImportSpecifier);
84458                 return ts.some(elements) ? factory.updateNamedImports(node, elements) : undefined;
84459             }
84460         }
84461         /**
84462          * Visits an import specifier, eliding it if it is not referenced.
84463          *
84464          * @param node The import specifier node.
84465          */
84466         function visitImportSpecifier(node) {
84467             // Elide an import specifier if it is not referenced.
84468             return resolver.isReferencedAliasDeclaration(node) ? node : undefined;
84469         }
84470         /**
84471          * Visits an export assignment, eliding it if it does not contain a clause that resolves
84472          * to a value.
84473          *
84474          * @param node The export assignment node.
84475          */
84476         function visitExportAssignment(node) {
84477             // Elide the export assignment if it does not reference a value.
84478             return resolver.isValueAliasDeclaration(node)
84479                 ? ts.visitEachChild(node, visitor, context)
84480                 : undefined;
84481         }
84482         /**
84483          * Visits an export declaration, eliding it if it does not contain a clause that resolves
84484          * to a value.
84485          *
84486          * @param node The export declaration node.
84487          */
84488         function visitExportDeclaration(node) {
84489             if (node.isTypeOnly) {
84490                 return undefined;
84491             }
84492             if (!node.exportClause || ts.isNamespaceExport(node.exportClause)) {
84493                 // never elide `export <whatever> from <whereever>` declarations -
84494                 // they should be kept for sideffects/untyped exports, even when the
84495                 // type checker doesn't know about any exports
84496                 return node;
84497             }
84498             if (!resolver.isValueAliasDeclaration(node)) {
84499                 // Elide the export declaration if it does not export a value.
84500                 return undefined;
84501             }
84502             // Elide the export declaration if all of its named exports are elided.
84503             var exportClause = ts.visitNode(node.exportClause, visitNamedExportBindings, ts.isNamedExportBindings);
84504             return exportClause
84505                 ? factory.updateExportDeclaration(node, 
84506                 /*decorators*/ undefined, 
84507                 /*modifiers*/ undefined, node.isTypeOnly, exportClause, node.moduleSpecifier)
84508                 : undefined;
84509         }
84510         /**
84511          * Visits named exports, eliding it if it does not contain an export specifier that
84512          * resolves to a value.
84513          *
84514          * @param node The named exports node.
84515          */
84516         function visitNamedExports(node) {
84517             // Elide the named exports if all of its export specifiers were elided.
84518             var elements = ts.visitNodes(node.elements, visitExportSpecifier, ts.isExportSpecifier);
84519             return ts.some(elements) ? factory.updateNamedExports(node, elements) : undefined;
84520         }
84521         function visitNamespaceExports(node) {
84522             return factory.updateNamespaceExport(node, ts.visitNode(node.name, visitor, ts.isIdentifier));
84523         }
84524         function visitNamedExportBindings(node) {
84525             return ts.isNamespaceExport(node) ? visitNamespaceExports(node) : visitNamedExports(node);
84526         }
84527         /**
84528          * Visits an export specifier, eliding it if it does not resolve to a value.
84529          *
84530          * @param node The export specifier node.
84531          */
84532         function visitExportSpecifier(node) {
84533             // Elide an export specifier if it does not reference a value.
84534             return resolver.isValueAliasDeclaration(node) ? node : undefined;
84535         }
84536         /**
84537          * Determines whether to emit an import equals declaration.
84538          *
84539          * @param node The import equals declaration node.
84540          */
84541         function shouldEmitImportEqualsDeclaration(node) {
84542             // preserve old compiler's behavior: emit 'var' for import declaration (even if we do not consider them referenced) when
84543             // - current file is not external module
84544             // - import declaration is top level and target is value imported by entity name
84545             return resolver.isReferencedAliasDeclaration(node)
84546                 || (!ts.isExternalModule(currentSourceFile)
84547                     && resolver.isTopLevelValueImportEqualsWithEntityName(node));
84548         }
84549         /**
84550          * Visits an import equals declaration.
84551          *
84552          * @param node The import equals declaration node.
84553          */
84554         function visitImportEqualsDeclaration(node) {
84555             if (ts.isExternalModuleImportEqualsDeclaration(node)) {
84556                 var isReferenced = resolver.isReferencedAliasDeclaration(node);
84557                 // If the alias is unreferenced but we want to keep the import, replace with 'import "mod"'.
84558                 if (!isReferenced && compilerOptions.importsNotUsedAsValues === 1 /* Preserve */) {
84559                     return ts.setOriginalNode(ts.setTextRange(factory.createImportDeclaration(
84560                     /*decorators*/ undefined, 
84561                     /*modifiers*/ undefined, 
84562                     /*importClause*/ undefined, node.moduleReference.expression), node), node);
84563                 }
84564                 return isReferenced ? ts.visitEachChild(node, visitor, context) : undefined;
84565             }
84566             if (!shouldEmitImportEqualsDeclaration(node)) {
84567                 return undefined;
84568             }
84569             var moduleReference = ts.createExpressionFromEntityName(factory, node.moduleReference);
84570             ts.setEmitFlags(moduleReference, 1536 /* NoComments */ | 2048 /* NoNestedComments */);
84571             if (isNamedExternalModuleExport(node) || !isExportOfNamespace(node)) {
84572                 //  export var ${name} = ${moduleReference};
84573                 //  var ${name} = ${moduleReference};
84574                 return ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.createVariableDeclarationList([
84575                     ts.setOriginalNode(factory.createVariableDeclaration(node.name, 
84576                     /*exclamationToken*/ undefined, 
84577                     /*type*/ undefined, moduleReference), node)
84578                 ])), node), node);
84579             }
84580             else {
84581                 // exports.${name} = ${moduleReference};
84582                 return ts.setOriginalNode(createNamespaceExport(node.name, moduleReference, node), node);
84583             }
84584         }
84585         /**
84586          * Gets a value indicating whether the node is exported from a namespace.
84587          *
84588          * @param node The node to test.
84589          */
84590         function isExportOfNamespace(node) {
84591             return currentNamespace !== undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
84592         }
84593         /**
84594          * Gets a value indicating whether the node is exported from an external module.
84595          *
84596          * @param node The node to test.
84597          */
84598         function isExternalModuleExport(node) {
84599             return currentNamespace === undefined && ts.hasSyntacticModifier(node, 1 /* Export */);
84600         }
84601         /**
84602          * Gets a value indicating whether the node is a named export from an external module.
84603          *
84604          * @param node The node to test.
84605          */
84606         function isNamedExternalModuleExport(node) {
84607             return isExternalModuleExport(node)
84608                 && !ts.hasSyntacticModifier(node, 512 /* Default */);
84609         }
84610         /**
84611          * Gets a value indicating whether the node is the default export of an external module.
84612          *
84613          * @param node The node to test.
84614          */
84615         function isDefaultExternalModuleExport(node) {
84616             return isExternalModuleExport(node)
84617                 && ts.hasSyntacticModifier(node, 512 /* Default */);
84618         }
84619         /**
84620          * Creates a statement for the provided expression. This is used in calls to `map`.
84621          */
84622         function expressionToStatement(expression) {
84623             return factory.createExpressionStatement(expression);
84624         }
84625         function addExportMemberAssignment(statements, node) {
84626             var expression = factory.createAssignment(factory.getExternalModuleOrNamespaceExportName(currentNamespaceContainerName, node, /*allowComments*/ false, /*allowSourceMaps*/ true), factory.getLocalName(node));
84627             ts.setSourceMapRange(expression, ts.createRange(node.name ? node.name.pos : node.pos, node.end));
84628             var statement = factory.createExpressionStatement(expression);
84629             ts.setSourceMapRange(statement, ts.createRange(-1, node.end));
84630             statements.push(statement);
84631         }
84632         function createNamespaceExport(exportName, exportValue, location) {
84633             return ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.getNamespaceMemberName(currentNamespaceContainerName, exportName, /*allowComments*/ false, /*allowSourceMaps*/ true), exportValue)), location);
84634         }
84635         function createNamespaceExportExpression(exportName, exportValue, location) {
84636             return ts.setTextRange(factory.createAssignment(getNamespaceMemberNameWithSourceMapsAndWithoutComments(exportName), exportValue), location);
84637         }
84638         function getNamespaceMemberNameWithSourceMapsAndWithoutComments(name) {
84639             return factory.getNamespaceMemberName(currentNamespaceContainerName, name, /*allowComments*/ false, /*allowSourceMaps*/ true);
84640         }
84641         /**
84642          * Gets the declaration name used inside of a namespace or enum.
84643          */
84644         function getNamespaceParameterName(node) {
84645             var name = factory.getGeneratedNameForNode(node);
84646             ts.setSourceMapRange(name, node.name);
84647             return name;
84648         }
84649         /**
84650          * Gets the expression used to refer to a namespace or enum within the body
84651          * of its declaration.
84652          */
84653         function getNamespaceContainerName(node) {
84654             return factory.getGeneratedNameForNode(node);
84655         }
84656         /**
84657          * Gets a local alias for a class declaration if it is a decorated class with an internal
84658          * reference to the static side of the class. This is necessary to avoid issues with
84659          * double-binding semantics for the class name.
84660          */
84661         function getClassAliasIfNeeded(node) {
84662             if (resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */) {
84663                 enableSubstitutionForClassAliases();
84664                 var classAlias = factory.createUniqueName(node.name && !ts.isGeneratedIdentifier(node.name) ? ts.idText(node.name) : "default");
84665                 classAliases[ts.getOriginalNodeId(node)] = classAlias;
84666                 hoistVariableDeclaration(classAlias);
84667                 return classAlias;
84668             }
84669         }
84670         function getClassPrototype(node) {
84671             return factory.createPropertyAccessExpression(factory.getDeclarationName(node), "prototype");
84672         }
84673         function getClassMemberPrefix(node, member) {
84674             return ts.hasSyntacticModifier(member, 32 /* Static */)
84675                 ? factory.getDeclarationName(node)
84676                 : getClassPrototype(node);
84677         }
84678         function enableSubstitutionForNonQualifiedEnumMembers() {
84679             if ((enabledSubstitutions & 8 /* NonQualifiedEnumMembers */) === 0) {
84680                 enabledSubstitutions |= 8 /* NonQualifiedEnumMembers */;
84681                 context.enableSubstitution(78 /* Identifier */);
84682             }
84683         }
84684         function enableSubstitutionForClassAliases() {
84685             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
84686                 enabledSubstitutions |= 1 /* ClassAliases */;
84687                 // We need to enable substitutions for identifiers. This allows us to
84688                 // substitute class names inside of a class declaration.
84689                 context.enableSubstitution(78 /* Identifier */);
84690                 // Keep track of class aliases.
84691                 classAliases = [];
84692             }
84693         }
84694         function enableSubstitutionForNamespaceExports() {
84695             if ((enabledSubstitutions & 2 /* NamespaceExports */) === 0) {
84696                 enabledSubstitutions |= 2 /* NamespaceExports */;
84697                 // We need to enable substitutions for identifiers and shorthand property assignments. This allows us to
84698                 // substitute the names of exported members of a namespace.
84699                 context.enableSubstitution(78 /* Identifier */);
84700                 context.enableSubstitution(289 /* ShorthandPropertyAssignment */);
84701                 // We need to be notified when entering and exiting namespaces.
84702                 context.enableEmitNotification(256 /* ModuleDeclaration */);
84703             }
84704         }
84705         function isTransformedModuleDeclaration(node) {
84706             return ts.getOriginalNode(node).kind === 256 /* ModuleDeclaration */;
84707         }
84708         function isTransformedEnumDeclaration(node) {
84709             return ts.getOriginalNode(node).kind === 255 /* EnumDeclaration */;
84710         }
84711         /**
84712          * Hook for node emit.
84713          *
84714          * @param hint A hint as to the intended usage of the node.
84715          * @param node The node to emit.
84716          * @param emit A callback used to emit the node in the printer.
84717          */
84718         function onEmitNode(hint, node, emitCallback) {
84719             var savedApplicableSubstitutions = applicableSubstitutions;
84720             var savedCurrentSourceFile = currentSourceFile;
84721             if (ts.isSourceFile(node)) {
84722                 currentSourceFile = node;
84723             }
84724             if (enabledSubstitutions & 2 /* NamespaceExports */ && isTransformedModuleDeclaration(node)) {
84725                 applicableSubstitutions |= 2 /* NamespaceExports */;
84726             }
84727             if (enabledSubstitutions & 8 /* NonQualifiedEnumMembers */ && isTransformedEnumDeclaration(node)) {
84728                 applicableSubstitutions |= 8 /* NonQualifiedEnumMembers */;
84729             }
84730             previousOnEmitNode(hint, node, emitCallback);
84731             applicableSubstitutions = savedApplicableSubstitutions;
84732             currentSourceFile = savedCurrentSourceFile;
84733         }
84734         /**
84735          * Hooks node substitutions.
84736          *
84737          * @param hint A hint as to the intended usage of the node.
84738          * @param node The node to substitute.
84739          */
84740         function onSubstituteNode(hint, node) {
84741             node = previousOnSubstituteNode(hint, node);
84742             if (hint === 1 /* Expression */) {
84743                 return substituteExpression(node);
84744             }
84745             else if (ts.isShorthandPropertyAssignment(node)) {
84746                 return substituteShorthandPropertyAssignment(node);
84747             }
84748             return node;
84749         }
84750         function substituteShorthandPropertyAssignment(node) {
84751             if (enabledSubstitutions & 2 /* NamespaceExports */) {
84752                 var name = node.name;
84753                 var exportedName = trySubstituteNamespaceExportedName(name);
84754                 if (exportedName) {
84755                     // A shorthand property with an assignment initializer is probably part of a
84756                     // destructuring assignment
84757                     if (node.objectAssignmentInitializer) {
84758                         var initializer = factory.createAssignment(exportedName, node.objectAssignmentInitializer);
84759                         return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
84760                     }
84761                     return ts.setTextRange(factory.createPropertyAssignment(name, exportedName), node);
84762                 }
84763             }
84764             return node;
84765         }
84766         function substituteExpression(node) {
84767             switch (node.kind) {
84768                 case 78 /* Identifier */:
84769                     return substituteExpressionIdentifier(node);
84770                 case 201 /* PropertyAccessExpression */:
84771                     return substitutePropertyAccessExpression(node);
84772                 case 202 /* ElementAccessExpression */:
84773                     return substituteElementAccessExpression(node);
84774             }
84775             return node;
84776         }
84777         function substituteExpressionIdentifier(node) {
84778             return trySubstituteClassAlias(node)
84779                 || trySubstituteNamespaceExportedName(node)
84780                 || node;
84781         }
84782         function trySubstituteClassAlias(node) {
84783             if (enabledSubstitutions & 1 /* ClassAliases */) {
84784                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
84785                     // Due to the emit for class decorators, any reference to the class from inside of the class body
84786                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
84787                     // behavior of class names in ES6.
84788                     // Also, when emitting statics for class expressions, we must substitute a class alias for
84789                     // constructor references in static property initializers.
84790                     var declaration = resolver.getReferencedValueDeclaration(node);
84791                     if (declaration) {
84792                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
84793                         if (classAlias) {
84794                             var clone_1 = factory.cloneNode(classAlias);
84795                             ts.setSourceMapRange(clone_1, node);
84796                             ts.setCommentRange(clone_1, node);
84797                             return clone_1;
84798                         }
84799                     }
84800                 }
84801             }
84802             return undefined;
84803         }
84804         function trySubstituteNamespaceExportedName(node) {
84805             // If this is explicitly a local name, do not substitute.
84806             if (enabledSubstitutions & applicableSubstitutions && !ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
84807                 // If we are nested within a namespace declaration, we may need to qualifiy
84808                 // an identifier that is exported from a merged namespace.
84809                 var container = resolver.getReferencedExportContainer(node, /*prefixLocals*/ false);
84810                 if (container && container.kind !== 297 /* SourceFile */) {
84811                     var substitute = (applicableSubstitutions & 2 /* NamespaceExports */ && container.kind === 256 /* ModuleDeclaration */) ||
84812                         (applicableSubstitutions & 8 /* NonQualifiedEnumMembers */ && container.kind === 255 /* EnumDeclaration */);
84813                     if (substitute) {
84814                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(container), node), 
84815                         /*location*/ node);
84816                     }
84817                 }
84818             }
84819             return undefined;
84820         }
84821         function substitutePropertyAccessExpression(node) {
84822             return substituteConstantValue(node);
84823         }
84824         function substituteElementAccessExpression(node) {
84825             return substituteConstantValue(node);
84826         }
84827         function substituteConstantValue(node) {
84828             var constantValue = tryGetConstEnumValue(node);
84829             if (constantValue !== undefined) {
84830                 // track the constant value on the node for the printer in needsDotDotForPropertyAccess
84831                 ts.setConstantValue(node, constantValue);
84832                 var substitute = typeof constantValue === "string" ? factory.createStringLiteral(constantValue) : factory.createNumericLiteral(constantValue);
84833                 if (!compilerOptions.removeComments) {
84834                     var originalNode = ts.getOriginalNode(node, ts.isAccessExpression);
84835                     var propertyName = ts.isPropertyAccessExpression(originalNode)
84836                         ? ts.declarationNameToString(originalNode.name)
84837                         : ts.getTextOfNode(originalNode.argumentExpression);
84838                     ts.addSyntheticTrailingComment(substitute, 3 /* MultiLineCommentTrivia */, " " + propertyName + " ");
84839                 }
84840                 return substitute;
84841             }
84842             return node;
84843         }
84844         function tryGetConstEnumValue(node) {
84845             if (compilerOptions.isolatedModules) {
84846                 return undefined;
84847             }
84848             return ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node) ? resolver.getConstantValue(node) : undefined;
84849         }
84850     }
84851     ts.transformTypeScript = transformTypeScript;
84852 })(ts || (ts = {}));
84853 /*@internal*/
84854 var ts;
84855 (function (ts) {
84856     var ClassPropertySubstitutionFlags;
84857     (function (ClassPropertySubstitutionFlags) {
84858         /**
84859          * Enables substitutions for class expressions with static fields
84860          * which have initializers that reference the class name.
84861          */
84862         ClassPropertySubstitutionFlags[ClassPropertySubstitutionFlags["ClassAliases"] = 1] = "ClassAliases";
84863     })(ClassPropertySubstitutionFlags || (ClassPropertySubstitutionFlags = {}));
84864     var PrivateIdentifierPlacement;
84865     (function (PrivateIdentifierPlacement) {
84866         PrivateIdentifierPlacement[PrivateIdentifierPlacement["InstanceField"] = 0] = "InstanceField";
84867     })(PrivateIdentifierPlacement || (PrivateIdentifierPlacement = {}));
84868     /**
84869      * Transforms ECMAScript Class Syntax.
84870      * TypeScript parameter property syntax is transformed in the TypeScript transformer.
84871      * For now, this transforms public field declarations using TypeScript class semantics,
84872      * where declarations are elided and initializers are transformed as assignments in the constructor.
84873      * When --useDefineForClassFields is on, this transforms to ECMAScript semantics, with Object.defineProperty.
84874      */
84875     function transformClassFields(context) {
84876         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration, endLexicalEnvironment = context.endLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment;
84877         var resolver = context.getEmitResolver();
84878         var compilerOptions = context.getCompilerOptions();
84879         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
84880         var shouldTransformPrivateFields = languageVersion < 99 /* ESNext */;
84881         var previousOnSubstituteNode = context.onSubstituteNode;
84882         context.onSubstituteNode = onSubstituteNode;
84883         var enabledSubstitutions;
84884         var classAliases;
84885         /**
84886          * Tracks what computed name expressions originating from elided names must be inlined
84887          * at the next execution site, in document order
84888          */
84889         var pendingExpressions;
84890         /**
84891          * Tracks what computed name expression statements and static property initializers must be
84892          * emitted at the next execution site, in document order (for decorated classes).
84893          */
84894         var pendingStatements;
84895         var privateIdentifierEnvironmentStack = [];
84896         var currentPrivateIdentifierEnvironment;
84897         return ts.chainBundle(context, transformSourceFile);
84898         function transformSourceFile(node) {
84899             var options = context.getCompilerOptions();
84900             if (node.isDeclarationFile
84901                 || options.useDefineForClassFields && options.target === 99 /* ESNext */) {
84902                 return node;
84903             }
84904             var visited = ts.visitEachChild(node, visitor, context);
84905             ts.addEmitHelpers(visited, context.readEmitHelpers());
84906             return visited;
84907         }
84908         function visitor(node) {
84909             if (!(node.transformFlags & 4194304 /* ContainsClassFields */))
84910                 return node;
84911             switch (node.kind) {
84912                 case 221 /* ClassExpression */:
84913                 case 252 /* ClassDeclaration */:
84914                     return visitClassLike(node);
84915                 case 163 /* PropertyDeclaration */:
84916                     return visitPropertyDeclaration(node);
84917                 case 232 /* VariableStatement */:
84918                     return visitVariableStatement(node);
84919                 case 158 /* ComputedPropertyName */:
84920                     return visitComputedPropertyName(node);
84921                 case 201 /* PropertyAccessExpression */:
84922                     return visitPropertyAccessExpression(node);
84923                 case 214 /* PrefixUnaryExpression */:
84924                     return visitPrefixUnaryExpression(node);
84925                 case 215 /* PostfixUnaryExpression */:
84926                     return visitPostfixUnaryExpression(node, /*valueIsDiscarded*/ false);
84927                 case 203 /* CallExpression */:
84928                     return visitCallExpression(node);
84929                 case 216 /* BinaryExpression */:
84930                     return visitBinaryExpression(node);
84931                 case 79 /* PrivateIdentifier */:
84932                     return visitPrivateIdentifier(node);
84933                 case 233 /* ExpressionStatement */:
84934                     return visitExpressionStatement(node);
84935                 case 237 /* ForStatement */:
84936                     return visitForStatement(node);
84937                 case 205 /* TaggedTemplateExpression */:
84938                     return visitTaggedTemplateExpression(node);
84939             }
84940             return ts.visitEachChild(node, visitor, context);
84941         }
84942         function visitorDestructuringTarget(node) {
84943             switch (node.kind) {
84944                 case 200 /* ObjectLiteralExpression */:
84945                 case 199 /* ArrayLiteralExpression */:
84946                     return visitAssignmentPattern(node);
84947                 default:
84948                     return visitor(node);
84949             }
84950         }
84951         /**
84952          * If we visit a private name, this means it is an undeclared private name.
84953          * Replace it with an empty identifier to indicate a problem with the code.
84954          */
84955         function visitPrivateIdentifier(node) {
84956             if (!shouldTransformPrivateFields) {
84957                 return node;
84958             }
84959             return ts.setOriginalNode(factory.createIdentifier(""), node);
84960         }
84961         /**
84962          * Visits the members of a class that has fields.
84963          *
84964          * @param node The node to visit.
84965          */
84966         function classElementVisitor(node) {
84967             switch (node.kind) {
84968                 case 166 /* Constructor */:
84969                     // Constructors for classes using class fields are transformed in
84970                     // `visitClassDeclaration` or `visitClassExpression`.
84971                     return undefined;
84972                 case 167 /* GetAccessor */:
84973                 case 168 /* SetAccessor */:
84974                 case 165 /* MethodDeclaration */:
84975                     // Visit the name of the member (if it's a computed property name).
84976                     return ts.visitEachChild(node, classElementVisitor, context);
84977                 case 163 /* PropertyDeclaration */:
84978                     return visitPropertyDeclaration(node);
84979                 case 158 /* ComputedPropertyName */:
84980                     return visitComputedPropertyName(node);
84981                 case 229 /* SemicolonClassElement */:
84982                     return node;
84983                 default:
84984                     return visitor(node);
84985             }
84986         }
84987         function visitVariableStatement(node) {
84988             var savedPendingStatements = pendingStatements;
84989             pendingStatements = [];
84990             var visitedNode = ts.visitEachChild(node, visitor, context);
84991             var statement = ts.some(pendingStatements) ? __spreadArrays([visitedNode], pendingStatements) :
84992                 visitedNode;
84993             pendingStatements = savedPendingStatements;
84994             return statement;
84995         }
84996         function visitComputedPropertyName(name) {
84997             var node = ts.visitEachChild(name, visitor, context);
84998             if (ts.some(pendingExpressions)) {
84999                 var expressions = pendingExpressions;
85000                 expressions.push(name.expression);
85001                 pendingExpressions = [];
85002                 node = factory.updateComputedPropertyName(node, factory.inlineExpressions(expressions));
85003             }
85004             return node;
85005         }
85006         function visitPropertyDeclaration(node) {
85007             ts.Debug.assert(!ts.some(node.decorators));
85008             if (!shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
85009                 // Initializer is elided as the field is initialized in transformConstructor.
85010                 return factory.updatePropertyDeclaration(node, 
85011                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.name, 
85012                 /*questionOrExclamationToken*/ undefined, 
85013                 /*type*/ undefined, 
85014                 /*initializer*/ undefined);
85015             }
85016             // Create a temporary variable to store a computed property name (if necessary).
85017             // If it's not inlineable, then we emit an expression after the class which assigns
85018             // the property name to the temporary variable.
85019             var expr = getPropertyNameExpressionIfNeeded(node.name, !!node.initializer || !!context.getCompilerOptions().useDefineForClassFields);
85020             if (expr && !ts.isSimpleInlineableExpression(expr)) {
85021                 getPendingExpressions().push(expr);
85022             }
85023             return undefined;
85024         }
85025         function createPrivateIdentifierAccess(info, receiver) {
85026             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
85027             switch (info.placement) {
85028                 case 0 /* InstanceField */:
85029                     return context.getEmitHelperFactory().createClassPrivateFieldGetHelper(ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver), info.weakMapName);
85030                 default: return ts.Debug.fail("Unexpected private identifier placement");
85031             }
85032         }
85033         function visitPropertyAccessExpression(node) {
85034             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(node.name)) {
85035                 var privateIdentifierInfo = accessPrivateIdentifier(node.name);
85036                 if (privateIdentifierInfo) {
85037                     return ts.setOriginalNode(createPrivateIdentifierAccess(privateIdentifierInfo, node.expression), node);
85038                 }
85039             }
85040             return ts.visitEachChild(node, visitor, context);
85041         }
85042         function visitPrefixUnaryExpression(node) {
85043             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
85044                 var operator = node.operator === 45 /* PlusPlusToken */ ?
85045                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
85046                     40 /* MinusToken */ : undefined;
85047                 var info = void 0;
85048                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
85049                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
85050                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
85051                     var existingValue = factory.createPrefixUnaryExpression(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
85052                     return ts.setOriginalNode(createPrivateIdentifierAssignment(info, initializeExpression || readExpression, factory.createBinaryExpression(existingValue, operator, factory.createNumericLiteral(1)), 62 /* EqualsToken */), node);
85053                 }
85054             }
85055             return ts.visitEachChild(node, visitor, context);
85056         }
85057         function visitPostfixUnaryExpression(node, valueIsDiscarded) {
85058             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.operand)) {
85059                 var operator = node.operator === 45 /* PlusPlusToken */ ?
85060                     39 /* PlusToken */ : node.operator === 46 /* MinusMinusToken */ ?
85061                     40 /* MinusToken */ : undefined;
85062                 var info = void 0;
85063                 if (operator && (info = accessPrivateIdentifier(node.operand.name))) {
85064                     var receiver = ts.visitNode(node.operand.expression, visitor, ts.isExpression);
85065                     var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
85066                     var existingValue = factory.createPrefixUnaryExpression(39 /* PlusToken */, createPrivateIdentifierAccess(info, readExpression));
85067                     // Create a temporary variable to store the value returned by the expression.
85068                     var returnValue = valueIsDiscarded ? undefined : factory.createTempVariable(hoistVariableDeclaration);
85069                     return ts.setOriginalNode(factory.inlineExpressions(ts.compact([
85070                         createPrivateIdentifierAssignment(info, initializeExpression || readExpression, factory.createBinaryExpression(returnValue ? factory.createAssignment(returnValue, existingValue) : existingValue, operator, factory.createNumericLiteral(1)), 62 /* EqualsToken */),
85071                         returnValue
85072                     ])), node);
85073                 }
85074             }
85075             return ts.visitEachChild(node, visitor, context);
85076         }
85077         function visitForStatement(node) {
85078             if (node.incrementor && ts.isPostfixUnaryExpression(node.incrementor)) {
85079                 return factory.updateForStatement(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));
85080             }
85081             return ts.visitEachChild(node, visitor, context);
85082         }
85083         function visitExpressionStatement(node) {
85084             if (ts.isPostfixUnaryExpression(node.expression)) {
85085                 return factory.updateExpressionStatement(node, visitPostfixUnaryExpression(node.expression, /*valueIsDiscarded*/ true));
85086             }
85087             return ts.visitEachChild(node, visitor, context);
85088         }
85089         function createCopiableReceiverExpr(receiver) {
85090             var clone = ts.nodeIsSynthesized(receiver) ? receiver : factory.cloneNode(receiver);
85091             if (ts.isSimpleInlineableExpression(receiver)) {
85092                 return { readExpression: clone, initializeExpression: undefined };
85093             }
85094             var readExpression = factory.createTempVariable(hoistVariableDeclaration);
85095             var initializeExpression = factory.createAssignment(readExpression, clone);
85096             return { readExpression: readExpression, initializeExpression: initializeExpression };
85097         }
85098         function visitCallExpression(node) {
85099             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.expression)) {
85100                 // Transform call expressions of private names to properly bind the `this` parameter.
85101                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
85102                 return factory.updateCallExpression(node, factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "call"), 
85103                 /*typeArguments*/ undefined, __spreadArrays([ts.visitNode(thisArg, visitor, ts.isExpression)], ts.visitNodes(node.arguments, visitor, ts.isExpression)));
85104             }
85105             return ts.visitEachChild(node, visitor, context);
85106         }
85107         function visitTaggedTemplateExpression(node) {
85108             if (shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyAccessExpression(node.tag)) {
85109                 // Bind the `this` correctly for tagged template literals when the tag is a private identifier property access.
85110                 var _a = factory.createCallBinding(node.tag, hoistVariableDeclaration, languageVersion), thisArg = _a.thisArg, target = _a.target;
85111                 return factory.updateTaggedTemplateExpression(node, factory.createCallExpression(factory.createPropertyAccessExpression(ts.visitNode(target, visitor), "bind"), 
85112                 /*typeArguments*/ undefined, [ts.visitNode(thisArg, visitor, ts.isExpression)]), 
85113                 /*typeArguments*/ undefined, ts.visitNode(node.template, visitor, ts.isTemplateLiteral));
85114             }
85115             return ts.visitEachChild(node, visitor, context);
85116         }
85117         function visitBinaryExpression(node) {
85118             if (shouldTransformPrivateFields) {
85119                 if (ts.isDestructuringAssignment(node)) {
85120                     var savedPendingExpressions = pendingExpressions;
85121                     pendingExpressions = undefined;
85122                     node = factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorDestructuringTarget), node.operatorToken, ts.visitNode(node.right, visitor));
85123                     var expr = ts.some(pendingExpressions) ?
85124                         factory.inlineExpressions(ts.compact(__spreadArrays(pendingExpressions, [node]))) :
85125                         node;
85126                     pendingExpressions = savedPendingExpressions;
85127                     return expr;
85128                 }
85129                 if (ts.isAssignmentExpression(node) && ts.isPrivateIdentifierPropertyAccessExpression(node.left)) {
85130                     var info = accessPrivateIdentifier(node.left.name);
85131                     if (info) {
85132                         return ts.setOriginalNode(createPrivateIdentifierAssignment(info, node.left.expression, node.right, node.operatorToken.kind), node);
85133                     }
85134                 }
85135             }
85136             return ts.visitEachChild(node, visitor, context);
85137         }
85138         function createPrivateIdentifierAssignment(info, receiver, right, operator) {
85139             switch (info.placement) {
85140                 case 0 /* InstanceField */: {
85141                     return createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator);
85142                 }
85143                 default: return ts.Debug.fail("Unexpected private identifier placement");
85144             }
85145         }
85146         function createPrivateIdentifierInstanceFieldAssignment(info, receiver, right, operator) {
85147             receiver = ts.visitNode(receiver, visitor, ts.isExpression);
85148             right = ts.visitNode(right, visitor, ts.isExpression);
85149             if (ts.isCompoundAssignment(operator)) {
85150                 var _a = createCopiableReceiverExpr(receiver), readExpression = _a.readExpression, initializeExpression = _a.initializeExpression;
85151                 return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(initializeExpression || readExpression, info.weakMapName, factory.createBinaryExpression(context.getEmitHelperFactory().createClassPrivateFieldGetHelper(readExpression, info.weakMapName), ts.getNonAssignmentOperatorForCompoundAssignment(operator), right));
85152             }
85153             else {
85154                 return context.getEmitHelperFactory().createClassPrivateFieldSetHelper(receiver, info.weakMapName, right);
85155             }
85156         }
85157         /**
85158          * Set up the environment for a class.
85159          */
85160         function visitClassLike(node) {
85161             var savedPendingExpressions = pendingExpressions;
85162             pendingExpressions = undefined;
85163             if (shouldTransformPrivateFields) {
85164                 startPrivateIdentifierEnvironment();
85165             }
85166             var result = ts.isClassDeclaration(node) ?
85167                 visitClassDeclaration(node) :
85168                 visitClassExpression(node);
85169             if (shouldTransformPrivateFields) {
85170                 endPrivateIdentifierEnvironment();
85171             }
85172             pendingExpressions = savedPendingExpressions;
85173             return result;
85174         }
85175         function doesClassElementNeedTransform(node) {
85176             return ts.isPropertyDeclaration(node) || (shouldTransformPrivateFields && node.name && ts.isPrivateIdentifier(node.name));
85177         }
85178         function visitClassDeclaration(node) {
85179             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
85180                 return ts.visitEachChild(node, visitor, context);
85181             }
85182             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
85183             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */);
85184             var statements = [
85185                 factory.updateClassDeclaration(node, 
85186                 /*decorators*/ undefined, node.modifiers, node.name, 
85187                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass))
85188             ];
85189             // Write any pending expressions from elided or moved computed property names
85190             if (ts.some(pendingExpressions)) {
85191                 statements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
85192             }
85193             // Emit static property assignment. Because classDeclaration is lexically evaluated,
85194             // it is safe to emit static property assignment after classDeclaration
85195             // From ES6 specification:
85196             //      HasLexicalDeclaration (N) : Determines if the argument identifier has a binding in this environment record that was created using
85197             //                                  a lexical declaration such as a LexicalDeclaration or a ClassDeclaration.
85198             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
85199             if (ts.some(staticProperties)) {
85200                 addPropertyStatements(statements, staticProperties, factory.getInternalName(node));
85201             }
85202             return statements;
85203         }
85204         function visitClassExpression(node) {
85205             if (!ts.forEach(node.members, doesClassElementNeedTransform)) {
85206                 return ts.visitEachChild(node, visitor, context);
85207             }
85208             // If this class expression is a transformation of a decorated class declaration,
85209             // then we want to output the pendingExpressions as statements, not as inlined
85210             // expressions with the class statement.
85211             //
85212             // In this case, we use pendingStatements to produce the same output as the
85213             // class declaration transformation. The VariableStatement visitor will insert
85214             // these statements after the class expression variable statement.
85215             var isDecoratedClassDeclaration = ts.isClassDeclaration(ts.getOriginalNode(node));
85216             var staticProperties = ts.getProperties(node, /*requireInitializer*/ true, /*isStatic*/ true);
85217             var extendsClauseElement = ts.getEffectiveBaseTypeNode(node);
85218             var isDerivedClass = !!(extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */);
85219             var classExpression = factory.updateClassExpression(node, ts.visitNodes(node.decorators, visitor, ts.isDecorator), node.modifiers, node.name, 
85220             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, visitor, ts.isHeritageClause), transformClassMembers(node, isDerivedClass));
85221             if (ts.some(staticProperties) || ts.some(pendingExpressions)) {
85222                 if (isDecoratedClassDeclaration) {
85223                     ts.Debug.assertIsDefined(pendingStatements, "Decorated classes transformed by TypeScript are expected to be within a variable declaration.");
85224                     // Write any pending expressions from elided or moved computed property names
85225                     if (pendingStatements && pendingExpressions && ts.some(pendingExpressions)) {
85226                         pendingStatements.push(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
85227                     }
85228                     if (pendingStatements && ts.some(staticProperties)) {
85229                         addPropertyStatements(pendingStatements, staticProperties, factory.getInternalName(node));
85230                     }
85231                     return classExpression;
85232                 }
85233                 else {
85234                     var expressions = [];
85235                     var isClassWithConstructorReference = resolver.getNodeCheckFlags(node) & 16777216 /* ClassWithConstructorReference */;
85236                     var temp = factory.createTempVariable(hoistVariableDeclaration, !!isClassWithConstructorReference);
85237                     if (isClassWithConstructorReference) {
85238                         // record an alias as the class name is not in scope for statics.
85239                         enableSubstitutionForClassAliases();
85240                         var alias = factory.cloneNode(temp);
85241                         alias.autoGenerateFlags &= ~8 /* ReservedInNestedScopes */;
85242                         classAliases[ts.getOriginalNodeId(node)] = alias;
85243                     }
85244                     // To preserve the behavior of the old emitter, we explicitly indent
85245                     // the body of a class with static initializers.
85246                     ts.setEmitFlags(classExpression, 65536 /* Indented */ | ts.getEmitFlags(classExpression));
85247                     expressions.push(ts.startOnNewLine(factory.createAssignment(temp, classExpression)));
85248                     // Add any pending expressions leftover from elided or relocated computed property names
85249                     ts.addRange(expressions, ts.map(pendingExpressions, ts.startOnNewLine));
85250                     ts.addRange(expressions, generateInitializedPropertyExpressions(staticProperties, temp));
85251                     expressions.push(ts.startOnNewLine(temp));
85252                     return factory.inlineExpressions(expressions);
85253                 }
85254             }
85255             return classExpression;
85256         }
85257         function transformClassMembers(node, isDerivedClass) {
85258             if (shouldTransformPrivateFields) {
85259                 // Declare private names.
85260                 for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
85261                     var member = _a[_i];
85262                     if (ts.isPrivateIdentifierPropertyDeclaration(member)) {
85263                         addPrivateIdentifierToEnvironment(member.name);
85264                     }
85265                 }
85266             }
85267             var members = [];
85268             var constructor = transformConstructor(node, isDerivedClass);
85269             if (constructor) {
85270                 members.push(constructor);
85271             }
85272             ts.addRange(members, ts.visitNodes(node.members, classElementVisitor, ts.isClassElement));
85273             return ts.setTextRange(factory.createNodeArray(members), /*location*/ node.members);
85274         }
85275         function isPropertyDeclarationThatRequiresConstructorStatement(member) {
85276             if (!ts.isPropertyDeclaration(member) || ts.hasStaticModifier(member)) {
85277                 return false;
85278             }
85279             if (context.getCompilerOptions().useDefineForClassFields) {
85280                 // If we are using define semantics and targeting ESNext or higher,
85281                 // then we don't need to transform any class properties.
85282                 return languageVersion < 99 /* ESNext */;
85283             }
85284             return ts.isInitializedProperty(member) || shouldTransformPrivateFields && ts.isPrivateIdentifierPropertyDeclaration(member);
85285         }
85286         function transformConstructor(node, isDerivedClass) {
85287             var constructor = ts.visitNode(ts.getFirstConstructorWithBody(node), visitor, ts.isConstructorDeclaration);
85288             var properties = node.members.filter(isPropertyDeclarationThatRequiresConstructorStatement);
85289             if (!ts.some(properties)) {
85290                 return constructor;
85291             }
85292             var parameters = ts.visitParameterList(constructor ? constructor.parameters : undefined, visitor, context);
85293             var body = transformConstructorBody(node, constructor, isDerivedClass);
85294             if (!body) {
85295                 return undefined;
85296             }
85297             return ts.startOnNewLine(ts.setOriginalNode(ts.setTextRange(factory.createConstructorDeclaration(
85298             /*decorators*/ undefined, 
85299             /*modifiers*/ undefined, parameters !== null && parameters !== void 0 ? parameters : [], body), constructor || node), constructor));
85300         }
85301         function transformConstructorBody(node, constructor, isDerivedClass) {
85302             var useDefineForClassFields = context.getCompilerOptions().useDefineForClassFields;
85303             var properties = ts.getProperties(node, /*requireInitializer*/ false, /*isStatic*/ false);
85304             if (!useDefineForClassFields) {
85305                 properties = ts.filter(properties, function (property) { return !!property.initializer || ts.isPrivateIdentifier(property.name); });
85306             }
85307             // Only generate synthetic constructor when there are property initializers to move.
85308             if (!constructor && !ts.some(properties)) {
85309                 return ts.visitFunctionBody(/*node*/ undefined, visitor, context);
85310             }
85311             resumeLexicalEnvironment();
85312             var indexOfFirstStatement = 0;
85313             var statements = [];
85314             if (!constructor && isDerivedClass) {
85315                 // Add a synthetic `super` call:
85316                 //
85317                 //  super(...arguments);
85318                 //
85319                 statements.push(factory.createExpressionStatement(factory.createCallExpression(factory.createSuper(), 
85320                 /*typeArguments*/ undefined, [factory.createSpreadElement(factory.createIdentifier("arguments"))])));
85321             }
85322             if (constructor) {
85323                 indexOfFirstStatement = ts.addPrologueDirectivesAndInitialSuperCall(factory, constructor, statements, visitor);
85324             }
85325             // Add the property initializers. Transforms this:
85326             //
85327             //  public x = 1;
85328             //
85329             // Into this:
85330             //
85331             //  constructor() {
85332             //      this.x = 1;
85333             //  }
85334             //
85335             if (constructor === null || constructor === void 0 ? void 0 : constructor.body) {
85336                 var afterParameterProperties = ts.findIndex(constructor.body.statements, function (s) { return !ts.isParameterPropertyDeclaration(ts.getOriginalNode(s), constructor); }, indexOfFirstStatement);
85337                 if (afterParameterProperties === -1) {
85338                     afterParameterProperties = constructor.body.statements.length;
85339                 }
85340                 if (afterParameterProperties > indexOfFirstStatement) {
85341                     if (!useDefineForClassFields) {
85342                         ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement, afterParameterProperties - indexOfFirstStatement));
85343                     }
85344                     indexOfFirstStatement = afterParameterProperties;
85345                 }
85346             }
85347             addPropertyStatements(statements, properties, factory.createThis());
85348             // Add existing statements, skipping the initial super call.
85349             if (constructor) {
85350                 ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, indexOfFirstStatement));
85351             }
85352             statements = factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
85353             return ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), 
85354             /*location*/ constructor ? constructor.body.statements : node.members), 
85355             /*multiLine*/ true), 
85356             /*location*/ constructor ? constructor.body : undefined);
85357         }
85358         /**
85359          * Generates assignment statements for property initializers.
85360          *
85361          * @param properties An array of property declarations to transform.
85362          * @param receiver The receiver on which each property should be assigned.
85363          */
85364         function addPropertyStatements(statements, properties, receiver) {
85365             for (var _i = 0, properties_7 = properties; _i < properties_7.length; _i++) {
85366                 var property = properties_7[_i];
85367                 var expression = transformProperty(property, receiver);
85368                 if (!expression) {
85369                     continue;
85370                 }
85371                 var statement = factory.createExpressionStatement(expression);
85372                 ts.setSourceMapRange(statement, ts.moveRangePastModifiers(property));
85373                 ts.setCommentRange(statement, property);
85374                 ts.setOriginalNode(statement, property);
85375                 statements.push(statement);
85376             }
85377         }
85378         /**
85379          * Generates assignment expressions for property initializers.
85380          *
85381          * @param properties An array of property declarations to transform.
85382          * @param receiver The receiver on which each property should be assigned.
85383          */
85384         function generateInitializedPropertyExpressions(properties, receiver) {
85385             var expressions = [];
85386             for (var _i = 0, properties_8 = properties; _i < properties_8.length; _i++) {
85387                 var property = properties_8[_i];
85388                 var expression = transformProperty(property, receiver);
85389                 if (!expression) {
85390                     continue;
85391                 }
85392                 ts.startOnNewLine(expression);
85393                 ts.setSourceMapRange(expression, ts.moveRangePastModifiers(property));
85394                 ts.setCommentRange(expression, property);
85395                 ts.setOriginalNode(expression, property);
85396                 expressions.push(expression);
85397             }
85398             return expressions;
85399         }
85400         /**
85401          * Transforms a property initializer into an assignment statement.
85402          *
85403          * @param property The property declaration.
85404          * @param receiver The object receiving the property assignment.
85405          */
85406         function transformProperty(property, receiver) {
85407             var _a;
85408             // We generate a name here in order to reuse the value cached by the relocated computed name expression (which uses the same generated name)
85409             var emitAssignment = !context.getCompilerOptions().useDefineForClassFields;
85410             var propertyName = ts.isComputedPropertyName(property.name) && !ts.isSimpleInlineableExpression(property.name.expression)
85411                 ? factory.updateComputedPropertyName(property.name, factory.getGeneratedNameForNode(property.name))
85412                 : property.name;
85413             if (shouldTransformPrivateFields && ts.isPrivateIdentifier(propertyName)) {
85414                 var privateIdentifierInfo = accessPrivateIdentifier(propertyName);
85415                 if (privateIdentifierInfo) {
85416                     switch (privateIdentifierInfo.placement) {
85417                         case 0 /* InstanceField */: {
85418                             return createPrivateInstanceFieldInitializer(receiver, ts.visitNode(property.initializer, visitor, ts.isExpression), privateIdentifierInfo.weakMapName);
85419                         }
85420                     }
85421                 }
85422                 else {
85423                     ts.Debug.fail("Undeclared private name for property declaration.");
85424                 }
85425             }
85426             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
85427                 return undefined;
85428             }
85429             if (ts.isPrivateIdentifier(propertyName) && !property.initializer) {
85430                 return undefined;
85431             }
85432             var propertyOriginalNode = ts.getOriginalNode(property);
85433             var initializer = property.initializer || emitAssignment ? (_a = ts.visitNode(property.initializer, visitor, ts.isExpression)) !== null && _a !== void 0 ? _a : factory.createVoidZero() : ts.isParameterPropertyDeclaration(propertyOriginalNode, propertyOriginalNode.parent) && ts.isIdentifier(propertyName) ? propertyName
85434                 : factory.createVoidZero();
85435             if (emitAssignment || ts.isPrivateIdentifier(propertyName)) {
85436                 var memberAccess = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ propertyName);
85437                 return factory.createAssignment(memberAccess, initializer);
85438             }
85439             else {
85440                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
85441                     : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
85442                         : propertyName;
85443                 var descriptor = factory.createPropertyDescriptor({ value: initializer, configurable: true, writable: true, enumerable: true });
85444                 return factory.createObjectDefinePropertyCall(receiver, name, descriptor);
85445             }
85446         }
85447         function enableSubstitutionForClassAliases() {
85448             if ((enabledSubstitutions & 1 /* ClassAliases */) === 0) {
85449                 enabledSubstitutions |= 1 /* ClassAliases */;
85450                 // We need to enable substitutions for identifiers. This allows us to
85451                 // substitute class names inside of a class declaration.
85452                 context.enableSubstitution(78 /* Identifier */);
85453                 // Keep track of class aliases.
85454                 classAliases = [];
85455             }
85456         }
85457         /**
85458          * Hooks node substitutions.
85459          *
85460          * @param hint The context for the emitter.
85461          * @param node The node to substitute.
85462          */
85463         function onSubstituteNode(hint, node) {
85464             node = previousOnSubstituteNode(hint, node);
85465             if (hint === 1 /* Expression */) {
85466                 return substituteExpression(node);
85467             }
85468             return node;
85469         }
85470         function substituteExpression(node) {
85471             switch (node.kind) {
85472                 case 78 /* Identifier */:
85473                     return substituteExpressionIdentifier(node);
85474             }
85475             return node;
85476         }
85477         function substituteExpressionIdentifier(node) {
85478             return trySubstituteClassAlias(node) || node;
85479         }
85480         function trySubstituteClassAlias(node) {
85481             if (enabledSubstitutions & 1 /* ClassAliases */) {
85482                 if (resolver.getNodeCheckFlags(node) & 33554432 /* ConstructorReferenceInClass */) {
85483                     // Due to the emit for class decorators, any reference to the class from inside of the class body
85484                     // must instead be rewritten to point to a temporary variable to avoid issues with the double-bind
85485                     // behavior of class names in ES6.
85486                     // Also, when emitting statics for class expressions, we must substitute a class alias for
85487                     // constructor references in static property initializers.
85488                     var declaration = resolver.getReferencedValueDeclaration(node);
85489                     if (declaration) {
85490                         var classAlias = classAliases[declaration.id]; // TODO: GH#18217
85491                         if (classAlias) {
85492                             var clone_2 = factory.cloneNode(classAlias);
85493                             ts.setSourceMapRange(clone_2, node);
85494                             ts.setCommentRange(clone_2, node);
85495                             return clone_2;
85496                         }
85497                     }
85498                 }
85499             }
85500             return undefined;
85501         }
85502         /**
85503          * If the name is a computed property, this function transforms it, then either returns an expression which caches the
85504          * value of the result or the expression itself if the value is either unused or safe to inline into multiple locations
85505          * @param shouldHoist Does the expression need to be reused? (ie, for an initializer or a decorator)
85506          */
85507         function getPropertyNameExpressionIfNeeded(name, shouldHoist) {
85508             if (ts.isComputedPropertyName(name)) {
85509                 var expression = ts.visitNode(name.expression, visitor, ts.isExpression);
85510                 var innerExpression = ts.skipPartiallyEmittedExpressions(expression);
85511                 var inlinable = ts.isSimpleInlineableExpression(innerExpression);
85512                 var alreadyTransformed = ts.isAssignmentExpression(innerExpression) && ts.isGeneratedIdentifier(innerExpression.left);
85513                 if (!alreadyTransformed && !inlinable && shouldHoist) {
85514                     var generatedName = factory.getGeneratedNameForNode(name);
85515                     hoistVariableDeclaration(generatedName);
85516                     return factory.createAssignment(generatedName, expression);
85517                 }
85518                 return (inlinable || ts.isIdentifier(innerExpression)) ? undefined : expression;
85519             }
85520         }
85521         function startPrivateIdentifierEnvironment() {
85522             privateIdentifierEnvironmentStack.push(currentPrivateIdentifierEnvironment);
85523             currentPrivateIdentifierEnvironment = undefined;
85524         }
85525         function endPrivateIdentifierEnvironment() {
85526             currentPrivateIdentifierEnvironment = privateIdentifierEnvironmentStack.pop();
85527         }
85528         function getPrivateIdentifierEnvironment() {
85529             return currentPrivateIdentifierEnvironment || (currentPrivateIdentifierEnvironment = new ts.Map());
85530         }
85531         function getPendingExpressions() {
85532             return pendingExpressions || (pendingExpressions = []);
85533         }
85534         function addPrivateIdentifierToEnvironment(name) {
85535             var text = ts.getTextOfPropertyName(name);
85536             var weakMapName = factory.createUniqueName("_" + text.substring(1), 16 /* Optimistic */ | 8 /* ReservedInNestedScopes */);
85537             hoistVariableDeclaration(weakMapName);
85538             getPrivateIdentifierEnvironment().set(name.escapedText, { placement: 0 /* InstanceField */, weakMapName: weakMapName });
85539             getPendingExpressions().push(factory.createAssignment(weakMapName, factory.createNewExpression(factory.createIdentifier("WeakMap"), 
85540             /*typeArguments*/ undefined, [])));
85541         }
85542         function accessPrivateIdentifier(name) {
85543             if (currentPrivateIdentifierEnvironment) {
85544                 var info = currentPrivateIdentifierEnvironment.get(name.escapedText);
85545                 if (info) {
85546                     return info;
85547                 }
85548             }
85549             for (var i = privateIdentifierEnvironmentStack.length - 1; i >= 0; --i) {
85550                 var env = privateIdentifierEnvironmentStack[i];
85551                 if (!env) {
85552                     continue;
85553                 }
85554                 var info = env.get(name.escapedText);
85555                 if (info) {
85556                     return info;
85557                 }
85558             }
85559             return undefined;
85560         }
85561         function wrapPrivateIdentifierForDestructuringTarget(node) {
85562             var parameter = factory.getGeneratedNameForNode(node);
85563             var info = accessPrivateIdentifier(node.name);
85564             if (!info) {
85565                 return ts.visitEachChild(node, visitor, context);
85566             }
85567             var receiver = node.expression;
85568             // We cannot copy `this` or `super` into the function because they will be bound
85569             // differently inside the function.
85570             if (ts.isThisProperty(node) || ts.isSuperProperty(node) || !ts.isSimpleCopiableExpression(node.expression)) {
85571                 receiver = factory.createTempVariable(hoistVariableDeclaration, /*reservedInNestedScopes*/ true);
85572                 getPendingExpressions().push(factory.createBinaryExpression(receiver, 62 /* EqualsToken */, node.expression));
85573             }
85574             return factory.createPropertyAccessExpression(
85575             // Explicit parens required because of v8 regression (https://bugs.chromium.org/p/v8/issues/detail?id=9560)
85576             factory.createParenthesizedExpression(factory.createObjectLiteralExpression([
85577                 factory.createSetAccessorDeclaration(
85578                 /*decorators*/ undefined, 
85579                 /*modifiers*/ undefined, "value", [factory.createParameterDeclaration(
85580                     /*decorators*/ undefined, 
85581                     /*modifiers*/ undefined, 
85582                     /*dotDotDotToken*/ undefined, parameter, 
85583                     /*questionToken*/ undefined, 
85584                     /*type*/ undefined, 
85585                     /*initializer*/ undefined)], factory.createBlock([factory.createExpressionStatement(createPrivateIdentifierAssignment(info, receiver, parameter, 62 /* EqualsToken */))]))
85586             ])), "value");
85587         }
85588         function visitArrayAssignmentTarget(node) {
85589             var target = ts.getTargetOfBindingOrAssignmentElement(node);
85590             if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
85591                 var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
85592                 if (ts.isAssignmentExpression(node)) {
85593                     return factory.updateBinaryExpression(node, wrapped, node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
85594                 }
85595                 else if (ts.isSpreadElement(node)) {
85596                     return factory.updateSpreadElement(node, wrapped);
85597                 }
85598                 else {
85599                     return wrapped;
85600                 }
85601             }
85602             return ts.visitNode(node, visitorDestructuringTarget);
85603         }
85604         function visitObjectAssignmentTarget(node) {
85605             if (ts.isPropertyAssignment(node)) {
85606                 var target = ts.getTargetOfBindingOrAssignmentElement(node);
85607                 if (target && ts.isPrivateIdentifierPropertyAccessExpression(target)) {
85608                     var initializer = ts.getInitializerOfBindingOrAssignmentElement(node);
85609                     var wrapped = wrapPrivateIdentifierForDestructuringTarget(target);
85610                     return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), initializer ? factory.createAssignment(wrapped, ts.visitNode(initializer, visitor)) : wrapped);
85611                 }
85612                 return factory.updatePropertyAssignment(node, ts.visitNode(node.name, visitor), ts.visitNode(node.initializer, visitorDestructuringTarget));
85613             }
85614             return ts.visitNode(node, visitor);
85615         }
85616         function visitAssignmentPattern(node) {
85617             if (ts.isArrayLiteralExpression(node)) {
85618                 // Transforms private names in destructuring assignment array bindings.
85619                 //
85620                 // Source:
85621                 // ([ this.#myProp ] = [ "hello" ]);
85622                 //
85623                 // Transformation:
85624                 // [ { set value(x) { this.#myProp = x; } }.value ] = [ "hello" ];
85625                 return factory.updateArrayLiteralExpression(node, ts.visitNodes(node.elements, visitArrayAssignmentTarget, ts.isExpression));
85626             }
85627             else {
85628                 // Transforms private names in destructuring assignment object bindings.
85629                 //
85630                 // Source:
85631                 // ({ stringProperty: this.#myProp } = { stringProperty: "hello" });
85632                 //
85633                 // Transformation:
85634                 // ({ stringProperty: { set value(x) { this.#myProp = x; } }.value }) = { stringProperty: "hello" };
85635                 return factory.updateObjectLiteralExpression(node, ts.visitNodes(node.properties, visitObjectAssignmentTarget, ts.isObjectLiteralElementLike));
85636             }
85637         }
85638     }
85639     ts.transformClassFields = transformClassFields;
85640     function createPrivateInstanceFieldInitializer(receiver, initializer, weakMapName) {
85641         return ts.factory.createCallExpression(ts.factory.createPropertyAccessExpression(weakMapName, "set"), 
85642         /*typeArguments*/ undefined, [receiver, initializer || ts.factory.createVoidZero()]);
85643     }
85644 })(ts || (ts = {}));
85645 /*@internal*/
85646 var ts;
85647 (function (ts) {
85648     var ES2017SubstitutionFlags;
85649     (function (ES2017SubstitutionFlags) {
85650         /** Enables substitutions for async methods with `super` calls. */
85651         ES2017SubstitutionFlags[ES2017SubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
85652     })(ES2017SubstitutionFlags || (ES2017SubstitutionFlags = {}));
85653     var ContextFlags;
85654     (function (ContextFlags) {
85655         ContextFlags[ContextFlags["NonTopLevel"] = 1] = "NonTopLevel";
85656         ContextFlags[ContextFlags["HasLexicalThis"] = 2] = "HasLexicalThis";
85657     })(ContextFlags || (ContextFlags = {}));
85658     function transformES2017(context) {
85659         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
85660         var resolver = context.getEmitResolver();
85661         var compilerOptions = context.getCompilerOptions();
85662         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
85663         /**
85664          * Keeps track of whether expression substitution has been enabled for specific edge cases.
85665          * They are persisted between each SourceFile transformation and should not be reset.
85666          */
85667         var enabledSubstitutions;
85668         /**
85669          * This keeps track of containers where `super` is valid, for use with
85670          * just-in-time substitution for `super` expressions inside of async methods.
85671          */
85672         var enclosingSuperContainerFlags = 0;
85673         var enclosingFunctionParameterNames;
85674         /**
85675          * Keeps track of property names accessed on super (`super.x`) within async functions.
85676          */
85677         var capturedSuperProperties;
85678         /** Whether the async function contains an element access on super (`super[x]`). */
85679         var hasSuperElementAccess;
85680         /** A set of node IDs for generated super accessors (variable statements). */
85681         var substitutedSuperAccessors = [];
85682         var contextFlags = 0;
85683         // Save the previous transformation hooks.
85684         var previousOnEmitNode = context.onEmitNode;
85685         var previousOnSubstituteNode = context.onSubstituteNode;
85686         // Set new transformation hooks.
85687         context.onEmitNode = onEmitNode;
85688         context.onSubstituteNode = onSubstituteNode;
85689         return ts.chainBundle(context, transformSourceFile);
85690         function transformSourceFile(node) {
85691             if (node.isDeclarationFile) {
85692                 return node;
85693             }
85694             setContextFlag(1 /* NonTopLevel */, false);
85695             setContextFlag(2 /* HasLexicalThis */, !ts.isEffectiveStrictModeSourceFile(node, compilerOptions));
85696             var visited = ts.visitEachChild(node, visitor, context);
85697             ts.addEmitHelpers(visited, context.readEmitHelpers());
85698             return visited;
85699         }
85700         function setContextFlag(flag, val) {
85701             contextFlags = val ? contextFlags | flag : contextFlags & ~flag;
85702         }
85703         function inContext(flags) {
85704             return (contextFlags & flags) !== 0;
85705         }
85706         function inTopLevelContext() {
85707             return !inContext(1 /* NonTopLevel */);
85708         }
85709         function inHasLexicalThisContext() {
85710             return inContext(2 /* HasLexicalThis */);
85711         }
85712         function doWithContext(flags, cb, value) {
85713             var contextFlagsToSet = flags & ~contextFlags;
85714             if (contextFlagsToSet) {
85715                 setContextFlag(contextFlagsToSet, /*val*/ true);
85716                 var result = cb(value);
85717                 setContextFlag(contextFlagsToSet, /*val*/ false);
85718                 return result;
85719             }
85720             return cb(value);
85721         }
85722         function visitDefault(node) {
85723             return ts.visitEachChild(node, visitor, context);
85724         }
85725         function visitor(node) {
85726             if ((node.transformFlags & 64 /* ContainsES2017 */) === 0) {
85727                 return node;
85728             }
85729             switch (node.kind) {
85730                 case 129 /* AsyncKeyword */:
85731                     // ES2017 async modifier should be elided for targets < ES2017
85732                     return undefined;
85733                 case 213 /* AwaitExpression */:
85734                     return visitAwaitExpression(node);
85735                 case 165 /* MethodDeclaration */:
85736                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitMethodDeclaration, node);
85737                 case 251 /* FunctionDeclaration */:
85738                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionDeclaration, node);
85739                 case 208 /* FunctionExpression */:
85740                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitFunctionExpression, node);
85741                 case 209 /* ArrowFunction */:
85742                     return doWithContext(1 /* NonTopLevel */, visitArrowFunction, node);
85743                 case 201 /* PropertyAccessExpression */:
85744                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) {
85745                         capturedSuperProperties.add(node.name.escapedText);
85746                     }
85747                     return ts.visitEachChild(node, visitor, context);
85748                 case 202 /* ElementAccessExpression */:
85749                     if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) {
85750                         hasSuperElementAccess = true;
85751                     }
85752                     return ts.visitEachChild(node, visitor, context);
85753                 case 167 /* GetAccessor */:
85754                 case 168 /* SetAccessor */:
85755                 case 166 /* Constructor */:
85756                 case 252 /* ClassDeclaration */:
85757                 case 221 /* ClassExpression */:
85758                     return doWithContext(1 /* NonTopLevel */ | 2 /* HasLexicalThis */, visitDefault, node);
85759                 default:
85760                     return ts.visitEachChild(node, visitor, context);
85761             }
85762         }
85763         function asyncBodyVisitor(node) {
85764             if (ts.isNodeWithPossibleHoistedDeclaration(node)) {
85765                 switch (node.kind) {
85766                     case 232 /* VariableStatement */:
85767                         return visitVariableStatementInAsyncBody(node);
85768                     case 237 /* ForStatement */:
85769                         return visitForStatementInAsyncBody(node);
85770                     case 238 /* ForInStatement */:
85771                         return visitForInStatementInAsyncBody(node);
85772                     case 239 /* ForOfStatement */:
85773                         return visitForOfStatementInAsyncBody(node);
85774                     case 287 /* CatchClause */:
85775                         return visitCatchClauseInAsyncBody(node);
85776                     case 230 /* Block */:
85777                     case 244 /* SwitchStatement */:
85778                     case 258 /* CaseBlock */:
85779                     case 284 /* CaseClause */:
85780                     case 285 /* DefaultClause */:
85781                     case 247 /* TryStatement */:
85782                     case 235 /* DoStatement */:
85783                     case 236 /* WhileStatement */:
85784                     case 234 /* IfStatement */:
85785                     case 243 /* WithStatement */:
85786                     case 245 /* LabeledStatement */:
85787                         return ts.visitEachChild(node, asyncBodyVisitor, context);
85788                     default:
85789                         return ts.Debug.assertNever(node, "Unhandled node.");
85790                 }
85791             }
85792             return visitor(node);
85793         }
85794         function visitCatchClauseInAsyncBody(node) {
85795             var catchClauseNames = new ts.Set();
85796             recordDeclarationName(node.variableDeclaration, catchClauseNames); // TODO: GH#18217
85797             // names declared in a catch variable are block scoped
85798             var catchClauseUnshadowedNames;
85799             catchClauseNames.forEach(function (_, escapedName) {
85800                 if (enclosingFunctionParameterNames.has(escapedName)) {
85801                     if (!catchClauseUnshadowedNames) {
85802                         catchClauseUnshadowedNames = new ts.Set(enclosingFunctionParameterNames);
85803                     }
85804                     catchClauseUnshadowedNames.delete(escapedName);
85805                 }
85806             });
85807             if (catchClauseUnshadowedNames) {
85808                 var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
85809                 enclosingFunctionParameterNames = catchClauseUnshadowedNames;
85810                 var result = ts.visitEachChild(node, asyncBodyVisitor, context);
85811                 enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
85812                 return result;
85813             }
85814             else {
85815                 return ts.visitEachChild(node, asyncBodyVisitor, context);
85816             }
85817         }
85818         function visitVariableStatementInAsyncBody(node) {
85819             if (isVariableDeclarationListWithCollidingName(node.declarationList)) {
85820                 var expression = visitVariableDeclarationListWithCollidingNames(node.declarationList, /*hasReceiver*/ false);
85821                 return expression ? factory.createExpressionStatement(expression) : undefined;
85822             }
85823             return ts.visitEachChild(node, visitor, context);
85824         }
85825         function visitForInStatementInAsyncBody(node) {
85826             return factory.updateForInStatement(node, isVariableDeclarationListWithCollidingName(node.initializer)
85827                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
85828                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock));
85829         }
85830         function visitForOfStatementInAsyncBody(node) {
85831             return factory.updateForOfStatement(node, ts.visitNode(node.awaitModifier, visitor, ts.isToken), isVariableDeclarationListWithCollidingName(node.initializer)
85832                 ? visitVariableDeclarationListWithCollidingNames(node.initializer, /*hasReceiver*/ true)
85833                 : ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, asyncBodyVisitor, ts.isStatement, factory.liftToBlock));
85834         }
85835         function visitForStatementInAsyncBody(node) {
85836             var initializer = node.initializer; // TODO: GH#18217
85837             return factory.updateForStatement(node, isVariableDeclarationListWithCollidingName(initializer)
85838                 ? visitVariableDeclarationListWithCollidingNames(initializer, /*hasReceiver*/ false)
85839                 : 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, factory.liftToBlock));
85840         }
85841         /**
85842          * Visits an AwaitExpression node.
85843          *
85844          * This function will be called any time a ES2017 await expression is encountered.
85845          *
85846          * @param node The node to visit.
85847          */
85848         function visitAwaitExpression(node) {
85849             // do not downlevel a top-level await as it is module syntax...
85850             if (inTopLevelContext()) {
85851                 return ts.visitEachChild(node, visitor, context);
85852             }
85853             return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
85854             /*asteriskToken*/ undefined, ts.visitNode(node.expression, visitor, ts.isExpression)), node), node);
85855         }
85856         /**
85857          * Visits a MethodDeclaration node.
85858          *
85859          * This function will be called when one of the following conditions are met:
85860          * - The node is marked as async
85861          *
85862          * @param node The node to visit.
85863          */
85864         function visitMethodDeclaration(node) {
85865             return factory.updateMethodDeclaration(node, 
85866             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
85867             /*questionToken*/ undefined, 
85868             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
85869             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
85870                 ? transformAsyncFunctionBody(node)
85871                 : ts.visitFunctionBody(node.body, visitor, context));
85872         }
85873         /**
85874          * Visits a FunctionDeclaration node.
85875          *
85876          * This function will be called when one of the following conditions are met:
85877          * - The node is marked async
85878          *
85879          * @param node The node to visit.
85880          */
85881         function visitFunctionDeclaration(node) {
85882             return factory.updateFunctionDeclaration(node, 
85883             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
85884             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
85885             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
85886                 ? transformAsyncFunctionBody(node)
85887                 : ts.visitFunctionBody(node.body, visitor, context));
85888         }
85889         /**
85890          * Visits a FunctionExpression node.
85891          *
85892          * This function will be called when one of the following conditions are met:
85893          * - The node is marked async
85894          *
85895          * @param node The node to visit.
85896          */
85897         function visitFunctionExpression(node) {
85898             return factory.updateFunctionExpression(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, node.name, 
85899             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
85900             /*type*/ undefined, ts.getFunctionFlags(node) & 2 /* Async */
85901                 ? transformAsyncFunctionBody(node)
85902                 : ts.visitFunctionBody(node.body, visitor, context));
85903         }
85904         /**
85905          * Visits an ArrowFunction.
85906          *
85907          * This function will be called when one of the following conditions are met:
85908          * - The node is marked async
85909          *
85910          * @param node The node to visit.
85911          */
85912         function visitArrowFunction(node) {
85913             return factory.updateArrowFunction(node, ts.visitNodes(node.modifiers, visitor, ts.isModifier), 
85914             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
85915             /*type*/ undefined, node.equalsGreaterThanToken, ts.getFunctionFlags(node) & 2 /* Async */
85916                 ? transformAsyncFunctionBody(node)
85917                 : ts.visitFunctionBody(node.body, visitor, context));
85918         }
85919         function recordDeclarationName(_a, names) {
85920             var name = _a.name;
85921             if (ts.isIdentifier(name)) {
85922                 names.add(name.escapedText);
85923             }
85924             else {
85925                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
85926                     var element = _b[_i];
85927                     if (!ts.isOmittedExpression(element)) {
85928                         recordDeclarationName(element, names);
85929                     }
85930                 }
85931             }
85932         }
85933         function isVariableDeclarationListWithCollidingName(node) {
85934             return !!node
85935                 && ts.isVariableDeclarationList(node)
85936                 && !(node.flags & 3 /* BlockScoped */)
85937                 && node.declarations.some(collidesWithParameterName);
85938         }
85939         function visitVariableDeclarationListWithCollidingNames(node, hasReceiver) {
85940             hoistVariableDeclarationList(node);
85941             var variables = ts.getInitializedVariables(node);
85942             if (variables.length === 0) {
85943                 if (hasReceiver) {
85944                     return ts.visitNode(factory.converters.convertToAssignmentElementTarget(node.declarations[0].name), visitor, ts.isExpression);
85945                 }
85946                 return undefined;
85947             }
85948             return factory.inlineExpressions(ts.map(variables, transformInitializedVariable));
85949         }
85950         function hoistVariableDeclarationList(node) {
85951             ts.forEach(node.declarations, hoistVariable);
85952         }
85953         function hoistVariable(_a) {
85954             var name = _a.name;
85955             if (ts.isIdentifier(name)) {
85956                 hoistVariableDeclaration(name);
85957             }
85958             else {
85959                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
85960                     var element = _b[_i];
85961                     if (!ts.isOmittedExpression(element)) {
85962                         hoistVariable(element);
85963                     }
85964                 }
85965             }
85966         }
85967         function transformInitializedVariable(node) {
85968             var converted = ts.setSourceMapRange(factory.createAssignment(factory.converters.convertToAssignmentElementTarget(node.name), node.initializer), node);
85969             return ts.visitNode(converted, visitor, ts.isExpression);
85970         }
85971         function collidesWithParameterName(_a) {
85972             var name = _a.name;
85973             if (ts.isIdentifier(name)) {
85974                 return enclosingFunctionParameterNames.has(name.escapedText);
85975             }
85976             else {
85977                 for (var _i = 0, _b = name.elements; _i < _b.length; _i++) {
85978                     var element = _b[_i];
85979                     if (!ts.isOmittedExpression(element) && collidesWithParameterName(element)) {
85980                         return true;
85981                     }
85982                 }
85983             }
85984             return false;
85985         }
85986         function transformAsyncFunctionBody(node) {
85987             resumeLexicalEnvironment();
85988             var original = ts.getOriginalNode(node, ts.isFunctionLike);
85989             var nodeType = original.type;
85990             var promiseConstructor = languageVersion < 2 /* ES2015 */ ? getPromiseConstructor(nodeType) : undefined;
85991             var isArrowFunction = node.kind === 209 /* ArrowFunction */;
85992             var hasLexicalArguments = (resolver.getNodeCheckFlags(node) & 8192 /* CaptureArguments */) !== 0;
85993             // An async function is emit as an outer function that calls an inner
85994             // generator function. To preserve lexical bindings, we pass the current
85995             // `this` and `arguments` objects to `__awaiter`. The generator function
85996             // passed to `__awaiter` is executed inside of the callback to the
85997             // promise constructor.
85998             var savedEnclosingFunctionParameterNames = enclosingFunctionParameterNames;
85999             enclosingFunctionParameterNames = new ts.Set();
86000             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
86001                 var parameter = _a[_i];
86002                 recordDeclarationName(parameter, enclosingFunctionParameterNames);
86003             }
86004             var savedCapturedSuperProperties = capturedSuperProperties;
86005             var savedHasSuperElementAccess = hasSuperElementAccess;
86006             if (!isArrowFunction) {
86007                 capturedSuperProperties = new ts.Set();
86008                 hasSuperElementAccess = false;
86009             }
86010             var result;
86011             if (!isArrowFunction) {
86012                 var statements = [];
86013                 var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
86014                 statements.push(factory.createReturnStatement(emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body, statementOffset))));
86015                 ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86016                 // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
86017                 // This step isn't needed if we eventually transform this to ES5.
86018                 var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
86019                 if (emitSuperHelpers) {
86020                     enableSubstitutionForAsyncMethodsWithSuper();
86021                     if (capturedSuperProperties.size) {
86022                         var variableStatement = createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
86023                         substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
86024                         ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
86025                     }
86026                 }
86027                 var block = factory.createBlock(statements, /*multiLine*/ true);
86028                 ts.setTextRange(block, node.body);
86029                 if (emitSuperHelpers && hasSuperElementAccess) {
86030                     // Emit helpers for super element access expressions (`super[x]`).
86031                     if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
86032                         ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
86033                     }
86034                     else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
86035                         ts.addEmitHelper(block, ts.asyncSuperHelper);
86036                     }
86037                 }
86038                 result = block;
86039             }
86040             else {
86041                 var expression = emitHelpers().createAwaiterHelper(inHasLexicalThisContext(), hasLexicalArguments, promiseConstructor, transformAsyncFunctionBodyWorker(node.body));
86042                 var declarations = endLexicalEnvironment();
86043                 if (ts.some(declarations)) {
86044                     var block = factory.converters.convertToFunctionBlock(expression);
86045                     result = factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(ts.concatenate(declarations, block.statements)), block.statements));
86046                 }
86047                 else {
86048                     result = expression;
86049                 }
86050             }
86051             enclosingFunctionParameterNames = savedEnclosingFunctionParameterNames;
86052             if (!isArrowFunction) {
86053                 capturedSuperProperties = savedCapturedSuperProperties;
86054                 hasSuperElementAccess = savedHasSuperElementAccess;
86055             }
86056             return result;
86057         }
86058         function transformAsyncFunctionBodyWorker(body, start) {
86059             if (ts.isBlock(body)) {
86060                 return factory.updateBlock(body, ts.visitNodes(body.statements, asyncBodyVisitor, ts.isStatement, start));
86061             }
86062             else {
86063                 return factory.converters.convertToFunctionBlock(ts.visitNode(body, asyncBodyVisitor, ts.isConciseBody));
86064             }
86065         }
86066         function getPromiseConstructor(type) {
86067             var typeName = type && ts.getEntityNameFromTypeNode(type);
86068             if (typeName && ts.isEntityName(typeName)) {
86069                 var serializationKind = resolver.getTypeReferenceSerializationKind(typeName);
86070                 if (serializationKind === ts.TypeReferenceSerializationKind.TypeWithConstructSignatureAndValue
86071                     || serializationKind === ts.TypeReferenceSerializationKind.Unknown) {
86072                     return typeName;
86073                 }
86074             }
86075             return undefined;
86076         }
86077         function enableSubstitutionForAsyncMethodsWithSuper() {
86078             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
86079                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
86080                 // We need to enable substitutions for call, property access, and element access
86081                 // if we need to rewrite super calls.
86082                 context.enableSubstitution(203 /* CallExpression */);
86083                 context.enableSubstitution(201 /* PropertyAccessExpression */);
86084                 context.enableSubstitution(202 /* ElementAccessExpression */);
86085                 // We need to be notified when entering and exiting declarations that bind super.
86086                 context.enableEmitNotification(252 /* ClassDeclaration */);
86087                 context.enableEmitNotification(165 /* MethodDeclaration */);
86088                 context.enableEmitNotification(167 /* GetAccessor */);
86089                 context.enableEmitNotification(168 /* SetAccessor */);
86090                 context.enableEmitNotification(166 /* Constructor */);
86091                 // We need to be notified when entering the generated accessor arrow functions.
86092                 context.enableEmitNotification(232 /* VariableStatement */);
86093             }
86094         }
86095         /**
86096          * Hook for node emit.
86097          *
86098          * @param hint A hint as to the intended usage of the node.
86099          * @param node The node to emit.
86100          * @param emit A callback used to emit the node in the printer.
86101          */
86102         function onEmitNode(hint, node, emitCallback) {
86103             // If we need to support substitutions for `super` in an async method,
86104             // we should track it here.
86105             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
86106                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
86107                 if (superContainerFlags !== enclosingSuperContainerFlags) {
86108                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
86109                     enclosingSuperContainerFlags = superContainerFlags;
86110                     previousOnEmitNode(hint, node, emitCallback);
86111                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
86112                     return;
86113                 }
86114             }
86115             // Disable substitution in the generated super accessor itself.
86116             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
86117                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
86118                 enclosingSuperContainerFlags = 0;
86119                 previousOnEmitNode(hint, node, emitCallback);
86120                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
86121                 return;
86122             }
86123             previousOnEmitNode(hint, node, emitCallback);
86124         }
86125         /**
86126          * Hooks node substitutions.
86127          *
86128          * @param hint A hint as to the intended usage of the node.
86129          * @param node The node to substitute.
86130          */
86131         function onSubstituteNode(hint, node) {
86132             node = previousOnSubstituteNode(hint, node);
86133             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
86134                 return substituteExpression(node);
86135             }
86136             return node;
86137         }
86138         function substituteExpression(node) {
86139             switch (node.kind) {
86140                 case 201 /* PropertyAccessExpression */:
86141                     return substitutePropertyAccessExpression(node);
86142                 case 202 /* ElementAccessExpression */:
86143                     return substituteElementAccessExpression(node);
86144                 case 203 /* CallExpression */:
86145                     return substituteCallExpression(node);
86146             }
86147             return node;
86148         }
86149         function substitutePropertyAccessExpression(node) {
86150             if (node.expression.kind === 105 /* SuperKeyword */) {
86151                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
86152             }
86153             return node;
86154         }
86155         function substituteElementAccessExpression(node) {
86156             if (node.expression.kind === 105 /* SuperKeyword */) {
86157                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
86158             }
86159             return node;
86160         }
86161         function substituteCallExpression(node) {
86162             var expression = node.expression;
86163             if (ts.isSuperProperty(expression)) {
86164                 var argumentExpression = ts.isPropertyAccessExpression(expression)
86165                     ? substitutePropertyAccessExpression(expression)
86166                     : substituteElementAccessExpression(expression);
86167                 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"), 
86168                 /*typeArguments*/ undefined, __spreadArrays([
86169                     factory.createThis()
86170                 ], node.arguments));
86171             }
86172             return node;
86173         }
86174         function isSuperContainer(node) {
86175             var kind = node.kind;
86176             return kind === 252 /* ClassDeclaration */
86177                 || kind === 166 /* Constructor */
86178                 || kind === 165 /* MethodDeclaration */
86179                 || kind === 167 /* GetAccessor */
86180                 || kind === 168 /* SetAccessor */;
86181         }
86182         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
86183             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
86184                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), 
86185                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
86186             }
86187             else {
86188                 return ts.setTextRange(factory.createCallExpression(factory.createUniqueName("_superIndex", 16 /* Optimistic */ | 32 /* FileLevel */), 
86189                 /*typeArguments*/ undefined, [argumentExpression]), location);
86190             }
86191         }
86192     }
86193     ts.transformES2017 = transformES2017;
86194     /** Creates a variable named `_super` with accessor properties for the given property names. */
86195     function createSuperAccessVariableStatement(factory, resolver, node, names) {
86196         // Create a variable declaration with a getter/setter (if binding) definition for each name:
86197         //   const _super = Object.create(null, { x: { get: () => super.x, set: (v) => super.x = v }, ... });
86198         var hasBinding = (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) !== 0;
86199         var accessors = [];
86200         names.forEach(function (_, key) {
86201             var name = ts.unescapeLeadingUnderscores(key);
86202             var getterAndSetter = [];
86203             getterAndSetter.push(factory.createPropertyAssignment("get", factory.createArrowFunction(
86204             /* modifiers */ undefined, 
86205             /* typeParameters */ undefined, 
86206             /* parameters */ [], 
86207             /* type */ undefined, 
86208             /* equalsGreaterThanToken */ undefined, ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */))));
86209             if (hasBinding) {
86210                 getterAndSetter.push(factory.createPropertyAssignment("set", factory.createArrowFunction(
86211                 /* modifiers */ undefined, 
86212                 /* typeParameters */ undefined, 
86213                 /* parameters */ [
86214                     factory.createParameterDeclaration(
86215                     /* decorators */ undefined, 
86216                     /* modifiers */ undefined, 
86217                     /* dotDotDotToken */ undefined, "v", 
86218                     /* questionToken */ undefined, 
86219                     /* type */ undefined, 
86220                     /* initializer */ undefined)
86221                 ], 
86222                 /* type */ undefined, 
86223                 /* equalsGreaterThanToken */ undefined, factory.createAssignment(ts.setEmitFlags(factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createSuper(), 4 /* NoSubstitution */), name), 4 /* NoSubstitution */), factory.createIdentifier("v")))));
86224             }
86225             accessors.push(factory.createPropertyAssignment(name, factory.createObjectLiteralExpression(getterAndSetter)));
86226         });
86227         return factory.createVariableStatement(
86228         /* modifiers */ undefined, factory.createVariableDeclarationList([
86229             factory.createVariableDeclaration(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), 
86230             /*exclamationToken*/ undefined, 
86231             /* type */ undefined, factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "create"), 
86232             /* typeArguments */ undefined, [
86233                 factory.createNull(),
86234                 factory.createObjectLiteralExpression(accessors, /* multiline */ true)
86235             ]))
86236         ], 2 /* Const */));
86237     }
86238     ts.createSuperAccessVariableStatement = createSuperAccessVariableStatement;
86239 })(ts || (ts = {}));
86240 /*@internal*/
86241 var ts;
86242 (function (ts) {
86243     var ESNextSubstitutionFlags;
86244     (function (ESNextSubstitutionFlags) {
86245         /** Enables substitutions for async methods with `super` calls. */
86246         ESNextSubstitutionFlags[ESNextSubstitutionFlags["AsyncMethodsWithSuper"] = 1] = "AsyncMethodsWithSuper";
86247     })(ESNextSubstitutionFlags || (ESNextSubstitutionFlags = {}));
86248     // Facts we track as we traverse the tree
86249     var HierarchyFacts;
86250     (function (HierarchyFacts) {
86251         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
86252         //
86253         // Ancestor facts
86254         //
86255         HierarchyFacts[HierarchyFacts["HasLexicalThis"] = 1] = "HasLexicalThis";
86256         HierarchyFacts[HierarchyFacts["IterationContainer"] = 2] = "IterationContainer";
86257         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
86258         //
86259         // Ancestor masks
86260         //
86261         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 3] = "AncestorFactsMask";
86262         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 1] = "SourceFileIncludes";
86263         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 2] = "SourceFileExcludes";
86264         HierarchyFacts[HierarchyFacts["StrictModeSourceFileIncludes"] = 0] = "StrictModeSourceFileIncludes";
86265         HierarchyFacts[HierarchyFacts["ClassOrFunctionIncludes"] = 1] = "ClassOrFunctionIncludes";
86266         HierarchyFacts[HierarchyFacts["ClassOrFunctionExcludes"] = 2] = "ClassOrFunctionExcludes";
86267         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 0] = "ArrowFunctionIncludes";
86268         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 2] = "ArrowFunctionExcludes";
86269         HierarchyFacts[HierarchyFacts["IterationStatementIncludes"] = 2] = "IterationStatementIncludes";
86270         HierarchyFacts[HierarchyFacts["IterationStatementExcludes"] = 0] = "IterationStatementExcludes";
86271     })(HierarchyFacts || (HierarchyFacts = {}));
86272     function transformES2018(context) {
86273         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
86274         var resolver = context.getEmitResolver();
86275         var compilerOptions = context.getCompilerOptions();
86276         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
86277         var previousOnEmitNode = context.onEmitNode;
86278         context.onEmitNode = onEmitNode;
86279         var previousOnSubstituteNode = context.onSubstituteNode;
86280         context.onSubstituteNode = onSubstituteNode;
86281         var exportedVariableStatement = false;
86282         var enabledSubstitutions;
86283         var enclosingFunctionFlags;
86284         var enclosingSuperContainerFlags = 0;
86285         var hierarchyFacts = 0;
86286         var currentSourceFile;
86287         var taggedTemplateStringDeclarations;
86288         /** Keeps track of property names accessed on super (`super.x`) within async functions. */
86289         var capturedSuperProperties;
86290         /** Whether the async function contains an element access on super (`super[x]`). */
86291         var hasSuperElementAccess;
86292         /** A set of node IDs for generated super accessors. */
86293         var substitutedSuperAccessors = [];
86294         return ts.chainBundle(context, transformSourceFile);
86295         function affectsSubtree(excludeFacts, includeFacts) {
86296             return hierarchyFacts !== (hierarchyFacts & ~excludeFacts | includeFacts);
86297         }
86298         /**
86299          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
86300          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
86301          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
86302          */
86303         function enterSubtree(excludeFacts, includeFacts) {
86304             var ancestorFacts = hierarchyFacts;
86305             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 3 /* AncestorFactsMask */;
86306             return ancestorFacts;
86307         }
86308         /**
86309          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
86310          * subtree.
86311          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
86312          */
86313         function exitSubtree(ancestorFacts) {
86314             hierarchyFacts = ancestorFacts;
86315         }
86316         function recordTaggedTemplateString(temp) {
86317             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
86318         }
86319         function transformSourceFile(node) {
86320             if (node.isDeclarationFile) {
86321                 return node;
86322             }
86323             currentSourceFile = node;
86324             var visited = visitSourceFile(node);
86325             ts.addEmitHelpers(visited, context.readEmitHelpers());
86326             currentSourceFile = undefined;
86327             taggedTemplateStringDeclarations = undefined;
86328             return visited;
86329         }
86330         function visitor(node) {
86331             return visitorWorker(node, /*expressionResultIsUnused*/ false);
86332         }
86333         function visitorWithUnusedExpressionResult(node) {
86334             return visitorWorker(node, /*expressionResultIsUnused*/ true);
86335         }
86336         function visitorNoAsyncModifier(node) {
86337             if (node.kind === 129 /* AsyncKeyword */) {
86338                 return undefined;
86339             }
86340             return node;
86341         }
86342         function doWithHierarchyFacts(cb, value, excludeFacts, includeFacts) {
86343             if (affectsSubtree(excludeFacts, includeFacts)) {
86344                 var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
86345                 var result = cb(value);
86346                 exitSubtree(ancestorFacts);
86347                 return result;
86348             }
86349             return cb(value);
86350         }
86351         function visitDefault(node) {
86352             return ts.visitEachChild(node, visitor, context);
86353         }
86354         /**
86355          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
86356          * expression of an `ExpressionStatement`).
86357          */
86358         function visitorWorker(node, expressionResultIsUnused) {
86359             if ((node.transformFlags & 32 /* ContainsES2018 */) === 0) {
86360                 return node;
86361             }
86362             switch (node.kind) {
86363                 case 213 /* AwaitExpression */:
86364                     return visitAwaitExpression(node);
86365                 case 219 /* YieldExpression */:
86366                     return visitYieldExpression(node);
86367                 case 242 /* ReturnStatement */:
86368                     return visitReturnStatement(node);
86369                 case 245 /* LabeledStatement */:
86370                     return visitLabeledStatement(node);
86371                 case 200 /* ObjectLiteralExpression */:
86372                     return visitObjectLiteralExpression(node);
86373                 case 216 /* BinaryExpression */:
86374                     return visitBinaryExpression(node, expressionResultIsUnused);
86375                 case 337 /* CommaListExpression */:
86376                     return visitCommaListExpression(node, expressionResultIsUnused);
86377                 case 287 /* CatchClause */:
86378                     return visitCatchClause(node);
86379                 case 232 /* VariableStatement */:
86380                     return visitVariableStatement(node);
86381                 case 249 /* VariableDeclaration */:
86382                     return visitVariableDeclaration(node);
86383                 case 235 /* DoStatement */:
86384                 case 236 /* WhileStatement */:
86385                 case 238 /* ForInStatement */:
86386                     return doWithHierarchyFacts(visitDefault, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
86387                 case 239 /* ForOfStatement */:
86388                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
86389                 case 237 /* ForStatement */:
86390                     return doWithHierarchyFacts(visitForStatement, node, 0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
86391                 case 212 /* VoidExpression */:
86392                     return visitVoidExpression(node);
86393                 case 166 /* Constructor */:
86394                     return doWithHierarchyFacts(visitConstructorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86395                 case 165 /* MethodDeclaration */:
86396                     return doWithHierarchyFacts(visitMethodDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86397                 case 167 /* GetAccessor */:
86398                     return doWithHierarchyFacts(visitGetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86399                 case 168 /* SetAccessor */:
86400                     return doWithHierarchyFacts(visitSetAccessorDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86401                 case 251 /* FunctionDeclaration */:
86402                     return doWithHierarchyFacts(visitFunctionDeclaration, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86403                 case 208 /* FunctionExpression */:
86404                     return doWithHierarchyFacts(visitFunctionExpression, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86405                 case 209 /* ArrowFunction */:
86406                     return doWithHierarchyFacts(visitArrowFunction, node, 2 /* ArrowFunctionExcludes */, 0 /* ArrowFunctionIncludes */);
86407                 case 160 /* Parameter */:
86408                     return visitParameter(node);
86409                 case 233 /* ExpressionStatement */:
86410                     return visitExpressionStatement(node);
86411                 case 207 /* ParenthesizedExpression */:
86412                     return visitParenthesizedExpression(node, expressionResultIsUnused);
86413                 case 205 /* TaggedTemplateExpression */:
86414                     return visitTaggedTemplateExpression(node);
86415                 case 201 /* PropertyAccessExpression */:
86416                     if (capturedSuperProperties && ts.isPropertyAccessExpression(node) && node.expression.kind === 105 /* SuperKeyword */) {
86417                         capturedSuperProperties.add(node.name.escapedText);
86418                     }
86419                     return ts.visitEachChild(node, visitor, context);
86420                 case 202 /* ElementAccessExpression */:
86421                     if (capturedSuperProperties && node.expression.kind === 105 /* SuperKeyword */) {
86422                         hasSuperElementAccess = true;
86423                     }
86424                     return ts.visitEachChild(node, visitor, context);
86425                 case 252 /* ClassDeclaration */:
86426                 case 221 /* ClassExpression */:
86427                     return doWithHierarchyFacts(visitDefault, node, 2 /* ClassOrFunctionExcludes */, 1 /* ClassOrFunctionIncludes */);
86428                 default:
86429                     return ts.visitEachChild(node, visitor, context);
86430             }
86431         }
86432         function visitAwaitExpression(node) {
86433             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
86434                 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(ts.visitNode(node.expression, visitor, ts.isExpression))), 
86435                 /*location*/ node), node);
86436             }
86437             return ts.visitEachChild(node, visitor, context);
86438         }
86439         function visitYieldExpression(node) {
86440             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
86441                 if (node.asteriskToken) {
86442                     var expression = ts.visitNode(ts.Debug.assertDefined(node.expression), visitor, ts.isExpression);
86443                     return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
86444                     /*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(factory.updateYieldExpression(node, node.asteriskToken, ts.setTextRange(emitHelpers().createAsyncDelegatorHelper(ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), expression)), expression)))), node), node);
86445                 }
86446                 return ts.setOriginalNode(ts.setTextRange(factory.createYieldExpression(
86447                 /*asteriskToken*/ undefined, createDownlevelAwait(node.expression
86448                     ? ts.visitNode(node.expression, visitor, ts.isExpression)
86449                     : factory.createVoidZero())), node), node);
86450             }
86451             return ts.visitEachChild(node, visitor, context);
86452         }
86453         function visitReturnStatement(node) {
86454             if (enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */) {
86455                 return factory.updateReturnStatement(node, createDownlevelAwait(node.expression ? ts.visitNode(node.expression, visitor, ts.isExpression) : factory.createVoidZero()));
86456             }
86457             return ts.visitEachChild(node, visitor, context);
86458         }
86459         function visitLabeledStatement(node) {
86460             if (enclosingFunctionFlags & 2 /* Async */) {
86461                 var statement = ts.unwrapInnermostStatementOfLabel(node);
86462                 if (statement.kind === 239 /* ForOfStatement */ && statement.awaitModifier) {
86463                     return visitForOfStatement(statement, node);
86464                 }
86465                 return factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node);
86466             }
86467             return ts.visitEachChild(node, visitor, context);
86468         }
86469         function chunkObjectLiteralElements(elements) {
86470             var chunkObject;
86471             var objects = [];
86472             for (var _i = 0, elements_4 = elements; _i < elements_4.length; _i++) {
86473                 var e = elements_4[_i];
86474                 if (e.kind === 290 /* SpreadAssignment */) {
86475                     if (chunkObject) {
86476                         objects.push(factory.createObjectLiteralExpression(chunkObject));
86477                         chunkObject = undefined;
86478                     }
86479                     var target = e.expression;
86480                     objects.push(ts.visitNode(target, visitor, ts.isExpression));
86481                 }
86482                 else {
86483                     chunkObject = ts.append(chunkObject, e.kind === 288 /* PropertyAssignment */
86484                         ? factory.createPropertyAssignment(e.name, ts.visitNode(e.initializer, visitor, ts.isExpression))
86485                         : ts.visitNode(e, visitor, ts.isObjectLiteralElementLike));
86486                 }
86487             }
86488             if (chunkObject) {
86489                 objects.push(factory.createObjectLiteralExpression(chunkObject));
86490             }
86491             return objects;
86492         }
86493         function visitObjectLiteralExpression(node) {
86494             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86495                 // spread elements emit like so:
86496                 // non-spread elements are chunked together into object literals, and then all are passed to __assign:
86497                 //     { a, ...o, b } => __assign(__assign({a}, o), {b});
86498                 // If the first element is a spread element, then the first argument to __assign is {}:
86499                 //     { ...o, a, b, ...o2 } => __assign(__assign(__assign({}, o), {a, b}), o2)
86500                 //
86501                 // We cannot call __assign with more than two elements, since any element could cause side effects. For
86502                 // example:
86503                 //      var k = { a: 1, b: 2 };
86504                 //      var o = { a: 3, ...k, b: k.a++ };
86505                 //      // expected: { a: 1, b: 1 }
86506                 // If we translate the above to `__assign({ a: 3 }, k, { b: k.a++ })`, the `k.a++` will evaluate before
86507                 // `k` is spread and we end up with `{ a: 2, b: 1 }`.
86508                 //
86509                 // This also occurs for spread elements, not just property assignments:
86510                 //      var k = { a: 1, get b() { l = { z: 9 }; return 2; } };
86511                 //      var l = { c: 3 };
86512                 //      var o = { ...k, ...l };
86513                 //      // expected: { a: 1, b: 2, z: 9 }
86514                 // If we translate the above to `__assign({}, k, l)`, the `l` will evaluate before `k` is spread and we
86515                 // end up with `{ a: 1, b: 2, c: 3 }`
86516                 var objects = chunkObjectLiteralElements(node.properties);
86517                 if (objects.length && objects[0].kind !== 200 /* ObjectLiteralExpression */) {
86518                     objects.unshift(factory.createObjectLiteralExpression());
86519                 }
86520                 var expression = objects[0];
86521                 if (objects.length > 1) {
86522                     for (var i = 1; i < objects.length; i++) {
86523                         expression = emitHelpers().createAssignHelper([expression, objects[i]]);
86524                     }
86525                     return expression;
86526                 }
86527                 else {
86528                     return emitHelpers().createAssignHelper(objects);
86529                 }
86530             }
86531             return ts.visitEachChild(node, visitor, context);
86532         }
86533         function visitExpressionStatement(node) {
86534             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
86535         }
86536         /**
86537          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
86538          * expression of an `ExpressionStatement`).
86539          */
86540         function visitParenthesizedExpression(node, expressionResultIsUnused) {
86541             return ts.visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context);
86542         }
86543         function visitSourceFile(node) {
86544             var ancestorFacts = enterSubtree(2 /* SourceFileExcludes */, ts.isEffectiveStrictModeSourceFile(node, compilerOptions) ?
86545                 0 /* StrictModeSourceFileIncludes */ :
86546                 1 /* SourceFileIncludes */);
86547             exportedVariableStatement = false;
86548             var visited = ts.visitEachChild(node, visitor, context);
86549             var statement = ts.concatenate(visited.statements, taggedTemplateStringDeclarations && [
86550                 factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations))
86551             ]);
86552             var result = factory.updateSourceFile(visited, ts.setTextRange(factory.createNodeArray(statement), node.statements));
86553             exitSubtree(ancestorFacts);
86554             return result;
86555         }
86556         function visitTaggedTemplateExpression(node) {
86557             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.LiftRestriction);
86558         }
86559         /**
86560          * Visits a BinaryExpression that contains a destructuring assignment.
86561          *
86562          * @param node A BinaryExpression node.
86563          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
86564          * expression of an `ExpressionStatement`).
86565          */
86566         function visitBinaryExpression(node, expressionResultIsUnused) {
86567             if (ts.isDestructuringAssignment(node) && node.left.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86568                 return ts.flattenDestructuringAssignment(node, visitor, context, 1 /* ObjectRest */, !expressionResultIsUnused);
86569             }
86570             if (node.operatorToken.kind === 27 /* CommaToken */) {
86571                 return factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorWithUnusedExpressionResult, ts.isExpression), node.operatorToken, ts.visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, ts.isExpression));
86572             }
86573             return ts.visitEachChild(node, visitor, context);
86574         }
86575         /**
86576          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
86577          * expression of an `ExpressionStatement`).
86578          */
86579         function visitCommaListExpression(node, expressionResultIsUnused) {
86580             if (expressionResultIsUnused) {
86581                 return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
86582             }
86583             var result;
86584             for (var i = 0; i < node.elements.length; i++) {
86585                 var element = node.elements[i];
86586                 var visited = ts.visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, ts.isExpression);
86587                 if (result || visited !== element) {
86588                     result || (result = node.elements.slice(0, i));
86589                     result.push(visited);
86590                 }
86591             }
86592             var elements = result ? ts.setTextRange(factory.createNodeArray(result), node.elements) : node.elements;
86593             return factory.updateCommaListExpression(node, elements);
86594         }
86595         function visitCatchClause(node) {
86596             if (node.variableDeclaration &&
86597                 ts.isBindingPattern(node.variableDeclaration.name) &&
86598                 node.variableDeclaration.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86599                 var name = factory.getGeneratedNameForNode(node.variableDeclaration.name);
86600                 var updatedDecl = factory.updateVariableDeclaration(node.variableDeclaration, node.variableDeclaration.name, /*exclamationToken*/ undefined, /*type*/ undefined, name);
86601                 var visitedBindings = ts.flattenDestructuringBinding(updatedDecl, visitor, context, 1 /* ObjectRest */);
86602                 var block = ts.visitNode(node.block, visitor, ts.isBlock);
86603                 if (ts.some(visitedBindings)) {
86604                     block = factory.updateBlock(block, __spreadArrays([
86605                         factory.createVariableStatement(/*modifiers*/ undefined, visitedBindings)
86606                     ], block.statements));
86607                 }
86608                 return factory.updateCatchClause(node, factory.updateVariableDeclaration(node.variableDeclaration, name, /*exclamationToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined), block);
86609             }
86610             return ts.visitEachChild(node, visitor, context);
86611         }
86612         function visitVariableStatement(node) {
86613             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
86614                 var savedExportedVariableStatement = exportedVariableStatement;
86615                 exportedVariableStatement = true;
86616                 var visited = ts.visitEachChild(node, visitor, context);
86617                 exportedVariableStatement = savedExportedVariableStatement;
86618                 return visited;
86619             }
86620             return ts.visitEachChild(node, visitor, context);
86621         }
86622         /**
86623          * Visits a VariableDeclaration node with a binding pattern.
86624          *
86625          * @param node A VariableDeclaration node.
86626          */
86627         function visitVariableDeclaration(node) {
86628             if (exportedVariableStatement) {
86629                 var savedExportedVariableStatement = exportedVariableStatement;
86630                 exportedVariableStatement = false;
86631                 var visited = visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ true);
86632                 exportedVariableStatement = savedExportedVariableStatement;
86633                 return visited;
86634             }
86635             return visitVariableDeclarationWorker(node, /*exportedVariableStatement*/ false);
86636         }
86637         function visitVariableDeclarationWorker(node, exportedVariableStatement) {
86638             // If we are here it is because the name contains a binding pattern with a rest somewhere in it.
86639             if (ts.isBindingPattern(node.name) && node.name.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86640                 return ts.flattenDestructuringBinding(node, visitor, context, 1 /* ObjectRest */, 
86641                 /*rval*/ undefined, exportedVariableStatement);
86642             }
86643             return ts.visitEachChild(node, visitor, context);
86644         }
86645         function visitForStatement(node) {
86646             return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement));
86647         }
86648         function visitVoidExpression(node) {
86649             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
86650         }
86651         /**
86652          * Visits a ForOfStatement and converts it into a ES2015-compatible ForOfStatement.
86653          *
86654          * @param node A ForOfStatement.
86655          */
86656         function visitForOfStatement(node, outermostLabeledStatement) {
86657             var ancestorFacts = enterSubtree(0 /* IterationStatementExcludes */, 2 /* IterationStatementIncludes */);
86658             if (node.initializer.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86659                 node = transformForOfStatementWithObjectRest(node);
86660             }
86661             var result = node.awaitModifier ?
86662                 transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) :
86663                 factory.restoreEnclosingLabel(ts.visitEachChild(node, visitor, context), outermostLabeledStatement);
86664             exitSubtree(ancestorFacts);
86665             return result;
86666         }
86667         function transformForOfStatementWithObjectRest(node) {
86668             var initializerWithoutParens = ts.skipParentheses(node.initializer);
86669             if (ts.isVariableDeclarationList(initializerWithoutParens) || ts.isAssignmentPattern(initializerWithoutParens)) {
86670                 var bodyLocation = void 0;
86671                 var statementsLocation = void 0;
86672                 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
86673                 var statements = [ts.createForOfBindingStatement(factory, initializerWithoutParens, temp)];
86674                 if (ts.isBlock(node.statement)) {
86675                     ts.addRange(statements, node.statement.statements);
86676                     bodyLocation = node.statement;
86677                     statementsLocation = node.statement.statements;
86678                 }
86679                 else if (node.statement) {
86680                     ts.append(statements, node.statement);
86681                     bodyLocation = node.statement;
86682                     statementsLocation = node.statement;
86683                 }
86684                 return factory.updateForOfStatement(node, node.awaitModifier, ts.setTextRange(factory.createVariableDeclarationList([
86685                     ts.setTextRange(factory.createVariableDeclaration(temp), node.initializer)
86686                 ], 1 /* Let */), node.initializer), node.expression, ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), 
86687                 /*multiLine*/ true), bodyLocation));
86688             }
86689             return node;
86690         }
86691         function convertForOfStatementHead(node, boundValue) {
86692             var binding = ts.createForOfBindingStatement(factory, node.initializer, boundValue);
86693             var bodyLocation;
86694             var statementsLocation;
86695             var statements = [ts.visitNode(binding, visitor, ts.isStatement)];
86696             var statement = ts.visitNode(node.statement, visitor, ts.isStatement);
86697             if (ts.isBlock(statement)) {
86698                 ts.addRange(statements, statement.statements);
86699                 bodyLocation = statement;
86700                 statementsLocation = statement.statements;
86701             }
86702             else {
86703                 statements.push(statement);
86704             }
86705             return ts.setEmitFlags(ts.setTextRange(factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), 
86706             /*multiLine*/ true), bodyLocation), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
86707         }
86708         function createDownlevelAwait(expression) {
86709             return enclosingFunctionFlags & 1 /* Generator */
86710                 ? factory.createYieldExpression(/*asteriskToken*/ undefined, emitHelpers().createAwaitHelper(expression))
86711                 : factory.createAwaitExpression(expression);
86712         }
86713         function transformForAwaitOfStatement(node, outermostLabeledStatement, ancestorFacts) {
86714             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
86715             var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
86716             var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
86717             var errorRecord = factory.createUniqueName("e");
86718             var catchVariable = factory.getGeneratedNameForNode(errorRecord);
86719             var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
86720             var callValues = ts.setTextRange(emitHelpers().createAsyncValuesHelper(expression), node.expression);
86721             var callNext = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
86722             var getDone = factory.createPropertyAccessExpression(result, "done");
86723             var getValue = factory.createPropertyAccessExpression(result, "value");
86724             var callReturn = factory.createFunctionCallCall(returnMethod, iterator, []);
86725             hoistVariableDeclaration(errorRecord);
86726             hoistVariableDeclaration(returnMethod);
86727             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
86728             var initializer = ancestorFacts & 2 /* IterationContainer */ ?
86729                 factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), callValues]) :
86730                 callValues;
86731             var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
86732             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
86733                 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
86734                 factory.createVariableDeclaration(result)
86735             ]), node.expression), 2097152 /* NoHoisting */), 
86736             /*condition*/ factory.createComma(factory.createAssignment(result, createDownlevelAwait(callNext)), factory.createLogicalNot(getDone)), 
86737             /*incrementor*/ undefined, 
86738             /*statement*/ convertForOfStatementHead(node, getValue)), 
86739             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
86740             return factory.createTryStatement(factory.createBlock([
86741                 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement)
86742             ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
86743                 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
86744                     factory.createPropertyAssignment("error", catchVariable)
86745                 ])))
86746             ]), 1 /* SingleLine */)), factory.createBlock([
86747                 factory.createTryStatement(
86748                 /*tryBlock*/ factory.createBlock([
86749                     ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(getDone)), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(createDownlevelAwait(callReturn))), 1 /* SingleLine */)
86750                 ]), 
86751                 /*catchClause*/ undefined, 
86752                 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
86753                     ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
86754                 ]), 1 /* SingleLine */))
86755             ]));
86756         }
86757         function visitParameter(node) {
86758             if (node.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86759                 // Binding patterns are converted into a generated name and are
86760                 // evaluated inside the function body.
86761                 return factory.updateParameterDeclaration(node, 
86762                 /*decorators*/ undefined, 
86763                 /*modifiers*/ undefined, node.dotDotDotToken, factory.getGeneratedNameForNode(node), 
86764                 /*questionToken*/ undefined, 
86765                 /*type*/ undefined, ts.visitNode(node.initializer, visitor, ts.isExpression));
86766             }
86767             return ts.visitEachChild(node, visitor, context);
86768         }
86769         function visitConstructorDeclaration(node) {
86770             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86771             enclosingFunctionFlags = 0 /* Normal */;
86772             var updated = factory.updateConstructorDeclaration(node, 
86773             /*decorators*/ undefined, node.modifiers, ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
86774             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86775             return updated;
86776         }
86777         function visitGetAccessorDeclaration(node) {
86778             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86779             enclosingFunctionFlags = 0 /* Normal */;
86780             var updated = factory.updateGetAccessorDeclaration(node, 
86781             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), 
86782             /*type*/ undefined, transformFunctionBody(node));
86783             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86784             return updated;
86785         }
86786         function visitSetAccessorDeclaration(node) {
86787             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86788             enclosingFunctionFlags = 0 /* Normal */;
86789             var updated = factory.updateSetAccessorDeclaration(node, 
86790             /*decorators*/ undefined, node.modifiers, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitParameterList(node.parameters, visitor, context), transformFunctionBody(node));
86791             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86792             return updated;
86793         }
86794         function visitMethodDeclaration(node) {
86795             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86796             enclosingFunctionFlags = ts.getFunctionFlags(node);
86797             var updated = factory.updateMethodDeclaration(node, 
86798             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
86799                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
86800                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
86801                 ? undefined
86802                 : node.asteriskToken, ts.visitNode(node.name, visitor, ts.isPropertyName), ts.visitNode(/*questionToken*/ undefined, visitor, ts.isToken), 
86803             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86804             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
86805                 ? transformAsyncGeneratorFunctionBody(node)
86806                 : transformFunctionBody(node));
86807             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86808             return updated;
86809         }
86810         function visitFunctionDeclaration(node) {
86811             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86812             enclosingFunctionFlags = ts.getFunctionFlags(node);
86813             var updated = factory.updateFunctionDeclaration(node, 
86814             /*decorators*/ undefined, enclosingFunctionFlags & 1 /* Generator */
86815                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
86816                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
86817                 ? undefined
86818                 : node.asteriskToken, node.name, 
86819             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86820             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
86821                 ? transformAsyncGeneratorFunctionBody(node)
86822                 : transformFunctionBody(node));
86823             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86824             return updated;
86825         }
86826         function visitArrowFunction(node) {
86827             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86828             enclosingFunctionFlags = ts.getFunctionFlags(node);
86829             var updated = factory.updateArrowFunction(node, node.modifiers, 
86830             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86831             /*type*/ undefined, node.equalsGreaterThanToken, transformFunctionBody(node));
86832             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86833             return updated;
86834         }
86835         function visitFunctionExpression(node) {
86836             var savedEnclosingFunctionFlags = enclosingFunctionFlags;
86837             enclosingFunctionFlags = ts.getFunctionFlags(node);
86838             var updated = factory.updateFunctionExpression(node, enclosingFunctionFlags & 1 /* Generator */
86839                 ? ts.visitNodes(node.modifiers, visitorNoAsyncModifier, ts.isModifier)
86840                 : node.modifiers, enclosingFunctionFlags & 2 /* Async */
86841                 ? undefined
86842                 : node.asteriskToken, node.name, 
86843             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
86844             /*type*/ undefined, enclosingFunctionFlags & 2 /* Async */ && enclosingFunctionFlags & 1 /* Generator */
86845                 ? transformAsyncGeneratorFunctionBody(node)
86846                 : transformFunctionBody(node));
86847             enclosingFunctionFlags = savedEnclosingFunctionFlags;
86848             return updated;
86849         }
86850         function transformAsyncGeneratorFunctionBody(node) {
86851             resumeLexicalEnvironment();
86852             var statements = [];
86853             var statementOffset = factory.copyPrologue(node.body.statements, statements, /*ensureUseStrict*/ false, visitor);
86854             appendObjectRestAssignmentsIfNeeded(statements, node);
86855             var savedCapturedSuperProperties = capturedSuperProperties;
86856             var savedHasSuperElementAccess = hasSuperElementAccess;
86857             capturedSuperProperties = new ts.Set();
86858             hasSuperElementAccess = false;
86859             var returnStatement = factory.createReturnStatement(emitHelpers().createAsyncGeneratorHelper(factory.createFunctionExpression(
86860             /*modifiers*/ undefined, factory.createToken(41 /* AsteriskToken */), node.name && factory.getGeneratedNameForNode(node.name), 
86861             /*typeParameters*/ undefined, 
86862             /*parameters*/ [], 
86863             /*type*/ undefined, factory.updateBlock(node.body, ts.visitLexicalEnvironment(node.body.statements, visitor, context, statementOffset))), !!(hierarchyFacts & 1 /* HasLexicalThis */)));
86864             // Minor optimization, emit `_super` helper to capture `super` access in an arrow.
86865             // This step isn't needed if we eventually transform this to ES5.
86866             var emitSuperHelpers = languageVersion >= 2 /* ES2015 */ && resolver.getNodeCheckFlags(node) & (4096 /* AsyncMethodWithSuperBinding */ | 2048 /* AsyncMethodWithSuper */);
86867             if (emitSuperHelpers) {
86868                 enableSubstitutionForAsyncMethodsWithSuper();
86869                 var variableStatement = ts.createSuperAccessVariableStatement(factory, resolver, node, capturedSuperProperties);
86870                 substitutedSuperAccessors[ts.getNodeId(variableStatement)] = true;
86871                 ts.insertStatementsAfterStandardPrologue(statements, [variableStatement]);
86872             }
86873             statements.push(returnStatement);
86874             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
86875             var block = factory.updateBlock(node.body, statements);
86876             if (emitSuperHelpers && hasSuperElementAccess) {
86877                 if (resolver.getNodeCheckFlags(node) & 4096 /* AsyncMethodWithSuperBinding */) {
86878                     ts.addEmitHelper(block, ts.advancedAsyncSuperHelper);
86879                 }
86880                 else if (resolver.getNodeCheckFlags(node) & 2048 /* AsyncMethodWithSuper */) {
86881                     ts.addEmitHelper(block, ts.asyncSuperHelper);
86882                 }
86883             }
86884             capturedSuperProperties = savedCapturedSuperProperties;
86885             hasSuperElementAccess = savedHasSuperElementAccess;
86886             return block;
86887         }
86888         function transformFunctionBody(node) {
86889             var _a;
86890             resumeLexicalEnvironment();
86891             var statementOffset = 0;
86892             var statements = [];
86893             var body = (_a = ts.visitNode(node.body, visitor, ts.isConciseBody)) !== null && _a !== void 0 ? _a : factory.createBlock([]);
86894             if (ts.isBlock(body)) {
86895                 statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
86896             }
86897             ts.addRange(statements, appendObjectRestAssignmentsIfNeeded(/*statements*/ undefined, node));
86898             var leadingStatements = endLexicalEnvironment();
86899             if (statementOffset > 0 || ts.some(statements) || ts.some(leadingStatements)) {
86900                 var block = factory.converters.convertToFunctionBlock(body, /*multiLine*/ true);
86901                 ts.insertStatementsAfterStandardPrologue(statements, leadingStatements);
86902                 ts.addRange(statements, block.statements.slice(statementOffset));
86903                 return factory.updateBlock(block, ts.setTextRange(factory.createNodeArray(statements), block.statements));
86904             }
86905             return body;
86906         }
86907         function appendObjectRestAssignmentsIfNeeded(statements, node) {
86908             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
86909                 var parameter = _a[_i];
86910                 if (parameter.transformFlags & 16384 /* ContainsObjectRestOrSpread */) {
86911                     var temp = factory.getGeneratedNameForNode(parameter);
86912                     var declarations = ts.flattenDestructuringBinding(parameter, visitor, context, 1 /* ObjectRest */, temp, 
86913                     /*doNotRecordTempVariablesInLine*/ false, 
86914                     /*skipInitializer*/ true);
86915                     if (ts.some(declarations)) {
86916                         var statement = factory.createVariableStatement(
86917                         /*modifiers*/ undefined, factory.createVariableDeclarationList(declarations));
86918                         ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
86919                         statements = ts.append(statements, statement);
86920                     }
86921                 }
86922             }
86923             return statements;
86924         }
86925         function enableSubstitutionForAsyncMethodsWithSuper() {
86926             if ((enabledSubstitutions & 1 /* AsyncMethodsWithSuper */) === 0) {
86927                 enabledSubstitutions |= 1 /* AsyncMethodsWithSuper */;
86928                 // We need to enable substitutions for call, property access, and element access
86929                 // if we need to rewrite super calls.
86930                 context.enableSubstitution(203 /* CallExpression */);
86931                 context.enableSubstitution(201 /* PropertyAccessExpression */);
86932                 context.enableSubstitution(202 /* ElementAccessExpression */);
86933                 // We need to be notified when entering and exiting declarations that bind super.
86934                 context.enableEmitNotification(252 /* ClassDeclaration */);
86935                 context.enableEmitNotification(165 /* MethodDeclaration */);
86936                 context.enableEmitNotification(167 /* GetAccessor */);
86937                 context.enableEmitNotification(168 /* SetAccessor */);
86938                 context.enableEmitNotification(166 /* Constructor */);
86939                 // We need to be notified when entering the generated accessor arrow functions.
86940                 context.enableEmitNotification(232 /* VariableStatement */);
86941             }
86942         }
86943         /**
86944          * Called by the printer just before a node is printed.
86945          *
86946          * @param hint A hint as to the intended usage of the node.
86947          * @param node The node to be printed.
86948          * @param emitCallback The callback used to emit the node.
86949          */
86950         function onEmitNode(hint, node, emitCallback) {
86951             // If we need to support substitutions for `super` in an async method,
86952             // we should track it here.
86953             if (enabledSubstitutions & 1 /* AsyncMethodsWithSuper */ && isSuperContainer(node)) {
86954                 var superContainerFlags = resolver.getNodeCheckFlags(node) & (2048 /* AsyncMethodWithSuper */ | 4096 /* AsyncMethodWithSuperBinding */);
86955                 if (superContainerFlags !== enclosingSuperContainerFlags) {
86956                     var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
86957                     enclosingSuperContainerFlags = superContainerFlags;
86958                     previousOnEmitNode(hint, node, emitCallback);
86959                     enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
86960                     return;
86961                 }
86962             }
86963             // Disable substitution in the generated super accessor itself.
86964             else if (enabledSubstitutions && substitutedSuperAccessors[ts.getNodeId(node)]) {
86965                 var savedEnclosingSuperContainerFlags = enclosingSuperContainerFlags;
86966                 enclosingSuperContainerFlags = 0;
86967                 previousOnEmitNode(hint, node, emitCallback);
86968                 enclosingSuperContainerFlags = savedEnclosingSuperContainerFlags;
86969                 return;
86970             }
86971             previousOnEmitNode(hint, node, emitCallback);
86972         }
86973         /**
86974          * Hooks node substitutions.
86975          *
86976          * @param hint The context for the emitter.
86977          * @param node The node to substitute.
86978          */
86979         function onSubstituteNode(hint, node) {
86980             node = previousOnSubstituteNode(hint, node);
86981             if (hint === 1 /* Expression */ && enclosingSuperContainerFlags) {
86982                 return substituteExpression(node);
86983             }
86984             return node;
86985         }
86986         function substituteExpression(node) {
86987             switch (node.kind) {
86988                 case 201 /* PropertyAccessExpression */:
86989                     return substitutePropertyAccessExpression(node);
86990                 case 202 /* ElementAccessExpression */:
86991                     return substituteElementAccessExpression(node);
86992                 case 203 /* CallExpression */:
86993                     return substituteCallExpression(node);
86994             }
86995             return node;
86996         }
86997         function substitutePropertyAccessExpression(node) {
86998             if (node.expression.kind === 105 /* SuperKeyword */) {
86999                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), node.name), node);
87000             }
87001             return node;
87002         }
87003         function substituteElementAccessExpression(node) {
87004             if (node.expression.kind === 105 /* SuperKeyword */) {
87005                 return createSuperElementAccessInAsyncMethod(node.argumentExpression, node);
87006             }
87007             return node;
87008         }
87009         function substituteCallExpression(node) {
87010             var expression = node.expression;
87011             if (ts.isSuperProperty(expression)) {
87012                 var argumentExpression = ts.isPropertyAccessExpression(expression)
87013                     ? substitutePropertyAccessExpression(expression)
87014                     : substituteElementAccessExpression(expression);
87015                 return factory.createCallExpression(factory.createPropertyAccessExpression(argumentExpression, "call"), 
87016                 /*typeArguments*/ undefined, __spreadArrays([
87017                     factory.createThis()
87018                 ], node.arguments));
87019             }
87020             return node;
87021         }
87022         function isSuperContainer(node) {
87023             var kind = node.kind;
87024             return kind === 252 /* ClassDeclaration */
87025                 || kind === 166 /* Constructor */
87026                 || kind === 165 /* MethodDeclaration */
87027                 || kind === 167 /* GetAccessor */
87028                 || kind === 168 /* SetAccessor */;
87029         }
87030         function createSuperElementAccessInAsyncMethod(argumentExpression, location) {
87031             if (enclosingSuperContainerFlags & 4096 /* AsyncMethodWithSuperBinding */) {
87032                 return ts.setTextRange(factory.createPropertyAccessExpression(factory.createCallExpression(factory.createIdentifier("_superIndex"), 
87033                 /*typeArguments*/ undefined, [argumentExpression]), "value"), location);
87034             }
87035             else {
87036                 return ts.setTextRange(factory.createCallExpression(factory.createIdentifier("_superIndex"), 
87037                 /*typeArguments*/ undefined, [argumentExpression]), location);
87038             }
87039         }
87040     }
87041     ts.transformES2018 = transformES2018;
87042 })(ts || (ts = {}));
87043 /*@internal*/
87044 var ts;
87045 (function (ts) {
87046     function transformES2019(context) {
87047         var factory = context.factory;
87048         return ts.chainBundle(context, transformSourceFile);
87049         function transformSourceFile(node) {
87050             if (node.isDeclarationFile) {
87051                 return node;
87052             }
87053             return ts.visitEachChild(node, visitor, context);
87054         }
87055         function visitor(node) {
87056             if ((node.transformFlags & 16 /* ContainsES2019 */) === 0) {
87057                 return node;
87058             }
87059             switch (node.kind) {
87060                 case 287 /* CatchClause */:
87061                     return visitCatchClause(node);
87062                 default:
87063                     return ts.visitEachChild(node, visitor, context);
87064             }
87065         }
87066         function visitCatchClause(node) {
87067             if (!node.variableDeclaration) {
87068                 return factory.updateCatchClause(node, factory.createVariableDeclaration(factory.createTempVariable(/*recordTempVariable*/ undefined)), ts.visitNode(node.block, visitor, ts.isBlock));
87069             }
87070             return ts.visitEachChild(node, visitor, context);
87071         }
87072     }
87073     ts.transformES2019 = transformES2019;
87074 })(ts || (ts = {}));
87075 /*@internal*/
87076 var ts;
87077 (function (ts) {
87078     function transformES2020(context) {
87079         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
87080         return ts.chainBundle(context, transformSourceFile);
87081         function transformSourceFile(node) {
87082             if (node.isDeclarationFile) {
87083                 return node;
87084             }
87085             return ts.visitEachChild(node, visitor, context);
87086         }
87087         function visitor(node) {
87088             if ((node.transformFlags & 8 /* ContainsES2020 */) === 0) {
87089                 return node;
87090             }
87091             switch (node.kind) {
87092                 case 201 /* PropertyAccessExpression */:
87093                 case 202 /* ElementAccessExpression */:
87094                 case 203 /* CallExpression */:
87095                     if (node.flags & 32 /* OptionalChain */) {
87096                         var updated = visitOptionalExpression(node, /*captureThisArg*/ false, /*isDelete*/ false);
87097                         ts.Debug.assertNotNode(updated, ts.isSyntheticReference);
87098                         return updated;
87099                     }
87100                     return ts.visitEachChild(node, visitor, context);
87101                 case 216 /* BinaryExpression */:
87102                     if (node.operatorToken.kind === 60 /* QuestionQuestionToken */) {
87103                         return transformNullishCoalescingExpression(node);
87104                     }
87105                     return ts.visitEachChild(node, visitor, context);
87106                 case 210 /* DeleteExpression */:
87107                     return visitDeleteExpression(node);
87108                 default:
87109                     return ts.visitEachChild(node, visitor, context);
87110             }
87111         }
87112         function flattenChain(chain) {
87113             ts.Debug.assertNotNode(chain, ts.isNonNullChain);
87114             var links = [chain];
87115             while (!chain.questionDotToken && !ts.isTaggedTemplateExpression(chain)) {
87116                 chain = ts.cast(ts.skipPartiallyEmittedExpressions(chain.expression), ts.isOptionalChain);
87117                 ts.Debug.assertNotNode(chain, ts.isNonNullChain);
87118                 links.unshift(chain);
87119             }
87120             return { expression: chain.expression, chain: links };
87121         }
87122         function visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete) {
87123             var expression = visitNonOptionalExpression(node.expression, captureThisArg, isDelete);
87124             if (ts.isSyntheticReference(expression)) {
87125                 // `(a.b)` -> { expression `((_a = a).b)`, thisArg: `_a` }
87126                 // `(a[b])` -> { expression `((_a = a)[b])`, thisArg: `_a` }
87127                 return factory.createSyntheticReferenceExpression(factory.updateParenthesizedExpression(node, expression.expression), expression.thisArg);
87128             }
87129             return factory.updateParenthesizedExpression(node, expression);
87130         }
87131         function visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete) {
87132             if (ts.isOptionalChain(node)) {
87133                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
87134                 return visitOptionalExpression(node, captureThisArg, isDelete);
87135             }
87136             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
87137             ts.Debug.assertNotNode(expression, ts.isSyntheticReference);
87138             var thisArg;
87139             if (captureThisArg) {
87140                 if (!ts.isSimpleCopiableExpression(expression)) {
87141                     thisArg = factory.createTempVariable(hoistVariableDeclaration);
87142                     expression = factory.createAssignment(thisArg, expression);
87143                     // if (inParameterInitializer) tempVariableInParameter = true;
87144                 }
87145                 else {
87146                     thisArg = expression;
87147                 }
87148             }
87149             expression = node.kind === 201 /* PropertyAccessExpression */
87150                 ? factory.updatePropertyAccessExpression(node, expression, ts.visitNode(node.name, visitor, ts.isIdentifier))
87151                 : factory.updateElementAccessExpression(node, expression, ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
87152             return thisArg ? factory.createSyntheticReferenceExpression(expression, thisArg) : expression;
87153         }
87154         function visitNonOptionalCallExpression(node, captureThisArg) {
87155             if (ts.isOptionalChain(node)) {
87156                 // If `node` is an optional chain, then it is the outermost chain of an optional expression.
87157                 return visitOptionalExpression(node, captureThisArg, /*isDelete*/ false);
87158             }
87159             return ts.visitEachChild(node, visitor, context);
87160         }
87161         function visitNonOptionalExpression(node, captureThisArg, isDelete) {
87162             switch (node.kind) {
87163                 case 207 /* ParenthesizedExpression */: return visitNonOptionalParenthesizedExpression(node, captureThisArg, isDelete);
87164                 case 201 /* PropertyAccessExpression */:
87165                 case 202 /* ElementAccessExpression */: return visitNonOptionalPropertyOrElementAccessExpression(node, captureThisArg, isDelete);
87166                 case 203 /* CallExpression */: return visitNonOptionalCallExpression(node, captureThisArg);
87167                 default: return ts.visitNode(node, visitor, ts.isExpression);
87168             }
87169         }
87170         function visitOptionalExpression(node, captureThisArg, isDelete) {
87171             var _a = flattenChain(node), expression = _a.expression, chain = _a.chain;
87172             var left = visitNonOptionalExpression(expression, ts.isCallChain(chain[0]), /*isDelete*/ false);
87173             var leftThisArg = ts.isSyntheticReference(left) ? left.thisArg : undefined;
87174             var leftExpression = ts.isSyntheticReference(left) ? left.expression : left;
87175             var capturedLeft = leftExpression;
87176             if (!ts.isSimpleCopiableExpression(leftExpression)) {
87177                 capturedLeft = factory.createTempVariable(hoistVariableDeclaration);
87178                 leftExpression = factory.createAssignment(capturedLeft, leftExpression);
87179                 // if (inParameterInitializer) tempVariableInParameter = true;
87180             }
87181             var rightExpression = capturedLeft;
87182             var thisArg;
87183             for (var i = 0; i < chain.length; i++) {
87184                 var segment = chain[i];
87185                 switch (segment.kind) {
87186                     case 201 /* PropertyAccessExpression */:
87187                     case 202 /* ElementAccessExpression */:
87188                         if (i === chain.length - 1 && captureThisArg) {
87189                             if (!ts.isSimpleCopiableExpression(rightExpression)) {
87190                                 thisArg = factory.createTempVariable(hoistVariableDeclaration);
87191                                 rightExpression = factory.createAssignment(thisArg, rightExpression);
87192                                 // if (inParameterInitializer) tempVariableInParameter = true;
87193                             }
87194                             else {
87195                                 thisArg = rightExpression;
87196                             }
87197                         }
87198                         rightExpression = segment.kind === 201 /* PropertyAccessExpression */
87199                             ? factory.createPropertyAccessExpression(rightExpression, ts.visitNode(segment.name, visitor, ts.isIdentifier))
87200                             : factory.createElementAccessExpression(rightExpression, ts.visitNode(segment.argumentExpression, visitor, ts.isExpression));
87201                         break;
87202                     case 203 /* CallExpression */:
87203                         if (i === 0 && leftThisArg) {
87204                             rightExpression = factory.createFunctionCallCall(rightExpression, leftThisArg.kind === 105 /* SuperKeyword */ ? factory.createThis() : leftThisArg, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
87205                         }
87206                         else {
87207                             rightExpression = factory.createCallExpression(rightExpression, 
87208                             /*typeArguments*/ undefined, ts.visitNodes(segment.arguments, visitor, ts.isExpression));
87209                         }
87210                         break;
87211                 }
87212                 ts.setOriginalNode(rightExpression, segment);
87213             }
87214             var target = isDelete
87215                 ? factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createTrue(), /*colonToken*/ undefined, factory.createDeleteExpression(rightExpression))
87216                 : factory.createConditionalExpression(createNotNullCondition(leftExpression, capturedLeft, /*invert*/ true), /*questionToken*/ undefined, factory.createVoidZero(), /*colonToken*/ undefined, rightExpression);
87217             return thisArg ? factory.createSyntheticReferenceExpression(target, thisArg) : target;
87218         }
87219         function createNotNullCondition(left, right, invert) {
87220             return factory.createBinaryExpression(factory.createBinaryExpression(left, factory.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), factory.createNull()), factory.createToken(invert ? 56 /* BarBarToken */ : 55 /* AmpersandAmpersandToken */), factory.createBinaryExpression(right, factory.createToken(invert ? 36 /* EqualsEqualsEqualsToken */ : 37 /* ExclamationEqualsEqualsToken */), factory.createVoidZero()));
87221         }
87222         function transformNullishCoalescingExpression(node) {
87223             var left = ts.visitNode(node.left, visitor, ts.isExpression);
87224             var right = left;
87225             if (!ts.isSimpleCopiableExpression(left)) {
87226                 right = factory.createTempVariable(hoistVariableDeclaration);
87227                 left = factory.createAssignment(right, left);
87228                 // if (inParameterInitializer) tempVariableInParameter = true;
87229             }
87230             return factory.createConditionalExpression(createNotNullCondition(left, right), 
87231             /*questionToken*/ undefined, right, 
87232             /*colonToken*/ undefined, ts.visitNode(node.right, visitor, ts.isExpression));
87233         }
87234         function visitDeleteExpression(node) {
87235             return ts.isOptionalChain(ts.skipParentheses(node.expression))
87236                 ? ts.setOriginalNode(visitNonOptionalExpression(node.expression, /*captureThisArg*/ false, /*isDelete*/ true), node)
87237                 : factory.updateDeleteExpression(node, ts.visitNode(node.expression, visitor, ts.isExpression));
87238         }
87239     }
87240     ts.transformES2020 = transformES2020;
87241 })(ts || (ts = {}));
87242 /*@internal*/
87243 var ts;
87244 (function (ts) {
87245     function transformESNext(context) {
87246         var hoistVariableDeclaration = context.hoistVariableDeclaration, factory = context.factory;
87247         return ts.chainBundle(context, transformSourceFile);
87248         function transformSourceFile(node) {
87249             if (node.isDeclarationFile) {
87250                 return node;
87251             }
87252             return ts.visitEachChild(node, visitor, context);
87253         }
87254         function visitor(node) {
87255             if ((node.transformFlags & 4 /* ContainsESNext */) === 0) {
87256                 return node;
87257             }
87258             switch (node.kind) {
87259                 case 216 /* BinaryExpression */:
87260                     var binaryExpression = node;
87261                     if (ts.isLogicalOrCoalescingAssignmentExpression(binaryExpression)) {
87262                         return transformLogicalAssignment(binaryExpression);
87263                     }
87264                 // falls through
87265                 default:
87266                     return ts.visitEachChild(node, visitor, context);
87267             }
87268         }
87269         function transformLogicalAssignment(binaryExpression) {
87270             var operator = binaryExpression.operatorToken;
87271             var nonAssignmentOperator = ts.getNonAssignmentOperatorForCompoundAssignment(operator.kind);
87272             var left = ts.skipParentheses(ts.visitNode(binaryExpression.left, visitor, ts.isLeftHandSideExpression));
87273             var assignmentTarget = left;
87274             var right = ts.skipParentheses(ts.visitNode(binaryExpression.right, visitor, ts.isExpression));
87275             if (ts.isAccessExpression(left)) {
87276                 var propertyAccessTargetSimpleCopiable = ts.isSimpleCopiableExpression(left.expression);
87277                 var propertyAccessTarget = propertyAccessTargetSimpleCopiable ? left.expression :
87278                     factory.createTempVariable(hoistVariableDeclaration);
87279                 var propertyAccessTargetAssignment = propertyAccessTargetSimpleCopiable ? left.expression : factory.createAssignment(propertyAccessTarget, left.expression);
87280                 if (ts.isPropertyAccessExpression(left)) {
87281                     assignmentTarget = factory.createPropertyAccessExpression(propertyAccessTarget, left.name);
87282                     left = factory.createPropertyAccessExpression(propertyAccessTargetAssignment, left.name);
87283                 }
87284                 else {
87285                     var elementAccessArgumentSimpleCopiable = ts.isSimpleCopiableExpression(left.argumentExpression);
87286                     var elementAccessArgument = elementAccessArgumentSimpleCopiable ? left.argumentExpression :
87287                         factory.createTempVariable(hoistVariableDeclaration);
87288                     assignmentTarget = factory.createElementAccessExpression(propertyAccessTarget, elementAccessArgument);
87289                     left = factory.createElementAccessExpression(propertyAccessTargetAssignment, elementAccessArgumentSimpleCopiable ? left.argumentExpression : factory.createAssignment(elementAccessArgument, left.argumentExpression));
87290                 }
87291             }
87292             return factory.createBinaryExpression(left, nonAssignmentOperator, factory.createParenthesizedExpression(factory.createAssignment(assignmentTarget, right)));
87293         }
87294     }
87295     ts.transformESNext = transformESNext;
87296 })(ts || (ts = {}));
87297 /*@internal*/
87298 var ts;
87299 (function (ts) {
87300     function transformJsx(context) {
87301         var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
87302         var compilerOptions = context.getCompilerOptions();
87303         var currentSourceFile;
87304         var currentFileState;
87305         return ts.chainBundle(context, transformSourceFile);
87306         function getCurrentFileNameExpression() {
87307             if (currentFileState.filenameDeclaration) {
87308                 return currentFileState.filenameDeclaration.name;
87309             }
87310             var declaration = factory.createVariableDeclaration(factory.createUniqueName("_jsxFileName", 16 /* Optimistic */ | 32 /* FileLevel */), /*exclaimationToken*/ undefined, /*type*/ undefined, factory.createStringLiteral(currentSourceFile.fileName));
87311             currentFileState.filenameDeclaration = declaration;
87312             return currentFileState.filenameDeclaration.name;
87313         }
87314         function getJsxFactoryCalleePrimitive(childrenLength) {
87315             return compilerOptions.jsx === 5 /* ReactJSXDev */ ? "jsxDEV" : childrenLength > 1 ? "jsxs" : "jsx";
87316         }
87317         function getJsxFactoryCallee(childrenLength) {
87318             var type = getJsxFactoryCalleePrimitive(childrenLength);
87319             return getImplicitImportForName(type);
87320         }
87321         function getImplicitJsxFragmentReference() {
87322             return getImplicitImportForName("Fragment");
87323         }
87324         function getImplicitImportForName(name) {
87325             var _a, _b;
87326             var importSource = name === "createElement"
87327                 ? currentFileState.importSpecifier
87328                 : ts.getJSXRuntimeImport(currentFileState.importSpecifier, compilerOptions);
87329             var existing = (_b = (_a = currentFileState.utilizedImplicitRuntimeImports) === null || _a === void 0 ? void 0 : _a.get(importSource)) === null || _b === void 0 ? void 0 : _b.get(name);
87330             if (existing) {
87331                 return existing.name;
87332             }
87333             if (!currentFileState.utilizedImplicitRuntimeImports) {
87334                 currentFileState.utilizedImplicitRuntimeImports = ts.createMap();
87335             }
87336             var specifierSourceImports = currentFileState.utilizedImplicitRuntimeImports.get(importSource);
87337             if (!specifierSourceImports) {
87338                 specifierSourceImports = ts.createMap();
87339                 currentFileState.utilizedImplicitRuntimeImports.set(importSource, specifierSourceImports);
87340             }
87341             var generatedName = factory.createUniqueName("_" + name, 16 /* Optimistic */ | 32 /* FileLevel */ | 64 /* AllowNameSubstitution */);
87342             var specifier = factory.createImportSpecifier(factory.createIdentifier(name), generatedName);
87343             generatedName.generatedImportReference = specifier;
87344             specifierSourceImports.set(name, specifier);
87345             return generatedName;
87346         }
87347         /**
87348          * Transform JSX-specific syntax in a SourceFile.
87349          *
87350          * @param node A SourceFile node.
87351          */
87352         function transformSourceFile(node) {
87353             if (node.isDeclarationFile) {
87354                 return node;
87355             }
87356             currentSourceFile = node;
87357             currentFileState = {};
87358             currentFileState.importSpecifier = ts.getJSXImplicitImportBase(compilerOptions, node);
87359             var visited = ts.visitEachChild(node, visitor, context);
87360             ts.addEmitHelpers(visited, context.readEmitHelpers());
87361             var statements = visited.statements;
87362             if (currentFileState.filenameDeclaration) {
87363                 statements = ts.insertStatementAfterCustomPrologue(statements.slice(), factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([currentFileState.filenameDeclaration], 2 /* Const */)));
87364             }
87365             if (currentFileState.utilizedImplicitRuntimeImports) {
87366                 for (var _i = 0, _a = ts.arrayFrom(currentFileState.utilizedImplicitRuntimeImports.entries()); _i < _a.length; _i++) {
87367                     var _b = _a[_i], importSource = _b[0], importSpecifiersMap = _b[1];
87368                     if (ts.isExternalModule(node)) {
87369                         // Add `import` statement
87370                         var importStatement = factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, factory.createImportClause(/*typeOnly*/ false, /*name*/ undefined, factory.createNamedImports(ts.arrayFrom(importSpecifiersMap.values()))), factory.createStringLiteral(importSource));
87371                         ts.setParentRecursive(importStatement, /*incremental*/ false);
87372                         statements = ts.insertStatementAfterCustomPrologue(statements.slice(), importStatement);
87373                     }
87374                     else if (ts.isExternalOrCommonJsModule(node)) {
87375                         // Add `require` statement
87376                         var requireStatement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([
87377                             factory.createVariableDeclaration(factory.createObjectBindingPattern(ts.map(ts.arrayFrom(importSpecifiersMap.values()), function (s) { return factory.createBindingElement(/*dotdotdot*/ undefined, s.propertyName, s.name); })), 
87378                             /*exclaimationToken*/ undefined, 
87379                             /*type*/ undefined, factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, [factory.createStringLiteral(importSource)]))
87380                         ], 2 /* Const */));
87381                         ts.setParentRecursive(requireStatement, /*incremental*/ false);
87382                         statements = ts.insertStatementAfterCustomPrologue(statements.slice(), requireStatement);
87383                     }
87384                     else {
87385                         // Do nothing (script file) - consider an error in the checker?
87386                     }
87387                 }
87388             }
87389             if (statements !== visited.statements) {
87390                 visited = factory.updateSourceFile(visited, statements);
87391             }
87392             currentFileState = undefined;
87393             return visited;
87394         }
87395         function visitor(node) {
87396             if (node.transformFlags & 2 /* ContainsJsx */) {
87397                 return visitorWorker(node);
87398             }
87399             else {
87400                 return node;
87401             }
87402         }
87403         function visitorWorker(node) {
87404             switch (node.kind) {
87405                 case 273 /* JsxElement */:
87406                     return visitJsxElement(node, /*isChild*/ false);
87407                 case 274 /* JsxSelfClosingElement */:
87408                     return visitJsxSelfClosingElement(node, /*isChild*/ false);
87409                 case 277 /* JsxFragment */:
87410                     return visitJsxFragment(node, /*isChild*/ false);
87411                 case 283 /* JsxExpression */:
87412                     return visitJsxExpression(node);
87413                 default:
87414                     return ts.visitEachChild(node, visitor, context);
87415             }
87416         }
87417         function transformJsxChildToExpression(node) {
87418             switch (node.kind) {
87419                 case 11 /* JsxText */:
87420                     return visitJsxText(node);
87421                 case 283 /* JsxExpression */:
87422                     return visitJsxExpression(node);
87423                 case 273 /* JsxElement */:
87424                     return visitJsxElement(node, /*isChild*/ true);
87425                 case 274 /* JsxSelfClosingElement */:
87426                     return visitJsxSelfClosingElement(node, /*isChild*/ true);
87427                 case 277 /* JsxFragment */:
87428                     return visitJsxFragment(node, /*isChild*/ true);
87429                 default:
87430                     return ts.Debug.failBadSyntaxKind(node);
87431             }
87432         }
87433         /**
87434          * The react jsx/jsxs transform falls back to `createElement` when an explicit `key` argument comes after a spread
87435          */
87436         function hasKeyAfterPropsSpread(node) {
87437             var spread = false;
87438             for (var _i = 0, _a = node.attributes.properties; _i < _a.length; _i++) {
87439                 var elem = _a[_i];
87440                 if (ts.isJsxSpreadAttribute(elem)) {
87441                     spread = true;
87442                 }
87443                 else if (spread && ts.isJsxAttribute(elem) && elem.name.escapedText === "key") {
87444                     return true;
87445                 }
87446             }
87447             return false;
87448         }
87449         function shouldUseCreateElement(node) {
87450             return currentFileState.importSpecifier === undefined || hasKeyAfterPropsSpread(node);
87451         }
87452         function visitJsxElement(node, isChild) {
87453             var tagTransform = shouldUseCreateElement(node.openingElement) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
87454             return tagTransform(node.openingElement, node.children, isChild, /*location*/ node);
87455         }
87456         function visitJsxSelfClosingElement(node, isChild) {
87457             var tagTransform = shouldUseCreateElement(node) ? visitJsxOpeningLikeElementCreateElement : visitJsxOpeningLikeElementJSX;
87458             return tagTransform(node, /*children*/ undefined, isChild, /*location*/ node);
87459         }
87460         function visitJsxFragment(node, isChild) {
87461             var tagTransform = currentFileState.importSpecifier === undefined ? visitJsxOpeningFragmentCreateElement : visitJsxOpeningFragmentJSX;
87462             return tagTransform(node.openingFragment, node.children, isChild, /*location*/ node);
87463         }
87464         function convertJsxChildrenToChildrenPropObject(children) {
87465             var nonWhitespaceChildren = ts.getSemanticJsxChildren(children);
87466             if (ts.length(nonWhitespaceChildren) === 1) {
87467                 var result_13 = transformJsxChildToExpression(nonWhitespaceChildren[0]);
87468                 return result_13 && factory.createObjectLiteralExpression([
87469                     factory.createPropertyAssignment("children", result_13)
87470                 ]);
87471             }
87472             var result = ts.mapDefined(children, transformJsxChildToExpression);
87473             return !result.length ? undefined : factory.createObjectLiteralExpression([
87474                 factory.createPropertyAssignment("children", factory.createArrayLiteralExpression(result))
87475             ]);
87476         }
87477         function visitJsxOpeningLikeElementJSX(node, children, isChild, location) {
87478             var tagName = getTagName(node);
87479             var objectProperties;
87480             var keyAttr = ts.find(node.attributes.properties, function (p) { return !!p.name && ts.isIdentifier(p.name) && p.name.escapedText === "key"; });
87481             var attrs = keyAttr ? ts.filter(node.attributes.properties, function (p) { return p !== keyAttr; }) : node.attributes.properties;
87482             var segments = [];
87483             if (attrs.length) {
87484                 // Map spans of JsxAttribute nodes into object literals and spans
87485                 // of JsxSpreadAttribute nodes into expressions.
87486                 segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
87487                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
87488                     : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
87489                 if (ts.isJsxSpreadAttribute(attrs[0])) {
87490                     // We must always emit at least one object literal before a spread
87491                     // argument.factory.createObjectLiteral
87492                     segments.unshift(factory.createObjectLiteralExpression());
87493                 }
87494             }
87495             if (children && children.length) {
87496                 var result = convertJsxChildrenToChildrenPropObject(children);
87497                 if (result) {
87498                     segments.push(result);
87499                 }
87500             }
87501             if (segments.length === 0) {
87502                 objectProperties = factory.createObjectLiteralExpression([]);
87503                 // When there are no attributes, React wants {}
87504             }
87505             else {
87506                 // Either emit one big object literal (no spread attribs), or
87507                 // a call to the __assign helper.
87508                 objectProperties = ts.singleOrUndefined(segments) || emitHelpers().createAssignHelper(segments);
87509             }
87510             return visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, ts.length(ts.getSemanticJsxChildren(children || ts.emptyArray)), isChild, location);
87511         }
87512         function visitJsxOpeningLikeElementOrFragmentJSX(tagName, objectProperties, keyAttr, childrenLength, isChild, location) {
87513             var args = [tagName, objectProperties, !keyAttr ? factory.createVoidZero() : transformJsxAttributeInitializer(keyAttr.initializer)];
87514             if (compilerOptions.jsx === 5 /* ReactJSXDev */) {
87515                 var originalFile = ts.getOriginalNode(currentSourceFile);
87516                 if (originalFile && ts.isSourceFile(originalFile)) {
87517                     // isStaticChildren development flag
87518                     args.push(childrenLength > 1 ? factory.createTrue() : factory.createFalse());
87519                     // __source development flag
87520                     var lineCol = ts.getLineAndCharacterOfPosition(originalFile, location.pos);
87521                     args.push(factory.createObjectLiteralExpression([
87522                         factory.createPropertyAssignment("fileName", getCurrentFileNameExpression()),
87523                         factory.createPropertyAssignment("lineNumber", factory.createNumericLiteral(lineCol.line + 1)),
87524                         factory.createPropertyAssignment("columnNumber", factory.createNumericLiteral(lineCol.character + 1))
87525                     ]));
87526                     // __self development flag
87527                     args.push(factory.createThis());
87528                 }
87529             }
87530             var element = ts.setTextRange(factory.createCallExpression(getJsxFactoryCallee(childrenLength), /*typeArguments*/ undefined, args), location);
87531             if (isChild) {
87532                 ts.startOnNewLine(element);
87533             }
87534             return element;
87535         }
87536         function visitJsxOpeningLikeElementCreateElement(node, children, isChild, location) {
87537             var tagName = getTagName(node);
87538             var objectProperties;
87539             var attrs = node.attributes.properties;
87540             if (attrs.length === 0) {
87541                 objectProperties = factory.createNull();
87542                 // When there are no attributes, React wants "null"
87543             }
87544             else {
87545                 // Map spans of JsxAttribute nodes into object literals and spans
87546                 // of JsxSpreadAttribute nodes into expressions.
87547                 var segments = ts.flatten(ts.spanMap(attrs, ts.isJsxSpreadAttribute, function (attrs, isSpread) { return isSpread
87548                     ? ts.map(attrs, transformJsxSpreadAttributeToExpression)
87549                     : factory.createObjectLiteralExpression(ts.map(attrs, transformJsxAttributeToObjectLiteralElement)); }));
87550                 if (ts.isJsxSpreadAttribute(attrs[0])) {
87551                     // We must always emit at least one object literal before a spread
87552                     // argument.factory.createObjectLiteral
87553                     segments.unshift(factory.createObjectLiteralExpression());
87554                 }
87555                 // Either emit one big object literal (no spread attribs), or
87556                 // a call to the __assign helper.
87557                 objectProperties = ts.singleOrUndefined(segments);
87558                 if (!objectProperties) {
87559                     objectProperties = emitHelpers().createAssignHelper(segments);
87560                 }
87561             }
87562             var callee = currentFileState.importSpecifier === undefined
87563                 ? ts.createJsxFactoryExpression(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
87564                 node)
87565                 : getImplicitImportForName("createElement");
87566             var element = ts.createExpressionForJsxElement(factory, callee, tagName, objectProperties, ts.mapDefined(children, transformJsxChildToExpression), location);
87567             if (isChild) {
87568                 ts.startOnNewLine(element);
87569             }
87570             return element;
87571         }
87572         function visitJsxOpeningFragmentJSX(_node, children, isChild, location) {
87573             var childrenProps;
87574             if (children && children.length) {
87575                 var result = convertJsxChildrenToChildrenPropObject(children);
87576                 if (result) {
87577                     childrenProps = result;
87578                 }
87579             }
87580             return visitJsxOpeningLikeElementOrFragmentJSX(getImplicitJsxFragmentReference(), childrenProps || factory.createObjectLiteralExpression([]), 
87581             /*keyAttr*/ undefined, ts.length(ts.getSemanticJsxChildren(children)), isChild, location);
87582         }
87583         function visitJsxOpeningFragmentCreateElement(node, children, isChild, location) {
87584             var element = ts.createExpressionForJsxFragment(factory, context.getEmitResolver().getJsxFactoryEntity(currentSourceFile), context.getEmitResolver().getJsxFragmentFactoryEntity(currentSourceFile), compilerOptions.reactNamespace, // TODO: GH#18217
87585             ts.mapDefined(children, transformJsxChildToExpression), node, location);
87586             if (isChild) {
87587                 ts.startOnNewLine(element);
87588             }
87589             return element;
87590         }
87591         function transformJsxSpreadAttributeToExpression(node) {
87592             return ts.visitNode(node.expression, visitor, ts.isExpression);
87593         }
87594         function transformJsxAttributeToObjectLiteralElement(node) {
87595             var name = getAttributeName(node);
87596             var expression = transformJsxAttributeInitializer(node.initializer);
87597             return factory.createPropertyAssignment(name, expression);
87598         }
87599         function transformJsxAttributeInitializer(node) {
87600             if (node === undefined) {
87601                 return factory.createTrue();
87602             }
87603             else if (node.kind === 10 /* StringLiteral */) {
87604                 // Always recreate the literal to escape any escape sequences or newlines which may be in the original jsx string and which
87605                 // Need to be escaped to be handled correctly in a normal string
87606                 var singleQuote = node.singleQuote !== undefined ? node.singleQuote : !ts.isStringDoubleQuoted(node, currentSourceFile);
87607                 var literal = factory.createStringLiteral(tryDecodeEntities(node.text) || node.text, singleQuote);
87608                 return ts.setTextRange(literal, node);
87609             }
87610             else if (node.kind === 283 /* JsxExpression */) {
87611                 if (node.expression === undefined) {
87612                     return factory.createTrue();
87613                 }
87614                 return ts.visitNode(node.expression, visitor, ts.isExpression);
87615             }
87616             else {
87617                 return ts.Debug.failBadSyntaxKind(node);
87618             }
87619         }
87620         function visitJsxText(node) {
87621             var fixed = fixupWhitespaceAndDecodeEntities(node.text);
87622             return fixed === undefined ? undefined : factory.createStringLiteral(fixed);
87623         }
87624         /**
87625          * JSX trims whitespace at the end and beginning of lines, except that the
87626          * start/end of a tag is considered a start/end of a line only if that line is
87627          * on the same line as the closing tag. See examples in
87628          * tests/cases/conformance/jsx/tsxReactEmitWhitespace.tsx
87629          * 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
87630          *
87631          * An equivalent algorithm would be:
87632          * - If there is only one line, return it.
87633          * - If there is only whitespace (but multiple lines), return `undefined`.
87634          * - Split the text into lines.
87635          * - 'trimRight' the first line, 'trimLeft' the last line, 'trim' middle lines.
87636          * - Decode entities on each line (individually).
87637          * - Remove empty lines and join the rest with " ".
87638          */
87639         function fixupWhitespaceAndDecodeEntities(text) {
87640             var acc;
87641             // First non-whitespace character on this line.
87642             var firstNonWhitespace = 0;
87643             // Last non-whitespace character on this line.
87644             var lastNonWhitespace = -1;
87645             // These initial values are special because the first line is:
87646             // firstNonWhitespace = 0 to indicate that we want leading whitsepace,
87647             // but lastNonWhitespace = -1 as a special flag to indicate that we *don't* include the line if it's all whitespace.
87648             for (var i = 0; i < text.length; i++) {
87649                 var c = text.charCodeAt(i);
87650                 if (ts.isLineBreak(c)) {
87651                     // If we've seen any non-whitespace characters on this line, add the 'trim' of the line.
87652                     // (lastNonWhitespace === -1 is a special flag to detect whether the first line is all whitespace.)
87653                     if (firstNonWhitespace !== -1 && lastNonWhitespace !== -1) {
87654                         acc = addLineOfJsxText(acc, text.substr(firstNonWhitespace, lastNonWhitespace - firstNonWhitespace + 1));
87655                     }
87656                     // Reset firstNonWhitespace for the next line.
87657                     // Don't bother to reset lastNonWhitespace because we ignore it if firstNonWhitespace = -1.
87658                     firstNonWhitespace = -1;
87659                 }
87660                 else if (!ts.isWhiteSpaceSingleLine(c)) {
87661                     lastNonWhitespace = i;
87662                     if (firstNonWhitespace === -1) {
87663                         firstNonWhitespace = i;
87664                     }
87665                 }
87666             }
87667             return firstNonWhitespace !== -1
87668                 // Last line had a non-whitespace character. Emit the 'trimLeft', meaning keep trailing whitespace.
87669                 ? addLineOfJsxText(acc, text.substr(firstNonWhitespace))
87670                 // Last line was all whitespace, so ignore it
87671                 : acc;
87672         }
87673         function addLineOfJsxText(acc, trimmedLine) {
87674             // We do not escape the string here as that is handled by the printer
87675             // when it emits the literal. We do, however, need to decode JSX entities.
87676             var decoded = decodeEntities(trimmedLine);
87677             return acc === undefined ? decoded : acc + " " + decoded;
87678         }
87679         /**
87680          * Replace entities like "&nbsp;", "&#123;", and "&#xDEADBEEF;" with the characters they encode.
87681          * See https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references
87682          */
87683         function decodeEntities(text) {
87684             return text.replace(/&((#((\d+)|x([\da-fA-F]+)))|(\w+));/g, function (match, _all, _number, _digits, decimal, hex, word) {
87685                 if (decimal) {
87686                     return ts.utf16EncodeAsString(parseInt(decimal, 10));
87687                 }
87688                 else if (hex) {
87689                     return ts.utf16EncodeAsString(parseInt(hex, 16));
87690                 }
87691                 else {
87692                     var ch = entities.get(word);
87693                     // If this is not a valid entity, then just use `match` (replace it with itself, i.e. don't replace)
87694                     return ch ? ts.utf16EncodeAsString(ch) : match;
87695                 }
87696             });
87697         }
87698         /** Like `decodeEntities` but returns `undefined` if there were no entities to decode. */
87699         function tryDecodeEntities(text) {
87700             var decoded = decodeEntities(text);
87701             return decoded === text ? undefined : decoded;
87702         }
87703         function getTagName(node) {
87704             if (node.kind === 273 /* JsxElement */) {
87705                 return getTagName(node.openingElement);
87706             }
87707             else {
87708                 var name = node.tagName;
87709                 if (ts.isIdentifier(name) && ts.isIntrinsicJsxName(name.escapedText)) {
87710                     return factory.createStringLiteral(ts.idText(name));
87711                 }
87712                 else {
87713                     return ts.createExpressionFromEntityName(factory, name);
87714                 }
87715             }
87716         }
87717         /**
87718          * Emit an attribute name, which is quoted if it needs to be quoted. Because
87719          * these emit into an object literal property name, we don't need to be worried
87720          * about keywords, just non-identifier characters
87721          */
87722         function getAttributeName(node) {
87723             var name = node.name;
87724             var text = ts.idText(name);
87725             if (/^[A-Za-z_]\w*$/.test(text)) {
87726                 return name;
87727             }
87728             else {
87729                 return factory.createStringLiteral(text);
87730             }
87731         }
87732         function visitJsxExpression(node) {
87733             return ts.visitNode(node.expression, visitor, ts.isExpression);
87734         }
87735     }
87736     ts.transformJsx = transformJsx;
87737     var entities = new ts.Map(ts.getEntries({
87738         quot: 0x0022,
87739         amp: 0x0026,
87740         apos: 0x0027,
87741         lt: 0x003C,
87742         gt: 0x003E,
87743         nbsp: 0x00A0,
87744         iexcl: 0x00A1,
87745         cent: 0x00A2,
87746         pound: 0x00A3,
87747         curren: 0x00A4,
87748         yen: 0x00A5,
87749         brvbar: 0x00A6,
87750         sect: 0x00A7,
87751         uml: 0x00A8,
87752         copy: 0x00A9,
87753         ordf: 0x00AA,
87754         laquo: 0x00AB,
87755         not: 0x00AC,
87756         shy: 0x00AD,
87757         reg: 0x00AE,
87758         macr: 0x00AF,
87759         deg: 0x00B0,
87760         plusmn: 0x00B1,
87761         sup2: 0x00B2,
87762         sup3: 0x00B3,
87763         acute: 0x00B4,
87764         micro: 0x00B5,
87765         para: 0x00B6,
87766         middot: 0x00B7,
87767         cedil: 0x00B8,
87768         sup1: 0x00B9,
87769         ordm: 0x00BA,
87770         raquo: 0x00BB,
87771         frac14: 0x00BC,
87772         frac12: 0x00BD,
87773         frac34: 0x00BE,
87774         iquest: 0x00BF,
87775         Agrave: 0x00C0,
87776         Aacute: 0x00C1,
87777         Acirc: 0x00C2,
87778         Atilde: 0x00C3,
87779         Auml: 0x00C4,
87780         Aring: 0x00C5,
87781         AElig: 0x00C6,
87782         Ccedil: 0x00C7,
87783         Egrave: 0x00C8,
87784         Eacute: 0x00C9,
87785         Ecirc: 0x00CA,
87786         Euml: 0x00CB,
87787         Igrave: 0x00CC,
87788         Iacute: 0x00CD,
87789         Icirc: 0x00CE,
87790         Iuml: 0x00CF,
87791         ETH: 0x00D0,
87792         Ntilde: 0x00D1,
87793         Ograve: 0x00D2,
87794         Oacute: 0x00D3,
87795         Ocirc: 0x00D4,
87796         Otilde: 0x00D5,
87797         Ouml: 0x00D6,
87798         times: 0x00D7,
87799         Oslash: 0x00D8,
87800         Ugrave: 0x00D9,
87801         Uacute: 0x00DA,
87802         Ucirc: 0x00DB,
87803         Uuml: 0x00DC,
87804         Yacute: 0x00DD,
87805         THORN: 0x00DE,
87806         szlig: 0x00DF,
87807         agrave: 0x00E0,
87808         aacute: 0x00E1,
87809         acirc: 0x00E2,
87810         atilde: 0x00E3,
87811         auml: 0x00E4,
87812         aring: 0x00E5,
87813         aelig: 0x00E6,
87814         ccedil: 0x00E7,
87815         egrave: 0x00E8,
87816         eacute: 0x00E9,
87817         ecirc: 0x00EA,
87818         euml: 0x00EB,
87819         igrave: 0x00EC,
87820         iacute: 0x00ED,
87821         icirc: 0x00EE,
87822         iuml: 0x00EF,
87823         eth: 0x00F0,
87824         ntilde: 0x00F1,
87825         ograve: 0x00F2,
87826         oacute: 0x00F3,
87827         ocirc: 0x00F4,
87828         otilde: 0x00F5,
87829         ouml: 0x00F6,
87830         divide: 0x00F7,
87831         oslash: 0x00F8,
87832         ugrave: 0x00F9,
87833         uacute: 0x00FA,
87834         ucirc: 0x00FB,
87835         uuml: 0x00FC,
87836         yacute: 0x00FD,
87837         thorn: 0x00FE,
87838         yuml: 0x00FF,
87839         OElig: 0x0152,
87840         oelig: 0x0153,
87841         Scaron: 0x0160,
87842         scaron: 0x0161,
87843         Yuml: 0x0178,
87844         fnof: 0x0192,
87845         circ: 0x02C6,
87846         tilde: 0x02DC,
87847         Alpha: 0x0391,
87848         Beta: 0x0392,
87849         Gamma: 0x0393,
87850         Delta: 0x0394,
87851         Epsilon: 0x0395,
87852         Zeta: 0x0396,
87853         Eta: 0x0397,
87854         Theta: 0x0398,
87855         Iota: 0x0399,
87856         Kappa: 0x039A,
87857         Lambda: 0x039B,
87858         Mu: 0x039C,
87859         Nu: 0x039D,
87860         Xi: 0x039E,
87861         Omicron: 0x039F,
87862         Pi: 0x03A0,
87863         Rho: 0x03A1,
87864         Sigma: 0x03A3,
87865         Tau: 0x03A4,
87866         Upsilon: 0x03A5,
87867         Phi: 0x03A6,
87868         Chi: 0x03A7,
87869         Psi: 0x03A8,
87870         Omega: 0x03A9,
87871         alpha: 0x03B1,
87872         beta: 0x03B2,
87873         gamma: 0x03B3,
87874         delta: 0x03B4,
87875         epsilon: 0x03B5,
87876         zeta: 0x03B6,
87877         eta: 0x03B7,
87878         theta: 0x03B8,
87879         iota: 0x03B9,
87880         kappa: 0x03BA,
87881         lambda: 0x03BB,
87882         mu: 0x03BC,
87883         nu: 0x03BD,
87884         xi: 0x03BE,
87885         omicron: 0x03BF,
87886         pi: 0x03C0,
87887         rho: 0x03C1,
87888         sigmaf: 0x03C2,
87889         sigma: 0x03C3,
87890         tau: 0x03C4,
87891         upsilon: 0x03C5,
87892         phi: 0x03C6,
87893         chi: 0x03C7,
87894         psi: 0x03C8,
87895         omega: 0x03C9,
87896         thetasym: 0x03D1,
87897         upsih: 0x03D2,
87898         piv: 0x03D6,
87899         ensp: 0x2002,
87900         emsp: 0x2003,
87901         thinsp: 0x2009,
87902         zwnj: 0x200C,
87903         zwj: 0x200D,
87904         lrm: 0x200E,
87905         rlm: 0x200F,
87906         ndash: 0x2013,
87907         mdash: 0x2014,
87908         lsquo: 0x2018,
87909         rsquo: 0x2019,
87910         sbquo: 0x201A,
87911         ldquo: 0x201C,
87912         rdquo: 0x201D,
87913         bdquo: 0x201E,
87914         dagger: 0x2020,
87915         Dagger: 0x2021,
87916         bull: 0x2022,
87917         hellip: 0x2026,
87918         permil: 0x2030,
87919         prime: 0x2032,
87920         Prime: 0x2033,
87921         lsaquo: 0x2039,
87922         rsaquo: 0x203A,
87923         oline: 0x203E,
87924         frasl: 0x2044,
87925         euro: 0x20AC,
87926         image: 0x2111,
87927         weierp: 0x2118,
87928         real: 0x211C,
87929         trade: 0x2122,
87930         alefsym: 0x2135,
87931         larr: 0x2190,
87932         uarr: 0x2191,
87933         rarr: 0x2192,
87934         darr: 0x2193,
87935         harr: 0x2194,
87936         crarr: 0x21B5,
87937         lArr: 0x21D0,
87938         uArr: 0x21D1,
87939         rArr: 0x21D2,
87940         dArr: 0x21D3,
87941         hArr: 0x21D4,
87942         forall: 0x2200,
87943         part: 0x2202,
87944         exist: 0x2203,
87945         empty: 0x2205,
87946         nabla: 0x2207,
87947         isin: 0x2208,
87948         notin: 0x2209,
87949         ni: 0x220B,
87950         prod: 0x220F,
87951         sum: 0x2211,
87952         minus: 0x2212,
87953         lowast: 0x2217,
87954         radic: 0x221A,
87955         prop: 0x221D,
87956         infin: 0x221E,
87957         ang: 0x2220,
87958         and: 0x2227,
87959         or: 0x2228,
87960         cap: 0x2229,
87961         cup: 0x222A,
87962         int: 0x222B,
87963         there4: 0x2234,
87964         sim: 0x223C,
87965         cong: 0x2245,
87966         asymp: 0x2248,
87967         ne: 0x2260,
87968         equiv: 0x2261,
87969         le: 0x2264,
87970         ge: 0x2265,
87971         sub: 0x2282,
87972         sup: 0x2283,
87973         nsub: 0x2284,
87974         sube: 0x2286,
87975         supe: 0x2287,
87976         oplus: 0x2295,
87977         otimes: 0x2297,
87978         perp: 0x22A5,
87979         sdot: 0x22C5,
87980         lceil: 0x2308,
87981         rceil: 0x2309,
87982         lfloor: 0x230A,
87983         rfloor: 0x230B,
87984         lang: 0x2329,
87985         rang: 0x232A,
87986         loz: 0x25CA,
87987         spades: 0x2660,
87988         clubs: 0x2663,
87989         hearts: 0x2665,
87990         diams: 0x2666
87991     }));
87992 })(ts || (ts = {}));
87993 /*@internal*/
87994 var ts;
87995 (function (ts) {
87996     function transformES2016(context) {
87997         var factory = context.factory, hoistVariableDeclaration = context.hoistVariableDeclaration;
87998         return ts.chainBundle(context, transformSourceFile);
87999         function transformSourceFile(node) {
88000             if (node.isDeclarationFile) {
88001                 return node;
88002             }
88003             return ts.visitEachChild(node, visitor, context);
88004         }
88005         function visitor(node) {
88006             if ((node.transformFlags & 128 /* ContainsES2016 */) === 0) {
88007                 return node;
88008             }
88009             switch (node.kind) {
88010                 case 216 /* BinaryExpression */:
88011                     return visitBinaryExpression(node);
88012                 default:
88013                     return ts.visitEachChild(node, visitor, context);
88014             }
88015         }
88016         function visitBinaryExpression(node) {
88017             switch (node.operatorToken.kind) {
88018                 case 66 /* AsteriskAsteriskEqualsToken */:
88019                     return visitExponentiationAssignmentExpression(node);
88020                 case 42 /* AsteriskAsteriskToken */:
88021                     return visitExponentiationExpression(node);
88022                 default:
88023                     return ts.visitEachChild(node, visitor, context);
88024             }
88025         }
88026         function visitExponentiationAssignmentExpression(node) {
88027             var target;
88028             var value;
88029             var left = ts.visitNode(node.left, visitor, ts.isExpression);
88030             var right = ts.visitNode(node.right, visitor, ts.isExpression);
88031             if (ts.isElementAccessExpression(left)) {
88032                 // Transforms `a[x] **= b` into `(_a = a)[_x = x] = Math.pow(_a[_x], b)`
88033                 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
88034                 var argumentExpressionTemp = factory.createTempVariable(hoistVariableDeclaration);
88035                 target = ts.setTextRange(factory.createElementAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), ts.setTextRange(factory.createAssignment(argumentExpressionTemp, left.argumentExpression), left.argumentExpression)), left);
88036                 value = ts.setTextRange(factory.createElementAccessExpression(expressionTemp, argumentExpressionTemp), left);
88037             }
88038             else if (ts.isPropertyAccessExpression(left)) {
88039                 // Transforms `a.x **= b` into `(_a = a).x = Math.pow(_a.x, b)`
88040                 var expressionTemp = factory.createTempVariable(hoistVariableDeclaration);
88041                 target = ts.setTextRange(factory.createPropertyAccessExpression(ts.setTextRange(factory.createAssignment(expressionTemp, left.expression), left.expression), left.name), left);
88042                 value = ts.setTextRange(factory.createPropertyAccessExpression(expressionTemp, left.name), left);
88043             }
88044             else {
88045                 // Transforms `a **= b` into `a = Math.pow(a, b)`
88046                 target = left;
88047                 value = left;
88048             }
88049             return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [value, right]), node)), node);
88050         }
88051         function visitExponentiationExpression(node) {
88052             // Transforms `a ** b` into `Math.pow(a, b)`
88053             var left = ts.visitNode(node.left, visitor, ts.isExpression);
88054             var right = ts.visitNode(node.right, visitor, ts.isExpression);
88055             return ts.setTextRange(factory.createGlobalMethodCall("Math", "pow", [left, right]), node);
88056         }
88057     }
88058     ts.transformES2016 = transformES2016;
88059 })(ts || (ts = {}));
88060 /*@internal*/
88061 var ts;
88062 (function (ts) {
88063     var ES2015SubstitutionFlags;
88064     (function (ES2015SubstitutionFlags) {
88065         /** Enables substitutions for captured `this` */
88066         ES2015SubstitutionFlags[ES2015SubstitutionFlags["CapturedThis"] = 1] = "CapturedThis";
88067         /** Enables substitutions for block-scoped bindings. */
88068         ES2015SubstitutionFlags[ES2015SubstitutionFlags["BlockScopedBindings"] = 2] = "BlockScopedBindings";
88069     })(ES2015SubstitutionFlags || (ES2015SubstitutionFlags = {}));
88070     var LoopOutParameterFlags;
88071     (function (LoopOutParameterFlags) {
88072         LoopOutParameterFlags[LoopOutParameterFlags["Body"] = 1] = "Body";
88073         LoopOutParameterFlags[LoopOutParameterFlags["Initializer"] = 2] = "Initializer";
88074     })(LoopOutParameterFlags || (LoopOutParameterFlags = {}));
88075     var CopyDirection;
88076     (function (CopyDirection) {
88077         CopyDirection[CopyDirection["ToOriginal"] = 0] = "ToOriginal";
88078         CopyDirection[CopyDirection["ToOutParameter"] = 1] = "ToOutParameter";
88079     })(CopyDirection || (CopyDirection = {}));
88080     var Jump;
88081     (function (Jump) {
88082         Jump[Jump["Break"] = 2] = "Break";
88083         Jump[Jump["Continue"] = 4] = "Continue";
88084         Jump[Jump["Return"] = 8] = "Return";
88085     })(Jump || (Jump = {}));
88086     // Facts we track as we traverse the tree
88087     var HierarchyFacts;
88088     (function (HierarchyFacts) {
88089         HierarchyFacts[HierarchyFacts["None"] = 0] = "None";
88090         //
88091         // Ancestor facts
88092         //
88093         HierarchyFacts[HierarchyFacts["Function"] = 1] = "Function";
88094         HierarchyFacts[HierarchyFacts["ArrowFunction"] = 2] = "ArrowFunction";
88095         HierarchyFacts[HierarchyFacts["AsyncFunctionBody"] = 4] = "AsyncFunctionBody";
88096         HierarchyFacts[HierarchyFacts["NonStaticClassElement"] = 8] = "NonStaticClassElement";
88097         HierarchyFacts[HierarchyFacts["CapturesThis"] = 16] = "CapturesThis";
88098         HierarchyFacts[HierarchyFacts["ExportedVariableStatement"] = 32] = "ExportedVariableStatement";
88099         HierarchyFacts[HierarchyFacts["TopLevel"] = 64] = "TopLevel";
88100         HierarchyFacts[HierarchyFacts["Block"] = 128] = "Block";
88101         HierarchyFacts[HierarchyFacts["IterationStatement"] = 256] = "IterationStatement";
88102         HierarchyFacts[HierarchyFacts["IterationStatementBlock"] = 512] = "IterationStatementBlock";
88103         HierarchyFacts[HierarchyFacts["IterationContainer"] = 1024] = "IterationContainer";
88104         HierarchyFacts[HierarchyFacts["ForStatement"] = 2048] = "ForStatement";
88105         HierarchyFacts[HierarchyFacts["ForInOrForOfStatement"] = 4096] = "ForInOrForOfStatement";
88106         HierarchyFacts[HierarchyFacts["ConstructorWithCapturedSuper"] = 8192] = "ConstructorWithCapturedSuper";
88107         // NOTE: do not add more ancestor flags without also updating AncestorFactsMask below.
88108         // NOTE: when adding a new ancestor flag, be sure to update the subtree flags below.
88109         //
88110         // Ancestor masks
88111         //
88112         HierarchyFacts[HierarchyFacts["AncestorFactsMask"] = 16383] = "AncestorFactsMask";
88113         // We are always in *some* kind of block scope, but only specific block-scope containers are
88114         // top-level or Blocks.
88115         HierarchyFacts[HierarchyFacts["BlockScopeIncludes"] = 0] = "BlockScopeIncludes";
88116         HierarchyFacts[HierarchyFacts["BlockScopeExcludes"] = 7104] = "BlockScopeExcludes";
88117         // A source file is a top-level block scope.
88118         HierarchyFacts[HierarchyFacts["SourceFileIncludes"] = 64] = "SourceFileIncludes";
88119         HierarchyFacts[HierarchyFacts["SourceFileExcludes"] = 8064] = "SourceFileExcludes";
88120         // Functions, methods, and accessors are both new lexical scopes and new block scopes.
88121         HierarchyFacts[HierarchyFacts["FunctionIncludes"] = 65] = "FunctionIncludes";
88122         HierarchyFacts[HierarchyFacts["FunctionExcludes"] = 16286] = "FunctionExcludes";
88123         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyIncludes"] = 69] = "AsyncFunctionBodyIncludes";
88124         HierarchyFacts[HierarchyFacts["AsyncFunctionBodyExcludes"] = 16278] = "AsyncFunctionBodyExcludes";
88125         // Arrow functions are lexically scoped to their container, but are new block scopes.
88126         HierarchyFacts[HierarchyFacts["ArrowFunctionIncludes"] = 66] = "ArrowFunctionIncludes";
88127         HierarchyFacts[HierarchyFacts["ArrowFunctionExcludes"] = 15232] = "ArrowFunctionExcludes";
88128         // Constructors are both new lexical scopes and new block scopes. Constructors are also
88129         // always considered non-static members of a class.
88130         HierarchyFacts[HierarchyFacts["ConstructorIncludes"] = 73] = "ConstructorIncludes";
88131         HierarchyFacts[HierarchyFacts["ConstructorExcludes"] = 16278] = "ConstructorExcludes";
88132         // 'do' and 'while' statements are not block scopes. We track that the subtree is contained
88133         // within an IterationStatement to indicate whether the embedded statement is an
88134         // IterationStatementBlock.
88135         HierarchyFacts[HierarchyFacts["DoOrWhileStatementIncludes"] = 1280] = "DoOrWhileStatementIncludes";
88136         HierarchyFacts[HierarchyFacts["DoOrWhileStatementExcludes"] = 0] = "DoOrWhileStatementExcludes";
88137         // 'for' statements are new block scopes and have special handling for 'let' declarations.
88138         HierarchyFacts[HierarchyFacts["ForStatementIncludes"] = 3328] = "ForStatementIncludes";
88139         HierarchyFacts[HierarchyFacts["ForStatementExcludes"] = 5056] = "ForStatementExcludes";
88140         // 'for-in' and 'for-of' statements are new block scopes and have special handling for
88141         // 'let' declarations.
88142         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementIncludes"] = 5376] = "ForInOrForOfStatementIncludes";
88143         HierarchyFacts[HierarchyFacts["ForInOrForOfStatementExcludes"] = 3008] = "ForInOrForOfStatementExcludes";
88144         // Blocks (other than function bodies) are new block scopes.
88145         HierarchyFacts[HierarchyFacts["BlockIncludes"] = 128] = "BlockIncludes";
88146         HierarchyFacts[HierarchyFacts["BlockExcludes"] = 6976] = "BlockExcludes";
88147         HierarchyFacts[HierarchyFacts["IterationStatementBlockIncludes"] = 512] = "IterationStatementBlockIncludes";
88148         HierarchyFacts[HierarchyFacts["IterationStatementBlockExcludes"] = 7104] = "IterationStatementBlockExcludes";
88149         //
88150         // Subtree facts
88151         //
88152         HierarchyFacts[HierarchyFacts["NewTarget"] = 16384] = "NewTarget";
88153         HierarchyFacts[HierarchyFacts["CapturedLexicalThis"] = 32768] = "CapturedLexicalThis";
88154         //
88155         // Subtree masks
88156         //
88157         HierarchyFacts[HierarchyFacts["SubtreeFactsMask"] = -16384] = "SubtreeFactsMask";
88158         HierarchyFacts[HierarchyFacts["ArrowFunctionSubtreeExcludes"] = 0] = "ArrowFunctionSubtreeExcludes";
88159         HierarchyFacts[HierarchyFacts["FunctionSubtreeExcludes"] = 49152] = "FunctionSubtreeExcludes";
88160     })(HierarchyFacts || (HierarchyFacts = {}));
88161     function transformES2015(context) {
88162         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
88163         var compilerOptions = context.getCompilerOptions();
88164         var resolver = context.getEmitResolver();
88165         var previousOnSubstituteNode = context.onSubstituteNode;
88166         var previousOnEmitNode = context.onEmitNode;
88167         context.onEmitNode = onEmitNode;
88168         context.onSubstituteNode = onSubstituteNode;
88169         var currentSourceFile;
88170         var currentText;
88171         var hierarchyFacts;
88172         var taggedTemplateStringDeclarations;
88173         function recordTaggedTemplateString(temp) {
88174             taggedTemplateStringDeclarations = ts.append(taggedTemplateStringDeclarations, factory.createVariableDeclaration(temp));
88175         }
88176         /**
88177          * Used to track if we are emitting body of the converted loop
88178          */
88179         var convertedLoopState;
88180         /**
88181          * Keeps track of whether substitutions have been enabled for specific cases.
88182          * They are persisted between each SourceFile transformation and should not
88183          * be reset.
88184          */
88185         var enabledSubstitutions;
88186         return ts.chainBundle(context, transformSourceFile);
88187         function transformSourceFile(node) {
88188             if (node.isDeclarationFile) {
88189                 return node;
88190             }
88191             currentSourceFile = node;
88192             currentText = node.text;
88193             var visited = visitSourceFile(node);
88194             ts.addEmitHelpers(visited, context.readEmitHelpers());
88195             currentSourceFile = undefined;
88196             currentText = undefined;
88197             taggedTemplateStringDeclarations = undefined;
88198             hierarchyFacts = 0 /* None */;
88199             return visited;
88200         }
88201         /**
88202          * Sets the `HierarchyFacts` for this node prior to visiting this node's subtree, returning the facts set prior to modification.
88203          * @param excludeFacts The existing `HierarchyFacts` to reset before visiting the subtree.
88204          * @param includeFacts The new `HierarchyFacts` to set before visiting the subtree.
88205          */
88206         function enterSubtree(excludeFacts, includeFacts) {
88207             var ancestorFacts = hierarchyFacts;
88208             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & 16383 /* AncestorFactsMask */;
88209             return ancestorFacts;
88210         }
88211         /**
88212          * Restores the `HierarchyFacts` for this node's ancestor after visiting this node's
88213          * subtree, propagating specific facts from the subtree.
88214          * @param ancestorFacts The `HierarchyFacts` of the ancestor to restore after visiting the subtree.
88215          * @param excludeFacts The existing `HierarchyFacts` of the subtree that should not be propagated.
88216          * @param includeFacts The new `HierarchyFacts` of the subtree that should be propagated.
88217          */
88218         function exitSubtree(ancestorFacts, excludeFacts, includeFacts) {
88219             hierarchyFacts = (hierarchyFacts & ~excludeFacts | includeFacts) & -16384 /* SubtreeFactsMask */ | ancestorFacts;
88220         }
88221         function isReturnVoidStatementInConstructorWithCapturedSuper(node) {
88222             return (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */) !== 0
88223                 && node.kind === 242 /* ReturnStatement */
88224                 && !node.expression;
88225         }
88226         function isOrMayContainReturnCompletion(node) {
88227             return node.transformFlags & 1048576 /* ContainsHoistedDeclarationOrCompletion */
88228                 && (ts.isReturnStatement(node)
88229                     || ts.isIfStatement(node)
88230                     || ts.isWithStatement(node)
88231                     || ts.isSwitchStatement(node)
88232                     || ts.isCaseBlock(node)
88233                     || ts.isCaseClause(node)
88234                     || ts.isDefaultClause(node)
88235                     || ts.isTryStatement(node)
88236                     || ts.isCatchClause(node)
88237                     || ts.isLabeledStatement(node)
88238                     || ts.isIterationStatement(node, /*lookInLabeledStatements*/ false)
88239                     || ts.isBlock(node));
88240         }
88241         function shouldVisitNode(node) {
88242             return (node.transformFlags & 256 /* ContainsES2015 */) !== 0
88243                 || convertedLoopState !== undefined
88244                 || (hierarchyFacts & 8192 /* ConstructorWithCapturedSuper */ && isOrMayContainReturnCompletion(node))
88245                 || (ts.isIterationStatement(node, /*lookInLabeledStatements*/ false) && shouldConvertIterationStatement(node))
88246                 || (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) !== 0;
88247         }
88248         function visitor(node) {
88249             return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ false) : node;
88250         }
88251         function visitorWithUnusedExpressionResult(node) {
88252             return shouldVisitNode(node) ? visitorWorker(node, /*expressionResultIsUnused*/ true) : node;
88253         }
88254         function callExpressionVisitor(node) {
88255             if (node.kind === 105 /* SuperKeyword */) {
88256                 return visitSuperKeyword(/*isExpressionOfCall*/ true);
88257             }
88258             return visitor(node);
88259         }
88260         function visitorWorker(node, expressionResultIsUnused) {
88261             switch (node.kind) {
88262                 case 123 /* StaticKeyword */:
88263                     return undefined; // elide static keyword
88264                 case 252 /* ClassDeclaration */:
88265                     return visitClassDeclaration(node);
88266                 case 221 /* ClassExpression */:
88267                     return visitClassExpression(node);
88268                 case 160 /* Parameter */:
88269                     return visitParameter(node);
88270                 case 251 /* FunctionDeclaration */:
88271                     return visitFunctionDeclaration(node);
88272                 case 209 /* ArrowFunction */:
88273                     return visitArrowFunction(node);
88274                 case 208 /* FunctionExpression */:
88275                     return visitFunctionExpression(node);
88276                 case 249 /* VariableDeclaration */:
88277                     return visitVariableDeclaration(node);
88278                 case 78 /* Identifier */:
88279                     return visitIdentifier(node);
88280                 case 250 /* VariableDeclarationList */:
88281                     return visitVariableDeclarationList(node);
88282                 case 244 /* SwitchStatement */:
88283                     return visitSwitchStatement(node);
88284                 case 258 /* CaseBlock */:
88285                     return visitCaseBlock(node);
88286                 case 230 /* Block */:
88287                     return visitBlock(node, /*isFunctionBody*/ false);
88288                 case 241 /* BreakStatement */:
88289                 case 240 /* ContinueStatement */:
88290                     return visitBreakOrContinueStatement(node);
88291                 case 245 /* LabeledStatement */:
88292                     return visitLabeledStatement(node);
88293                 case 235 /* DoStatement */:
88294                 case 236 /* WhileStatement */:
88295                     return visitDoOrWhileStatement(node, /*outermostLabeledStatement*/ undefined);
88296                 case 237 /* ForStatement */:
88297                     return visitForStatement(node, /*outermostLabeledStatement*/ undefined);
88298                 case 238 /* ForInStatement */:
88299                     return visitForInStatement(node, /*outermostLabeledStatement*/ undefined);
88300                 case 239 /* ForOfStatement */:
88301                     return visitForOfStatement(node, /*outermostLabeledStatement*/ undefined);
88302                 case 233 /* ExpressionStatement */:
88303                     return visitExpressionStatement(node);
88304                 case 200 /* ObjectLiteralExpression */:
88305                     return visitObjectLiteralExpression(node);
88306                 case 287 /* CatchClause */:
88307                     return visitCatchClause(node);
88308                 case 289 /* ShorthandPropertyAssignment */:
88309                     return visitShorthandPropertyAssignment(node);
88310                 case 158 /* ComputedPropertyName */:
88311                     return visitComputedPropertyName(node);
88312                 case 199 /* ArrayLiteralExpression */:
88313                     return visitArrayLiteralExpression(node);
88314                 case 203 /* CallExpression */:
88315                     return visitCallExpression(node);
88316                 case 204 /* NewExpression */:
88317                     return visitNewExpression(node);
88318                 case 207 /* ParenthesizedExpression */:
88319                     return visitParenthesizedExpression(node, expressionResultIsUnused);
88320                 case 216 /* BinaryExpression */:
88321                     return visitBinaryExpression(node, expressionResultIsUnused);
88322                 case 337 /* CommaListExpression */:
88323                     return visitCommaListExpression(node, expressionResultIsUnused);
88324                 case 14 /* NoSubstitutionTemplateLiteral */:
88325                 case 15 /* TemplateHead */:
88326                 case 16 /* TemplateMiddle */:
88327                 case 17 /* TemplateTail */:
88328                     return visitTemplateLiteral(node);
88329                 case 10 /* StringLiteral */:
88330                     return visitStringLiteral(node);
88331                 case 8 /* NumericLiteral */:
88332                     return visitNumericLiteral(node);
88333                 case 205 /* TaggedTemplateExpression */:
88334                     return visitTaggedTemplateExpression(node);
88335                 case 218 /* TemplateExpression */:
88336                     return visitTemplateExpression(node);
88337                 case 219 /* YieldExpression */:
88338                     return visitYieldExpression(node);
88339                 case 220 /* SpreadElement */:
88340                     return visitSpreadElement(node);
88341                 case 105 /* SuperKeyword */:
88342                     return visitSuperKeyword(/*isExpressionOfCall*/ false);
88343                 case 107 /* ThisKeyword */:
88344                     return visitThisKeyword(node);
88345                 case 226 /* MetaProperty */:
88346                     return visitMetaProperty(node);
88347                 case 165 /* MethodDeclaration */:
88348                     return visitMethodDeclaration(node);
88349                 case 167 /* GetAccessor */:
88350                 case 168 /* SetAccessor */:
88351                     return visitAccessorDeclaration(node);
88352                 case 232 /* VariableStatement */:
88353                     return visitVariableStatement(node);
88354                 case 242 /* ReturnStatement */:
88355                     return visitReturnStatement(node);
88356                 case 212 /* VoidExpression */:
88357                     return visitVoidExpression(node);
88358                 default:
88359                     return ts.visitEachChild(node, visitor, context);
88360             }
88361         }
88362         function visitSourceFile(node) {
88363             var ancestorFacts = enterSubtree(8064 /* SourceFileExcludes */, 64 /* SourceFileIncludes */);
88364             var prologue = [];
88365             var statements = [];
88366             startLexicalEnvironment();
88367             var statementOffset = factory.copyPrologue(node.statements, prologue, /*ensureUseStrict*/ false, visitor);
88368             ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
88369             if (taggedTemplateStringDeclarations) {
88370                 statements.push(factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList(taggedTemplateStringDeclarations)));
88371             }
88372             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
88373             insertCaptureThisForNodeIfNeeded(prologue, node);
88374             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
88375             return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), node.statements));
88376         }
88377         function visitSwitchStatement(node) {
88378             if (convertedLoopState !== undefined) {
88379                 var savedAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
88380                 // for switch statement allow only non-labeled break
88381                 convertedLoopState.allowedNonLabeledJumps |= 2 /* Break */;
88382                 var result = ts.visitEachChild(node, visitor, context);
88383                 convertedLoopState.allowedNonLabeledJumps = savedAllowedNonLabeledJumps;
88384                 return result;
88385             }
88386             return ts.visitEachChild(node, visitor, context);
88387         }
88388         function visitCaseBlock(node) {
88389             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
88390             var updated = ts.visitEachChild(node, visitor, context);
88391             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
88392             return updated;
88393         }
88394         function returnCapturedThis(node) {
88395             return ts.setOriginalNode(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)), node);
88396         }
88397         function visitReturnStatement(node) {
88398             if (convertedLoopState) {
88399                 convertedLoopState.nonLocalJumps |= 8 /* Return */;
88400                 if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
88401                     node = returnCapturedThis(node);
88402                 }
88403                 return factory.createReturnStatement(factory.createObjectLiteralExpression([
88404                     factory.createPropertyAssignment(factory.createIdentifier("value"), node.expression
88405                         ? ts.visitNode(node.expression, visitor, ts.isExpression)
88406                         : factory.createVoidZero())
88407                 ]));
88408             }
88409             else if (isReturnVoidStatementInConstructorWithCapturedSuper(node)) {
88410                 return returnCapturedThis(node);
88411             }
88412             return ts.visitEachChild(node, visitor, context);
88413         }
88414         function visitThisKeyword(node) {
88415             if (hierarchyFacts & 2 /* ArrowFunction */) {
88416                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
88417             }
88418             if (convertedLoopState) {
88419                 if (hierarchyFacts & 2 /* ArrowFunction */) {
88420                     // if the enclosing function is an ArrowFunction then we use the captured 'this' keyword.
88421                     convertedLoopState.containsLexicalThis = true;
88422                     return node;
88423                 }
88424                 return convertedLoopState.thisName || (convertedLoopState.thisName = factory.createUniqueName("this"));
88425             }
88426             return node;
88427         }
88428         function visitVoidExpression(node) {
88429             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
88430         }
88431         function visitIdentifier(node) {
88432             if (!convertedLoopState) {
88433                 return node;
88434             }
88435             if (resolver.isArgumentsLocalBinding(node)) {
88436                 return convertedLoopState.argumentsName || (convertedLoopState.argumentsName = factory.createUniqueName("arguments"));
88437             }
88438             return node;
88439         }
88440         function visitBreakOrContinueStatement(node) {
88441             if (convertedLoopState) {
88442                 // check if we can emit break/continue as is
88443                 // it is possible if either
88444                 //   - break/continue is labeled and label is located inside the converted loop
88445                 //   - break/continue is non-labeled and located in non-converted loop/switch statement
88446                 var jump = node.kind === 241 /* BreakStatement */ ? 2 /* Break */ : 4 /* Continue */;
88447                 var canUseBreakOrContinue = (node.label && convertedLoopState.labels && convertedLoopState.labels.get(ts.idText(node.label))) ||
88448                     (!node.label && (convertedLoopState.allowedNonLabeledJumps & jump));
88449                 if (!canUseBreakOrContinue) {
88450                     var labelMarker = void 0;
88451                     var label = node.label;
88452                     if (!label) {
88453                         if (node.kind === 241 /* BreakStatement */) {
88454                             convertedLoopState.nonLocalJumps |= 2 /* Break */;
88455                             labelMarker = "break";
88456                         }
88457                         else {
88458                             convertedLoopState.nonLocalJumps |= 4 /* Continue */;
88459                             // note: return value is emitted only to simplify debugging, call to converted loop body does not do any dispatching on it.
88460                             labelMarker = "continue";
88461                         }
88462                     }
88463                     else {
88464                         if (node.kind === 241 /* BreakStatement */) {
88465                             labelMarker = "break-" + label.escapedText;
88466                             setLabeledJump(convertedLoopState, /*isBreak*/ true, ts.idText(label), labelMarker);
88467                         }
88468                         else {
88469                             labelMarker = "continue-" + label.escapedText;
88470                             setLabeledJump(convertedLoopState, /*isBreak*/ false, ts.idText(label), labelMarker);
88471                         }
88472                     }
88473                     var returnExpression = factory.createStringLiteral(labelMarker);
88474                     if (convertedLoopState.loopOutParameters.length) {
88475                         var outParams = convertedLoopState.loopOutParameters;
88476                         var expr = void 0;
88477                         for (var i = 0; i < outParams.length; i++) {
88478                             var copyExpr = copyOutParameter(outParams[i], 1 /* ToOutParameter */);
88479                             if (i === 0) {
88480                                 expr = copyExpr;
88481                             }
88482                             else {
88483                                 expr = factory.createBinaryExpression(expr, 27 /* CommaToken */, copyExpr);
88484                             }
88485                         }
88486                         returnExpression = factory.createBinaryExpression(expr, 27 /* CommaToken */, returnExpression);
88487                     }
88488                     return factory.createReturnStatement(returnExpression);
88489                 }
88490             }
88491             return ts.visitEachChild(node, visitor, context);
88492         }
88493         /**
88494          * Visits a ClassDeclaration and transforms it into a variable statement.
88495          *
88496          * @param node A ClassDeclaration node.
88497          */
88498         function visitClassDeclaration(node) {
88499             // [source]
88500             //      class C { }
88501             //
88502             // [output]
88503             //      var C = (function () {
88504             //          function C() {
88505             //          }
88506             //          return C;
88507             //      }());
88508             var variable = factory.createVariableDeclaration(factory.getLocalName(node, /*allowComments*/ true), 
88509             /*exclamationToken*/ undefined, 
88510             /*type*/ undefined, transformClassLikeDeclarationToExpression(node));
88511             ts.setOriginalNode(variable, node);
88512             var statements = [];
88513             var statement = factory.createVariableStatement(/*modifiers*/ undefined, factory.createVariableDeclarationList([variable]));
88514             ts.setOriginalNode(statement, node);
88515             ts.setTextRange(statement, node);
88516             ts.startOnNewLine(statement);
88517             statements.push(statement);
88518             // Add an `export default` statement for default exports (for `--target es5 --module es6`)
88519             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
88520                 var exportStatement = ts.hasSyntacticModifier(node, 512 /* Default */)
88521                     ? factory.createExportDefault(factory.getLocalName(node))
88522                     : factory.createExternalModuleExport(factory.getLocalName(node));
88523                 ts.setOriginalNode(exportStatement, statement);
88524                 statements.push(exportStatement);
88525             }
88526             var emitFlags = ts.getEmitFlags(node);
88527             if ((emitFlags & 4194304 /* HasEndOfDeclarationMarker */) === 0) {
88528                 // Add a DeclarationMarker as a marker for the end of the declaration
88529                 statements.push(factory.createEndOfDeclarationMarker(node));
88530                 ts.setEmitFlags(statement, emitFlags | 4194304 /* HasEndOfDeclarationMarker */);
88531             }
88532             return ts.singleOrMany(statements);
88533         }
88534         /**
88535          * Visits a ClassExpression and transforms it into an expression.
88536          *
88537          * @param node A ClassExpression node.
88538          */
88539         function visitClassExpression(node) {
88540             // [source]
88541             //      C = class { }
88542             //
88543             // [output]
88544             //      C = (function () {
88545             //          function class_1() {
88546             //          }
88547             //          return class_1;
88548             //      }())
88549             return transformClassLikeDeclarationToExpression(node);
88550         }
88551         /**
88552          * Transforms a ClassExpression or ClassDeclaration into an expression.
88553          *
88554          * @param node A ClassExpression or ClassDeclaration node.
88555          */
88556         function transformClassLikeDeclarationToExpression(node) {
88557             // [source]
88558             //      class C extends D {
88559             //          constructor() {}
88560             //          method() {}
88561             //          get prop() {}
88562             //          set prop(v) {}
88563             //      }
88564             //
88565             // [output]
88566             //      (function (_super) {
88567             //          __extends(C, _super);
88568             //          function C() {
88569             //          }
88570             //          C.prototype.method = function () {}
88571             //          Object.defineProperty(C.prototype, "prop", {
88572             //              get: function() {},
88573             //              set: function() {},
88574             //              enumerable: true,
88575             //              configurable: true
88576             //          });
88577             //          return C;
88578             //      }(D))
88579             if (node.name) {
88580                 enableSubstitutionsForBlockScopedBindings();
88581             }
88582             var extendsClauseElement = ts.getClassExtendsHeritageElement(node);
88583             var classFunction = factory.createFunctionExpression(
88584             /*modifiers*/ undefined, 
88585             /*asteriskToken*/ undefined, 
88586             /*name*/ undefined, 
88587             /*typeParameters*/ undefined, extendsClauseElement ? [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */))] : [], 
88588             /*type*/ undefined, transformClassBody(node, extendsClauseElement));
88589             // To preserve the behavior of the old emitter, we explicitly indent
88590             // the body of the function here if it was requested in an earlier
88591             // transformation.
88592             ts.setEmitFlags(classFunction, (ts.getEmitFlags(node) & 65536 /* Indented */) | 524288 /* ReuseTempVariableScope */);
88593             // "inner" and "outer" below are added purely to preserve source map locations from
88594             // the old emitter
88595             var inner = factory.createPartiallyEmittedExpression(classFunction);
88596             ts.setTextRangeEnd(inner, node.end);
88597             ts.setEmitFlags(inner, 1536 /* NoComments */);
88598             var outer = factory.createPartiallyEmittedExpression(inner);
88599             ts.setTextRangeEnd(outer, ts.skipTrivia(currentText, node.pos));
88600             ts.setEmitFlags(outer, 1536 /* NoComments */);
88601             var result = factory.createParenthesizedExpression(factory.createCallExpression(outer, 
88602             /*typeArguments*/ undefined, extendsClauseElement
88603                 ? [ts.visitNode(extendsClauseElement.expression, visitor, ts.isExpression)]
88604                 : []));
88605             ts.addSyntheticLeadingComment(result, 3 /* MultiLineCommentTrivia */, "* @class ");
88606             return result;
88607         }
88608         /**
88609          * Transforms a ClassExpression or ClassDeclaration into a function body.
88610          *
88611          * @param node A ClassExpression or ClassDeclaration node.
88612          * @param extendsClauseElement The expression for the class `extends` clause.
88613          */
88614         function transformClassBody(node, extendsClauseElement) {
88615             var statements = [];
88616             var name = factory.getInternalName(node);
88617             var constructorLikeName = ts.isIdentifierANonContextualKeyword(name) ? factory.getGeneratedNameForNode(name) : name;
88618             startLexicalEnvironment();
88619             addExtendsHelperIfNeeded(statements, node, extendsClauseElement);
88620             addConstructor(statements, node, constructorLikeName, extendsClauseElement);
88621             addClassMembers(statements, node);
88622             // Create a synthetic text range for the return statement.
88623             var closingBraceLocation = ts.createTokenRange(ts.skipTrivia(currentText, node.members.end), 19 /* CloseBraceToken */);
88624             // The following partially-emitted expression exists purely to align our sourcemap
88625             // emit with the original emitter.
88626             var outer = factory.createPartiallyEmittedExpression(constructorLikeName);
88627             ts.setTextRangeEnd(outer, closingBraceLocation.end);
88628             ts.setEmitFlags(outer, 1536 /* NoComments */);
88629             var statement = factory.createReturnStatement(outer);
88630             ts.setTextRangePos(statement, closingBraceLocation.pos);
88631             ts.setEmitFlags(statement, 1536 /* NoComments */ | 384 /* NoTokenSourceMaps */);
88632             statements.push(statement);
88633             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
88634             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), /*location*/ node.members), /*multiLine*/ true);
88635             ts.setEmitFlags(block, 1536 /* NoComments */);
88636             return block;
88637         }
88638         /**
88639          * Adds a call to the `__extends` helper if needed for a class.
88640          *
88641          * @param statements The statements of the class body function.
88642          * @param node The ClassExpression or ClassDeclaration node.
88643          * @param extendsClauseElement The expression for the class `extends` clause.
88644          */
88645         function addExtendsHelperIfNeeded(statements, node, extendsClauseElement) {
88646             if (extendsClauseElement) {
88647                 statements.push(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExtendsHelper(factory.getInternalName(node))), 
88648                 /*location*/ extendsClauseElement));
88649             }
88650         }
88651         /**
88652          * Adds the constructor of the class to a class body function.
88653          *
88654          * @param statements The statements of the class body function.
88655          * @param node The ClassExpression or ClassDeclaration node.
88656          * @param extendsClauseElement The expression for the class `extends` clause.
88657          */
88658         function addConstructor(statements, node, name, extendsClauseElement) {
88659             var savedConvertedLoopState = convertedLoopState;
88660             convertedLoopState = undefined;
88661             var ancestorFacts = enterSubtree(16278 /* ConstructorExcludes */, 73 /* ConstructorIncludes */);
88662             var constructor = ts.getFirstConstructorWithBody(node);
88663             var hasSynthesizedSuper = hasSynthesizedDefaultSuperCall(constructor, extendsClauseElement !== undefined);
88664             var constructorFunction = factory.createFunctionDeclaration(
88665             /*decorators*/ undefined, 
88666             /*modifiers*/ undefined, 
88667             /*asteriskToken*/ undefined, name, 
88668             /*typeParameters*/ undefined, transformConstructorParameters(constructor, hasSynthesizedSuper), 
88669             /*type*/ undefined, transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper));
88670             ts.setTextRange(constructorFunction, constructor || node);
88671             if (extendsClauseElement) {
88672                 ts.setEmitFlags(constructorFunction, 8 /* CapturesThis */);
88673             }
88674             statements.push(constructorFunction);
88675             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
88676             convertedLoopState = savedConvertedLoopState;
88677         }
88678         /**
88679          * Transforms the parameters of the constructor declaration of a class.
88680          *
88681          * @param constructor The constructor for the class.
88682          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
88683          *                            synthesized `super` call.
88684          */
88685         function transformConstructorParameters(constructor, hasSynthesizedSuper) {
88686             // If the TypeScript transformer needed to synthesize a constructor for property
88687             // initializers, it would have also added a synthetic `...args` parameter and
88688             // `super` call.
88689             // If this is the case, we do not include the synthetic `...args` parameter and
88690             // will instead use the `arguments` object in ES5/3.
88691             return ts.visitParameterList(constructor && !hasSynthesizedSuper ? constructor.parameters : undefined, visitor, context)
88692                 || [];
88693         }
88694         function createDefaultConstructorBody(node, isDerivedClass) {
88695             // We must be here because the user didn't write a constructor
88696             // but we needed to call 'super(...args)' anyway as per 14.5.14 of the ES2016 spec.
88697             // If that's the case we can just immediately return the result of a 'super()' call.
88698             var statements = [];
88699             resumeLexicalEnvironment();
88700             factory.mergeLexicalEnvironment(statements, endLexicalEnvironment());
88701             if (isDerivedClass) {
88702                 // return _super !== null && _super.apply(this, arguments) || this;
88703                 statements.push(factory.createReturnStatement(createDefaultSuperCallOrThis()));
88704             }
88705             var statementsArray = factory.createNodeArray(statements);
88706             ts.setTextRange(statementsArray, node.members);
88707             var block = factory.createBlock(statementsArray, /*multiLine*/ true);
88708             ts.setTextRange(block, node);
88709             ts.setEmitFlags(block, 1536 /* NoComments */);
88710             return block;
88711         }
88712         /**
88713          * Transforms the body of a constructor declaration of a class.
88714          *
88715          * @param constructor The constructor for the class.
88716          * @param node The node which contains the constructor.
88717          * @param extendsClauseElement The expression for the class `extends` clause.
88718          * @param hasSynthesizedSuper A value indicating whether the constructor starts with a
88719          *                            synthesized `super` call.
88720          */
88721         function transformConstructorBody(constructor, node, extendsClauseElement, hasSynthesizedSuper) {
88722             // determine whether the class is known syntactically to be a derived class (e.g. a
88723             // class that extends a value that is not syntactically known to be `null`).
88724             var isDerivedClass = !!extendsClauseElement && ts.skipOuterExpressions(extendsClauseElement.expression).kind !== 103 /* NullKeyword */;
88725             // When the subclass does not have a constructor, we synthesize a *default* constructor using the following
88726             // representation:
88727             //
88728             // ```
88729             // // es2015 (source)
88730             // class C extends Base { }
88731             //
88732             // // es5 (transformed)
88733             // var C = (function (_super) {
88734             //     function C() {
88735             //         return _super.apply(this, arguments) || this;
88736             //     }
88737             //     return C;
88738             // })(Base);
88739             // ```
88740             if (!constructor)
88741                 return createDefaultConstructorBody(node, isDerivedClass);
88742             // The prologue will contain all leading standard and custom prologue statements added by this transform
88743             var prologue = [];
88744             var statements = [];
88745             resumeLexicalEnvironment();
88746             // If a super call has already been synthesized,
88747             // we're going to assume that we should just transform everything after that.
88748             // The assumption is that no prior step in the pipeline has added any prologue directives.
88749             var statementOffset = 0;
88750             if (!hasSynthesizedSuper)
88751                 statementOffset = factory.copyStandardPrologue(constructor.body.statements, prologue, /*ensureUseStrict*/ false);
88752             addDefaultValueAssignmentsIfNeeded(statements, constructor);
88753             addRestParameterIfNeeded(statements, constructor, hasSynthesizedSuper);
88754             if (!hasSynthesizedSuper)
88755                 statementOffset = factory.copyCustomPrologue(constructor.body.statements, statements, statementOffset, visitor);
88756             // If the first statement is a call to `super()`, visit the statement directly
88757             var superCallExpression;
88758             if (hasSynthesizedSuper) {
88759                 superCallExpression = createDefaultSuperCallOrThis();
88760             }
88761             else if (isDerivedClass && statementOffset < constructor.body.statements.length) {
88762                 var firstStatement = constructor.body.statements[statementOffset];
88763                 if (ts.isExpressionStatement(firstStatement) && ts.isSuperCall(firstStatement.expression)) {
88764                     superCallExpression = visitImmediateSuperCallInBody(firstStatement.expression);
88765                 }
88766             }
88767             if (superCallExpression) {
88768                 hierarchyFacts |= 8192 /* ConstructorWithCapturedSuper */;
88769                 statementOffset++; // skip this statement, we will add it after visiting the rest of the body.
88770             }
88771             // visit the remaining statements
88772             ts.addRange(statements, ts.visitNodes(constructor.body.statements, visitor, ts.isStatement, /*start*/ statementOffset));
88773             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
88774             insertCaptureNewTargetIfNeeded(prologue, constructor, /*copyOnWrite*/ false);
88775             if (isDerivedClass) {
88776                 if (superCallExpression && statementOffset === constructor.body.statements.length && !(constructor.body.transformFlags & 4096 /* ContainsLexicalThis */)) {
88777                     // If the subclass constructor does *not* contain `this` and *ends* with a `super()` call, we will use the
88778                     // following representation:
88779                     //
88780                     // ```
88781                     // // es2015 (source)
88782                     // class C extends Base {
88783                     //     constructor() {
88784                     //         super("foo");
88785                     //     }
88786                     // }
88787                     //
88788                     // // es5 (transformed)
88789                     // var C = (function (_super) {
88790                     //     function C() {
88791                     //         return _super.call(this, "foo") || this;
88792                     //     }
88793                     //     return C;
88794                     // })(Base);
88795                     // ```
88796                     var superCall = ts.cast(ts.cast(superCallExpression, ts.isBinaryExpression).left, ts.isCallExpression);
88797                     var returnStatement = factory.createReturnStatement(superCallExpression);
88798                     ts.setCommentRange(returnStatement, ts.getCommentRange(superCall));
88799                     ts.setEmitFlags(superCall, 1536 /* NoComments */);
88800                     statements.push(returnStatement);
88801                 }
88802                 else {
88803                     // Otherwise, we will use the following transformed representation for calls to `super()` in a constructor:
88804                     //
88805                     // ```
88806                     // // es2015 (source)
88807                     // class C extends Base {
88808                     //     constructor() {
88809                     //         super("foo");
88810                     //         this.x = 1;
88811                     //     }
88812                     // }
88813                     //
88814                     // // es5 (transformed)
88815                     // var C = (function (_super) {
88816                     //     function C() {
88817                     //         var _this = _super.call(this, "foo") || this;
88818                     //         _this.x = 1;
88819                     //         return _this;
88820                     //     }
88821                     //     return C;
88822                     // })(Base);
88823                     // ```
88824                     // Since the `super()` call was the first statement, we insert the `this` capturing call to
88825                     // `super()` at the top of the list of `statements` (after any pre-existing custom prologues).
88826                     insertCaptureThisForNode(statements, constructor, superCallExpression || createActualThis());
88827                     if (!isSufficientlyCoveredByReturnStatements(constructor.body)) {
88828                         statements.push(factory.createReturnStatement(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */)));
88829                     }
88830                 }
88831             }
88832             else {
88833                 // If a class is not derived from a base class or does not have a call to `super()`, `this` is only
88834                 // captured when necessitated by an arrow function capturing the lexical `this`:
88835                 //
88836                 // ```
88837                 // // es2015
88838                 // class C {}
88839                 //
88840                 // // es5
88841                 // var C = (function () {
88842                 //     function C() {
88843                 //     }
88844                 //     return C;
88845                 // })();
88846                 // ```
88847                 insertCaptureThisForNodeIfNeeded(prologue, constructor);
88848             }
88849             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(ts.concatenate(prologue, statements)), 
88850             /*location*/ constructor.body.statements), 
88851             /*multiLine*/ true);
88852             ts.setTextRange(block, constructor.body);
88853             return block;
88854         }
88855         /**
88856          * We want to try to avoid emitting a return statement in certain cases if a user already returned something.
88857          * It would generate obviously dead code, so we'll try to make things a little bit prettier
88858          * by doing a minimal check on whether some common patterns always explicitly return.
88859          */
88860         function isSufficientlyCoveredByReturnStatements(statement) {
88861             // A return statement is considered covered.
88862             if (statement.kind === 242 /* ReturnStatement */) {
88863                 return true;
88864             }
88865             // An if-statement with two covered branches is covered.
88866             else if (statement.kind === 234 /* IfStatement */) {
88867                 var ifStatement = statement;
88868                 if (ifStatement.elseStatement) {
88869                     return isSufficientlyCoveredByReturnStatements(ifStatement.thenStatement) &&
88870                         isSufficientlyCoveredByReturnStatements(ifStatement.elseStatement);
88871                 }
88872             }
88873             // A block is covered if it has a last statement which is covered.
88874             else if (statement.kind === 230 /* Block */) {
88875                 var lastStatement = ts.lastOrUndefined(statement.statements);
88876                 if (lastStatement && isSufficientlyCoveredByReturnStatements(lastStatement)) {
88877                     return true;
88878                 }
88879             }
88880             return false;
88881         }
88882         function createActualThis() {
88883             return ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */);
88884         }
88885         function createDefaultSuperCallOrThis() {
88886             return factory.createLogicalOr(factory.createLogicalAnd(factory.createStrictInequality(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), factory.createNull()), factory.createFunctionApplyCall(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), createActualThis(), factory.createIdentifier("arguments"))), createActualThis());
88887         }
88888         /**
88889          * Visits a parameter declaration.
88890          *
88891          * @param node A ParameterDeclaration node.
88892          */
88893         function visitParameter(node) {
88894             if (node.dotDotDotToken) {
88895                 // rest parameters are elided
88896                 return undefined;
88897             }
88898             else if (ts.isBindingPattern(node.name)) {
88899                 // Binding patterns are converted into a generated name and are
88900                 // evaluated inside the function body.
88901                 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
88902                 /*decorators*/ undefined, 
88903                 /*modifiers*/ undefined, 
88904                 /*dotDotDotToken*/ undefined, factory.getGeneratedNameForNode(node), 
88905                 /*questionToken*/ undefined, 
88906                 /*type*/ undefined, 
88907                 /*initializer*/ undefined), 
88908                 /*location*/ node), 
88909                 /*original*/ node);
88910             }
88911             else if (node.initializer) {
88912                 // Initializers are elided
88913                 return ts.setOriginalNode(ts.setTextRange(factory.createParameterDeclaration(
88914                 /*decorators*/ undefined, 
88915                 /*modifiers*/ undefined, 
88916                 /*dotDotDotToken*/ undefined, node.name, 
88917                 /*questionToken*/ undefined, 
88918                 /*type*/ undefined, 
88919                 /*initializer*/ undefined), 
88920                 /*location*/ node), 
88921                 /*original*/ node);
88922             }
88923             else {
88924                 return node;
88925             }
88926         }
88927         function hasDefaultValueOrBindingPattern(node) {
88928             return node.initializer !== undefined
88929                 || ts.isBindingPattern(node.name);
88930         }
88931         /**
88932          * Adds statements to the body of a function-like node if it contains parameters with
88933          * binding patterns or initializers.
88934          *
88935          * @param statements The statements for the new function body.
88936          * @param node A function-like node.
88937          */
88938         function addDefaultValueAssignmentsIfNeeded(statements, node) {
88939             if (!ts.some(node.parameters, hasDefaultValueOrBindingPattern)) {
88940                 return false;
88941             }
88942             var added = false;
88943             for (var _i = 0, _a = node.parameters; _i < _a.length; _i++) {
88944                 var parameter = _a[_i];
88945                 var name = parameter.name, initializer = parameter.initializer, dotDotDotToken = parameter.dotDotDotToken;
88946                 // A rest parameter cannot have a binding pattern or an initializer,
88947                 // so let's just ignore it.
88948                 if (dotDotDotToken) {
88949                     continue;
88950                 }
88951                 if (ts.isBindingPattern(name)) {
88952                     added = insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) || added;
88953                 }
88954                 else if (initializer) {
88955                     insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer);
88956                     added = true;
88957                 }
88958             }
88959             return added;
88960         }
88961         /**
88962          * Adds statements to the body of a function-like node for parameters with binding patterns
88963          *
88964          * @param statements The statements for the new function body.
88965          * @param parameter The parameter for the function.
88966          * @param name The name of the parameter.
88967          * @param initializer The initializer for the parameter.
88968          */
88969         function insertDefaultValueAssignmentForBindingPattern(statements, parameter, name, initializer) {
88970             // In cases where a binding pattern is simply '[]' or '{}',
88971             // we usually don't want to emit a var declaration; however, in the presence
88972             // of an initializer, we must emit that expression to preserve side effects.
88973             if (name.elements.length > 0) {
88974                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createVariableStatement(
88975                 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, factory.getGeneratedNameForNode(parameter)))), 1048576 /* CustomPrologue */));
88976                 return true;
88977             }
88978             else if (initializer) {
88979                 ts.insertStatementAfterCustomPrologue(statements, ts.setEmitFlags(factory.createExpressionStatement(factory.createAssignment(factory.getGeneratedNameForNode(parameter), ts.visitNode(initializer, visitor, ts.isExpression))), 1048576 /* CustomPrologue */));
88980                 return true;
88981             }
88982             return false;
88983         }
88984         /**
88985          * Adds statements to the body of a function-like node for parameters with initializers.
88986          *
88987          * @param statements The statements for the new function body.
88988          * @param parameter The parameter for the function.
88989          * @param name The name of the parameter.
88990          * @param initializer The initializer for the parameter.
88991          */
88992         function insertDefaultValueAssignmentForInitializer(statements, parameter, name, initializer) {
88993             initializer = ts.visitNode(initializer, visitor, ts.isExpression);
88994             var statement = factory.createIfStatement(factory.createTypeCheck(factory.cloneNode(name), "undefined"), ts.setEmitFlags(ts.setTextRange(factory.createBlock([
88995                 factory.createExpressionStatement(ts.setEmitFlags(ts.setTextRange(factory.createAssignment(
88996                 // TODO(rbuckton): Does this need to be parented?
88997                 ts.setEmitFlags(ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent), 48 /* NoSourceMap */), ts.setEmitFlags(initializer, 48 /* NoSourceMap */ | ts.getEmitFlags(initializer) | 1536 /* NoComments */)), parameter), 1536 /* NoComments */))
88998             ]), parameter), 1 /* SingleLine */ | 32 /* NoTrailingSourceMap */ | 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */));
88999             ts.startOnNewLine(statement);
89000             ts.setTextRange(statement, parameter);
89001             ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1048576 /* CustomPrologue */ | 1536 /* NoComments */);
89002             ts.insertStatementAfterCustomPrologue(statements, statement);
89003         }
89004         /**
89005          * Gets a value indicating whether we need to add statements to handle a rest parameter.
89006          *
89007          * @param node A ParameterDeclaration node.
89008          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
89009          *                                          part of a constructor declaration with a
89010          *                                          synthesized call to `super`
89011          */
89012         function shouldAddRestParameter(node, inConstructorWithSynthesizedSuper) {
89013             return !!(node && node.dotDotDotToken && !inConstructorWithSynthesizedSuper);
89014         }
89015         /**
89016          * Adds statements to the body of a function-like node if it contains a rest parameter.
89017          *
89018          * @param statements The statements for the new function body.
89019          * @param node A function-like node.
89020          * @param inConstructorWithSynthesizedSuper A value indicating whether the parameter is
89021          *                                          part of a constructor declaration with a
89022          *                                          synthesized call to `super`
89023          */
89024         function addRestParameterIfNeeded(statements, node, inConstructorWithSynthesizedSuper) {
89025             var prologueStatements = [];
89026             var parameter = ts.lastOrUndefined(node.parameters);
89027             if (!shouldAddRestParameter(parameter, inConstructorWithSynthesizedSuper)) {
89028                 return false;
89029             }
89030             // `declarationName` is the name of the local declaration for the parameter.
89031             // TODO(rbuckton): Does this need to be parented?
89032             var declarationName = parameter.name.kind === 78 /* Identifier */ ? ts.setParent(ts.setTextRange(factory.cloneNode(parameter.name), parameter.name), parameter.name.parent) : factory.createTempVariable(/*recordTempVariable*/ undefined);
89033             ts.setEmitFlags(declarationName, 48 /* NoSourceMap */);
89034             // `expressionName` is the name of the parameter used in expressions.
89035             var expressionName = parameter.name.kind === 78 /* Identifier */ ? factory.cloneNode(parameter.name) : declarationName;
89036             var restIndex = node.parameters.length - 1;
89037             var temp = factory.createLoopVariable();
89038             // var param = [];
89039             prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
89040             /*modifiers*/ undefined, factory.createVariableDeclarationList([
89041                 factory.createVariableDeclaration(declarationName, 
89042                 /*exclamationToken*/ undefined, 
89043                 /*type*/ undefined, factory.createArrayLiteralExpression([]))
89044             ])), 
89045             /*location*/ parameter), 1048576 /* CustomPrologue */));
89046             // for (var _i = restIndex; _i < arguments.length; _i++) {
89047             //   param[_i - restIndex] = arguments[_i];
89048             // }
89049             var forStatement = factory.createForStatement(ts.setTextRange(factory.createVariableDeclarationList([
89050                 factory.createVariableDeclaration(temp, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(restIndex))
89051             ]), parameter), ts.setTextRange(factory.createLessThan(temp, factory.createPropertyAccessExpression(factory.createIdentifier("arguments"), "length")), parameter), ts.setTextRange(factory.createPostfixIncrement(temp), parameter), factory.createBlock([
89052                 ts.startOnNewLine(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(expressionName, restIndex === 0
89053                     ? temp
89054                     : factory.createSubtract(temp, factory.createNumericLiteral(restIndex))), factory.createElementAccessExpression(factory.createIdentifier("arguments"), temp))), 
89055                 /*location*/ parameter))
89056             ]));
89057             ts.setEmitFlags(forStatement, 1048576 /* CustomPrologue */);
89058             ts.startOnNewLine(forStatement);
89059             prologueStatements.push(forStatement);
89060             if (parameter.name.kind !== 78 /* Identifier */) {
89061                 // do the actual destructuring of the rest parameter if necessary
89062                 prologueStatements.push(ts.setEmitFlags(ts.setTextRange(factory.createVariableStatement(
89063                 /*modifiers*/ undefined, factory.createVariableDeclarationList(ts.flattenDestructuringBinding(parameter, visitor, context, 0 /* All */, expressionName))), parameter), 1048576 /* CustomPrologue */));
89064             }
89065             ts.insertStatementsAfterCustomPrologue(statements, prologueStatements);
89066             return true;
89067         }
89068         /**
89069          * Adds a statement to capture the `this` of a function declaration if it is needed.
89070          * NOTE: This must be executed *after* the subtree has been visited.
89071          *
89072          * @param statements The statements for the new function body.
89073          * @param node A node.
89074          */
89075         function insertCaptureThisForNodeIfNeeded(statements, node) {
89076             if (hierarchyFacts & 32768 /* CapturedLexicalThis */ && node.kind !== 209 /* ArrowFunction */) {
89077                 insertCaptureThisForNode(statements, node, factory.createThis());
89078                 return true;
89079             }
89080             return false;
89081         }
89082         function insertCaptureThisForNode(statements, node, initializer) {
89083             enableSubstitutionsForCapturedThis();
89084             var captureThisStatement = factory.createVariableStatement(
89085             /*modifiers*/ undefined, factory.createVariableDeclarationList([
89086                 factory.createVariableDeclaration(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), 
89087                 /*exclamationToken*/ undefined, 
89088                 /*type*/ undefined, initializer)
89089             ]));
89090             ts.setEmitFlags(captureThisStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
89091             ts.setSourceMapRange(captureThisStatement, node);
89092             ts.insertStatementAfterCustomPrologue(statements, captureThisStatement);
89093         }
89094         function insertCaptureNewTargetIfNeeded(statements, node, copyOnWrite) {
89095             if (hierarchyFacts & 16384 /* NewTarget */) {
89096                 var newTarget = void 0;
89097                 switch (node.kind) {
89098                     case 209 /* ArrowFunction */:
89099                         return statements;
89100                     case 165 /* MethodDeclaration */:
89101                     case 167 /* GetAccessor */:
89102                     case 168 /* SetAccessor */:
89103                         // Methods and accessors cannot be constructors, so 'new.target' will
89104                         // always return 'undefined'.
89105                         newTarget = factory.createVoidZero();
89106                         break;
89107                     case 166 /* Constructor */:
89108                         // Class constructors can only be called with `new`, so `this.constructor`
89109                         // should be relatively safe to use.
89110                         newTarget = factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor");
89111                         break;
89112                     case 251 /* FunctionDeclaration */:
89113                     case 208 /* FunctionExpression */:
89114                         // Functions can be called or constructed, and may have a `this` due to
89115                         // being a member or when calling an imported function via `other_1.f()`.
89116                         newTarget = factory.createConditionalExpression(factory.createLogicalAnd(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), factory.createBinaryExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), 101 /* InstanceOfKeyword */, factory.getLocalName(node))), 
89117                         /*questionToken*/ undefined, factory.createPropertyAccessExpression(ts.setEmitFlags(factory.createThis(), 4 /* NoSubstitution */), "constructor"), 
89118                         /*colonToken*/ undefined, factory.createVoidZero());
89119                         break;
89120                     default:
89121                         return ts.Debug.failBadSyntaxKind(node);
89122                 }
89123                 var captureNewTargetStatement = factory.createVariableStatement(
89124                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
89125                     factory.createVariableDeclaration(factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */), 
89126                     /*exclamationToken*/ undefined, 
89127                     /*type*/ undefined, newTarget)
89128                 ]));
89129                 ts.setEmitFlags(captureNewTargetStatement, 1536 /* NoComments */ | 1048576 /* CustomPrologue */);
89130                 if (copyOnWrite) {
89131                     statements = statements.slice();
89132                 }
89133                 ts.insertStatementAfterCustomPrologue(statements, captureNewTargetStatement);
89134             }
89135             return statements;
89136         }
89137         /**
89138          * Adds statements to the class body function for a class to define the members of the
89139          * class.
89140          *
89141          * @param statements The statements for the class body function.
89142          * @param node The ClassExpression or ClassDeclaration node.
89143          */
89144         function addClassMembers(statements, node) {
89145             for (var _i = 0, _a = node.members; _i < _a.length; _i++) {
89146                 var member = _a[_i];
89147                 switch (member.kind) {
89148                     case 229 /* SemicolonClassElement */:
89149                         statements.push(transformSemicolonClassElementToStatement(member));
89150                         break;
89151                     case 165 /* MethodDeclaration */:
89152                         statements.push(transformClassMethodDeclarationToStatement(getClassMemberPrefix(node, member), member, node));
89153                         break;
89154                     case 167 /* GetAccessor */:
89155                     case 168 /* SetAccessor */:
89156                         var accessors = ts.getAllAccessorDeclarations(node.members, member);
89157                         if (member === accessors.firstAccessor) {
89158                             statements.push(transformAccessorsToStatement(getClassMemberPrefix(node, member), accessors, node));
89159                         }
89160                         break;
89161                     case 166 /* Constructor */:
89162                         // Constructors are handled in visitClassExpression/visitClassDeclaration
89163                         break;
89164                     default:
89165                         ts.Debug.failBadSyntaxKind(member, currentSourceFile && currentSourceFile.fileName);
89166                         break;
89167                 }
89168             }
89169         }
89170         /**
89171          * Transforms a SemicolonClassElement into a statement for a class body function.
89172          *
89173          * @param member The SemicolonClassElement node.
89174          */
89175         function transformSemicolonClassElementToStatement(member) {
89176             return ts.setTextRange(factory.createEmptyStatement(), member);
89177         }
89178         /**
89179          * Transforms a MethodDeclaration into a statement for a class body function.
89180          *
89181          * @param receiver The receiver for the member.
89182          * @param member The MethodDeclaration node.
89183          */
89184         function transformClassMethodDeclarationToStatement(receiver, member, container) {
89185             var commentRange = ts.getCommentRange(member);
89186             var sourceMapRange = ts.getSourceMapRange(member);
89187             var memberFunction = transformFunctionLikeToExpression(member, /*location*/ member, /*name*/ undefined, container);
89188             var propertyName = ts.visitNode(member.name, visitor, ts.isPropertyName);
89189             var e;
89190             if (!ts.isPrivateIdentifier(propertyName) && context.getCompilerOptions().useDefineForClassFields) {
89191                 var name = ts.isComputedPropertyName(propertyName) ? propertyName.expression
89192                     : ts.isIdentifier(propertyName) ? factory.createStringLiteral(ts.unescapeLeadingUnderscores(propertyName.escapedText))
89193                         : propertyName;
89194                 e = factory.createObjectDefinePropertyCall(receiver, name, factory.createPropertyDescriptor({ value: memberFunction, enumerable: false, writable: true, configurable: true }));
89195             }
89196             else {
89197                 var memberName = ts.createMemberAccessForPropertyName(factory, receiver, propertyName, /*location*/ member.name);
89198                 e = factory.createAssignment(memberName, memberFunction);
89199             }
89200             ts.setEmitFlags(memberFunction, 1536 /* NoComments */);
89201             ts.setSourceMapRange(memberFunction, sourceMapRange);
89202             var statement = ts.setTextRange(factory.createExpressionStatement(e), /*location*/ member);
89203             ts.setOriginalNode(statement, member);
89204             ts.setCommentRange(statement, commentRange);
89205             // The location for the statement is used to emit comments only.
89206             // No source map should be emitted for this statement to align with the
89207             // old emitter.
89208             ts.setEmitFlags(statement, 48 /* NoSourceMap */);
89209             return statement;
89210         }
89211         /**
89212          * Transforms a set of related of get/set accessors into a statement for a class body function.
89213          *
89214          * @param receiver The receiver for the member.
89215          * @param accessors The set of related get/set accessors.
89216          */
89217         function transformAccessorsToStatement(receiver, accessors, container) {
89218             var statement = factory.createExpressionStatement(transformAccessorsToExpression(receiver, accessors, container, /*startsOnNewLine*/ false));
89219             // The location for the statement is used to emit source maps only.
89220             // No comments should be emitted for this statement to align with the
89221             // old emitter.
89222             ts.setEmitFlags(statement, 1536 /* NoComments */);
89223             ts.setSourceMapRange(statement, ts.getSourceMapRange(accessors.firstAccessor));
89224             return statement;
89225         }
89226         /**
89227          * Transforms a set of related get/set accessors into an expression for either a class
89228          * body function or an ObjectLiteralExpression with computed properties.
89229          *
89230          * @param receiver The receiver for the member.
89231          */
89232         function transformAccessorsToExpression(receiver, _a, container, startsOnNewLine) {
89233             var firstAccessor = _a.firstAccessor, getAccessor = _a.getAccessor, setAccessor = _a.setAccessor;
89234             // To align with source maps in the old emitter, the receiver and property name
89235             // arguments are both mapped contiguously to the accessor name.
89236             // TODO(rbuckton): Does this need to be parented?
89237             var target = ts.setParent(ts.setTextRange(factory.cloneNode(receiver), receiver), receiver.parent);
89238             ts.setEmitFlags(target, 1536 /* NoComments */ | 32 /* NoTrailingSourceMap */);
89239             ts.setSourceMapRange(target, firstAccessor.name);
89240             var visitedAccessorName = ts.visitNode(firstAccessor.name, visitor, ts.isPropertyName);
89241             if (ts.isPrivateIdentifier(visitedAccessorName)) {
89242                 return ts.Debug.failBadSyntaxKind(visitedAccessorName, "Encountered unhandled private identifier while transforming ES2015.");
89243             }
89244             var propertyName = ts.createExpressionForPropertyName(factory, visitedAccessorName);
89245             ts.setEmitFlags(propertyName, 1536 /* NoComments */ | 16 /* NoLeadingSourceMap */);
89246             ts.setSourceMapRange(propertyName, firstAccessor.name);
89247             var properties = [];
89248             if (getAccessor) {
89249                 var getterFunction = transformFunctionLikeToExpression(getAccessor, /*location*/ undefined, /*name*/ undefined, container);
89250                 ts.setSourceMapRange(getterFunction, ts.getSourceMapRange(getAccessor));
89251                 ts.setEmitFlags(getterFunction, 512 /* NoLeadingComments */);
89252                 var getter = factory.createPropertyAssignment("get", getterFunction);
89253                 ts.setCommentRange(getter, ts.getCommentRange(getAccessor));
89254                 properties.push(getter);
89255             }
89256             if (setAccessor) {
89257                 var setterFunction = transformFunctionLikeToExpression(setAccessor, /*location*/ undefined, /*name*/ undefined, container);
89258                 ts.setSourceMapRange(setterFunction, ts.getSourceMapRange(setAccessor));
89259                 ts.setEmitFlags(setterFunction, 512 /* NoLeadingComments */);
89260                 var setter = factory.createPropertyAssignment("set", setterFunction);
89261                 ts.setCommentRange(setter, ts.getCommentRange(setAccessor));
89262                 properties.push(setter);
89263             }
89264             properties.push(factory.createPropertyAssignment("enumerable", getAccessor || setAccessor ? factory.createFalse() : factory.createTrue()), factory.createPropertyAssignment("configurable", factory.createTrue()));
89265             var call = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
89266             /*typeArguments*/ undefined, [
89267                 target,
89268                 propertyName,
89269                 factory.createObjectLiteralExpression(properties, /*multiLine*/ true)
89270             ]);
89271             if (startsOnNewLine) {
89272                 ts.startOnNewLine(call);
89273             }
89274             return call;
89275         }
89276         /**
89277          * Visits an ArrowFunction and transforms it into a FunctionExpression.
89278          *
89279          * @param node An ArrowFunction node.
89280          */
89281         function visitArrowFunction(node) {
89282             if (node.transformFlags & 4096 /* ContainsLexicalThis */) {
89283                 hierarchyFacts |= 32768 /* CapturedLexicalThis */;
89284             }
89285             var savedConvertedLoopState = convertedLoopState;
89286             convertedLoopState = undefined;
89287             var ancestorFacts = enterSubtree(15232 /* ArrowFunctionExcludes */, 66 /* ArrowFunctionIncludes */);
89288             var func = factory.createFunctionExpression(
89289             /*modifiers*/ undefined, 
89290             /*asteriskToken*/ undefined, 
89291             /*name*/ undefined, 
89292             /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
89293             /*type*/ undefined, transformFunctionBody(node));
89294             ts.setTextRange(func, node);
89295             ts.setOriginalNode(func, node);
89296             ts.setEmitFlags(func, 8 /* CapturesThis */);
89297             if (hierarchyFacts & 32768 /* CapturedLexicalThis */) {
89298                 enableSubstitutionsForCapturedThis();
89299             }
89300             // If an arrow function contains
89301             exitSubtree(ancestorFacts, 0 /* ArrowFunctionSubtreeExcludes */, 0 /* None */);
89302             convertedLoopState = savedConvertedLoopState;
89303             return func;
89304         }
89305         /**
89306          * Visits a FunctionExpression node.
89307          *
89308          * @param node a FunctionExpression node.
89309          */
89310         function visitFunctionExpression(node) {
89311             var ancestorFacts = ts.getEmitFlags(node) & 262144 /* AsyncFunctionBody */
89312                 ? enterSubtree(16278 /* AsyncFunctionBodyExcludes */, 69 /* AsyncFunctionBodyIncludes */)
89313                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
89314             var savedConvertedLoopState = convertedLoopState;
89315             convertedLoopState = undefined;
89316             var parameters = ts.visitParameterList(node.parameters, visitor, context);
89317             var body = transformFunctionBody(node);
89318             var name = hierarchyFacts & 16384 /* NewTarget */
89319                 ? factory.getLocalName(node)
89320                 : node.name;
89321             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
89322             convertedLoopState = savedConvertedLoopState;
89323             return factory.updateFunctionExpression(node, 
89324             /*modifiers*/ undefined, node.asteriskToken, name, 
89325             /*typeParameters*/ undefined, parameters, 
89326             /*type*/ undefined, body);
89327         }
89328         /**
89329          * Visits a FunctionDeclaration node.
89330          *
89331          * @param node a FunctionDeclaration node.
89332          */
89333         function visitFunctionDeclaration(node) {
89334             var savedConvertedLoopState = convertedLoopState;
89335             convertedLoopState = undefined;
89336             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
89337             var parameters = ts.visitParameterList(node.parameters, visitor, context);
89338             var body = transformFunctionBody(node);
89339             var name = hierarchyFacts & 16384 /* NewTarget */
89340                 ? factory.getLocalName(node)
89341                 : node.name;
89342             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
89343             convertedLoopState = savedConvertedLoopState;
89344             return factory.updateFunctionDeclaration(node, 
89345             /*decorators*/ undefined, ts.visitNodes(node.modifiers, visitor, ts.isModifier), node.asteriskToken, name, 
89346             /*typeParameters*/ undefined, parameters, 
89347             /*type*/ undefined, body);
89348         }
89349         /**
89350          * Transforms a function-like node into a FunctionExpression.
89351          *
89352          * @param node The function-like node to transform.
89353          * @param location The source-map location for the new FunctionExpression.
89354          * @param name The name of the new FunctionExpression.
89355          */
89356         function transformFunctionLikeToExpression(node, location, name, container) {
89357             var savedConvertedLoopState = convertedLoopState;
89358             convertedLoopState = undefined;
89359             var ancestorFacts = container && ts.isClassLike(container) && !ts.hasSyntacticModifier(node, 32 /* Static */)
89360                 ? enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */ | 8 /* NonStaticClassElement */)
89361                 : enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
89362             var parameters = ts.visitParameterList(node.parameters, visitor, context);
89363             var body = transformFunctionBody(node);
89364             if (hierarchyFacts & 16384 /* NewTarget */ && !name && (node.kind === 251 /* FunctionDeclaration */ || node.kind === 208 /* FunctionExpression */)) {
89365                 name = factory.getGeneratedNameForNode(node);
89366             }
89367             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
89368             convertedLoopState = savedConvertedLoopState;
89369             return ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
89370             /*modifiers*/ undefined, node.asteriskToken, name, 
89371             /*typeParameters*/ undefined, parameters, 
89372             /*type*/ undefined, body), location), 
89373             /*original*/ node);
89374         }
89375         /**
89376          * Transforms the body of a function-like node.
89377          *
89378          * @param node A function-like node.
89379          */
89380         function transformFunctionBody(node) {
89381             var multiLine = false; // indicates whether the block *must* be emitted as multiple lines
89382             var singleLine = false; // indicates whether the block *may* be emitted as a single line
89383             var statementsLocation;
89384             var closeBraceLocation;
89385             var prologue = [];
89386             var statements = [];
89387             var body = node.body;
89388             var statementOffset;
89389             resumeLexicalEnvironment();
89390             if (ts.isBlock(body)) {
89391                 // ensureUseStrict is false because no new prologue-directive should be added.
89392                 // addStandardPrologue will put already-existing directives at the beginning of the target statement-array
89393                 statementOffset = factory.copyStandardPrologue(body.statements, prologue, /*ensureUseStrict*/ false);
89394                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedFunction);
89395                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor, ts.isHoistedVariableStatement);
89396             }
89397             multiLine = addDefaultValueAssignmentsIfNeeded(statements, node) || multiLine;
89398             multiLine = addRestParameterIfNeeded(statements, node, /*inConstructorWithSynthesizedSuper*/ false) || multiLine;
89399             if (ts.isBlock(body)) {
89400                 // addCustomPrologue puts already-existing directives at the beginning of the target statement-array
89401                 statementOffset = factory.copyCustomPrologue(body.statements, statements, statementOffset, visitor);
89402                 statementsLocation = body.statements;
89403                 ts.addRange(statements, ts.visitNodes(body.statements, visitor, ts.isStatement, statementOffset));
89404                 // If the original body was a multi-line block, this must be a multi-line block.
89405                 if (!multiLine && body.multiLine) {
89406                     multiLine = true;
89407                 }
89408             }
89409             else {
89410                 ts.Debug.assert(node.kind === 209 /* ArrowFunction */);
89411                 // To align with the old emitter, we use a synthetic end position on the location
89412                 // for the statement list we synthesize when we down-level an arrow function with
89413                 // an expression function body. This prevents both comments and source maps from
89414                 // being emitted for the end position only.
89415                 statementsLocation = ts.moveRangeEnd(body, -1);
89416                 var equalsGreaterThanToken = node.equalsGreaterThanToken;
89417                 if (!ts.nodeIsSynthesized(equalsGreaterThanToken) && !ts.nodeIsSynthesized(body)) {
89418                     if (ts.rangeEndIsOnSameLineAsRangeStart(equalsGreaterThanToken, body, currentSourceFile)) {
89419                         singleLine = true;
89420                     }
89421                     else {
89422                         multiLine = true;
89423                     }
89424                 }
89425                 var expression = ts.visitNode(body, visitor, ts.isExpression);
89426                 var returnStatement = factory.createReturnStatement(expression);
89427                 ts.setTextRange(returnStatement, body);
89428                 ts.moveSyntheticComments(returnStatement, body);
89429                 ts.setEmitFlags(returnStatement, 384 /* NoTokenSourceMaps */ | 32 /* NoTrailingSourceMap */ | 1024 /* NoTrailingComments */);
89430                 statements.push(returnStatement);
89431                 // To align with the source map emit for the old emitter, we set a custom
89432                 // source map location for the close brace.
89433                 closeBraceLocation = body;
89434             }
89435             factory.mergeLexicalEnvironment(prologue, endLexicalEnvironment());
89436             insertCaptureNewTargetIfNeeded(prologue, node, /*copyOnWrite*/ false);
89437             insertCaptureThisForNodeIfNeeded(prologue, node);
89438             // If we added any final generated statements, this must be a multi-line block
89439             if (ts.some(prologue)) {
89440                 multiLine = true;
89441             }
89442             statements.unshift.apply(statements, prologue);
89443             if (ts.isBlock(body) && ts.arrayIsEqualTo(statements, body.statements)) {
89444                 // no changes were made, preserve the tree
89445                 return body;
89446             }
89447             var block = factory.createBlock(ts.setTextRange(factory.createNodeArray(statements), statementsLocation), multiLine);
89448             ts.setTextRange(block, node.body);
89449             if (!multiLine && singleLine) {
89450                 ts.setEmitFlags(block, 1 /* SingleLine */);
89451             }
89452             if (closeBraceLocation) {
89453                 ts.setTokenSourceMapRange(block, 19 /* CloseBraceToken */, closeBraceLocation);
89454             }
89455             ts.setOriginalNode(block, node.body);
89456             return block;
89457         }
89458         function visitBlock(node, isFunctionBody) {
89459             if (isFunctionBody) {
89460                 // A function body is not a block scope.
89461                 return ts.visitEachChild(node, visitor, context);
89462             }
89463             var ancestorFacts = hierarchyFacts & 256 /* IterationStatement */
89464                 ? enterSubtree(7104 /* IterationStatementBlockExcludes */, 512 /* IterationStatementBlockIncludes */)
89465                 : enterSubtree(6976 /* BlockExcludes */, 128 /* BlockIncludes */);
89466             var updated = ts.visitEachChild(node, visitor, context);
89467             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89468             return updated;
89469         }
89470         /**
89471          * Visits an ExpressionStatement that contains a destructuring assignment.
89472          *
89473          * @param node An ExpressionStatement node.
89474          */
89475         function visitExpressionStatement(node) {
89476             return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
89477         }
89478         /**
89479          * Visits a ParenthesizedExpression that may contain a destructuring assignment.
89480          *
89481          * @param node A ParenthesizedExpression node.
89482          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
89483          * expression of an `ExpressionStatement`).
89484          */
89485         function visitParenthesizedExpression(node, expressionResultIsUnused) {
89486             return ts.visitEachChild(node, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, context);
89487         }
89488         /**
89489          * Visits a BinaryExpression that contains a destructuring assignment.
89490          *
89491          * @param node A BinaryExpression node.
89492          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
89493          * expression of an `ExpressionStatement`).
89494          */
89495         function visitBinaryExpression(node, expressionResultIsUnused) {
89496             // If we are here it is because this is a destructuring assignment.
89497             if (ts.isDestructuringAssignment(node)) {
89498                 return ts.flattenDestructuringAssignment(node, visitor, context, 0 /* All */, !expressionResultIsUnused);
89499             }
89500             if (node.operatorToken.kind === 27 /* CommaToken */) {
89501                 return factory.updateBinaryExpression(node, ts.visitNode(node.left, visitorWithUnusedExpressionResult, ts.isExpression), node.operatorToken, ts.visitNode(node.right, expressionResultIsUnused ? visitorWithUnusedExpressionResult : visitor, ts.isExpression));
89502             }
89503             return ts.visitEachChild(node, visitor, context);
89504         }
89505         /**
89506          * @param expressionResultIsUnused Indicates the result of an expression is unused by the parent node (i.e., the left side of a comma or the
89507          * expression of an `ExpressionStatement`).
89508          */
89509         function visitCommaListExpression(node, expressionResultIsUnused) {
89510             if (expressionResultIsUnused) {
89511                 return ts.visitEachChild(node, visitorWithUnusedExpressionResult, context);
89512             }
89513             var result;
89514             for (var i = 0; i < node.elements.length; i++) {
89515                 var element = node.elements[i];
89516                 var visited = ts.visitNode(element, i < node.elements.length - 1 ? visitorWithUnusedExpressionResult : visitor, ts.isExpression);
89517                 if (result || visited !== element) {
89518                     result || (result = node.elements.slice(0, i));
89519                     result.push(visited);
89520                 }
89521             }
89522             var elements = result ? ts.setTextRange(factory.createNodeArray(result), node.elements) : node.elements;
89523             return factory.updateCommaListExpression(node, elements);
89524         }
89525         function isVariableStatementOfTypeScriptClassWrapper(node) {
89526             return node.declarationList.declarations.length === 1
89527                 && !!node.declarationList.declarations[0].initializer
89528                 && !!(ts.getEmitFlags(node.declarationList.declarations[0].initializer) & 33554432 /* TypeScriptClassWrapper */);
89529         }
89530         function visitVariableStatement(node) {
89531             var ancestorFacts = enterSubtree(0 /* None */, ts.hasSyntacticModifier(node, 1 /* Export */) ? 32 /* ExportedVariableStatement */ : 0 /* None */);
89532             var updated;
89533             if (convertedLoopState && (node.declarationList.flags & 3 /* BlockScoped */) === 0 && !isVariableStatementOfTypeScriptClassWrapper(node)) {
89534                 // we are inside a converted loop - hoist variable declarations
89535                 var assignments = void 0;
89536                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
89537                     var decl = _a[_i];
89538                     hoistVariableDeclarationDeclaredInConvertedLoop(convertedLoopState, decl);
89539                     if (decl.initializer) {
89540                         var assignment = void 0;
89541                         if (ts.isBindingPattern(decl.name)) {
89542                             assignment = ts.flattenDestructuringAssignment(decl, visitor, context, 0 /* All */);
89543                         }
89544                         else {
89545                             assignment = factory.createBinaryExpression(decl.name, 62 /* EqualsToken */, ts.visitNode(decl.initializer, visitor, ts.isExpression));
89546                             ts.setTextRange(assignment, decl);
89547                         }
89548                         assignments = ts.append(assignments, assignment);
89549                     }
89550                 }
89551                 if (assignments) {
89552                     updated = ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(assignments)), node);
89553                 }
89554                 else {
89555                     // none of declarations has initializer - the entire variable statement can be deleted
89556                     updated = undefined;
89557                 }
89558             }
89559             else {
89560                 updated = ts.visitEachChild(node, visitor, context);
89561             }
89562             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89563             return updated;
89564         }
89565         /**
89566          * Visits a VariableDeclarationList that is block scoped (e.g. `let` or `const`).
89567          *
89568          * @param node A VariableDeclarationList node.
89569          */
89570         function visitVariableDeclarationList(node) {
89571             if (node.flags & 3 /* BlockScoped */ || node.transformFlags & 131072 /* ContainsBindingPattern */) {
89572                 if (node.flags & 3 /* BlockScoped */) {
89573                     enableSubstitutionsForBlockScopedBindings();
89574                 }
89575                 var declarations = ts.flatMap(node.declarations, node.flags & 1 /* Let */
89576                     ? visitVariableDeclarationInLetDeclarationList
89577                     : visitVariableDeclaration);
89578                 var declarationList = factory.createVariableDeclarationList(declarations);
89579                 ts.setOriginalNode(declarationList, node);
89580                 ts.setTextRange(declarationList, node);
89581                 ts.setCommentRange(declarationList, node);
89582                 // If the first or last declaration is a binding pattern, we need to modify
89583                 // the source map range for the declaration list.
89584                 if (node.transformFlags & 131072 /* ContainsBindingPattern */
89585                     && (ts.isBindingPattern(node.declarations[0].name) || ts.isBindingPattern(ts.last(node.declarations).name))) {
89586                     ts.setSourceMapRange(declarationList, getRangeUnion(declarations));
89587                 }
89588                 return declarationList;
89589             }
89590             return ts.visitEachChild(node, visitor, context);
89591         }
89592         function getRangeUnion(declarations) {
89593             // declarations may not be sorted by position.
89594             // pos should be the minimum* position over all nodes (that's not -1), end should be the maximum end over all nodes.
89595             var pos = -1, end = -1;
89596             for (var _i = 0, declarations_10 = declarations; _i < declarations_10.length; _i++) {
89597                 var node = declarations_10[_i];
89598                 pos = pos === -1 ? node.pos : node.pos === -1 ? pos : Math.min(pos, node.pos);
89599                 end = Math.max(end, node.end);
89600             }
89601             return ts.createRange(pos, end);
89602         }
89603         /**
89604          * Gets a value indicating whether we should emit an explicit initializer for a variable
89605          * declaration in a `let` declaration list.
89606          *
89607          * @param node A VariableDeclaration node.
89608          */
89609         function shouldEmitExplicitInitializerForLetDeclaration(node) {
89610             // Nested let bindings might need to be initialized explicitly to preserve
89611             // ES6 semantic:
89612             //
89613             //  { let x = 1; }
89614             //  { let x; } // x here should be undefined. not 1
89615             //
89616             // Top level bindings never collide with anything and thus don't require
89617             // explicit initialization. As for nested let bindings there are two cases:
89618             //
89619             // - Nested let bindings that were not renamed definitely should be
89620             //   initialized explicitly:
89621             //
89622             //    { let x = 1; }
89623             //    { let x; if (some-condition) { x = 1}; if (x) { /*1*/ } }
89624             //
89625             //   Without explicit initialization code in /*1*/ can be executed even if
89626             //   some-condition is evaluated to false.
89627             //
89628             // - Renaming introduces fresh name that should not collide with any
89629             //   existing names, however renamed bindings sometimes also should be
89630             //   explicitly initialized. One particular case: non-captured binding
89631             //   declared inside loop body (but not in loop initializer):
89632             //
89633             //    let x;
89634             //    for (;;) {
89635             //        let x;
89636             //    }
89637             //
89638             //   In downlevel codegen inner 'x' will be renamed so it won't collide
89639             //   with outer 'x' however it will should be reset on every iteration as
89640             //   if it was declared anew.
89641             //
89642             //   * Why non-captured binding?
89643             //     - Because if loop contains block scoped binding captured in some
89644             //       function then loop body will be rewritten to have a fresh scope
89645             //       on every iteration so everything will just work.
89646             //
89647             //   * Why loop initializer is excluded?
89648             //     - Since we've introduced a fresh name it already will be undefined.
89649             var flags = resolver.getNodeCheckFlags(node);
89650             var isCapturedInFunction = flags & 262144 /* CapturedBlockScopedBinding */;
89651             var isDeclaredInLoop = flags & 524288 /* BlockScopedBindingInLoop */;
89652             var emittedAsTopLevel = (hierarchyFacts & 64 /* TopLevel */) !== 0
89653                 || (isCapturedInFunction
89654                     && isDeclaredInLoop
89655                     && (hierarchyFacts & 512 /* IterationStatementBlock */) !== 0);
89656             var emitExplicitInitializer = !emittedAsTopLevel
89657                 && (hierarchyFacts & 4096 /* ForInOrForOfStatement */) === 0
89658                 && (!resolver.isDeclarationWithCollidingName(node)
89659                     || (isDeclaredInLoop
89660                         && !isCapturedInFunction
89661                         && (hierarchyFacts & (2048 /* ForStatement */ | 4096 /* ForInOrForOfStatement */)) === 0));
89662             return emitExplicitInitializer;
89663         }
89664         /**
89665          * Visits a VariableDeclaration in a `let` declaration list.
89666          *
89667          * @param node A VariableDeclaration node.
89668          */
89669         function visitVariableDeclarationInLetDeclarationList(node) {
89670             // For binding pattern names that lack initializers there is no point to emit
89671             // explicit initializer since downlevel codegen for destructuring will fail
89672             // in the absence of initializer so all binding elements will say uninitialized
89673             var name = node.name;
89674             if (ts.isBindingPattern(name)) {
89675                 return visitVariableDeclaration(node);
89676             }
89677             if (!node.initializer && shouldEmitExplicitInitializerForLetDeclaration(node)) {
89678                 return factory.updateVariableDeclaration(node, node.name, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createVoidZero());
89679             }
89680             return ts.visitEachChild(node, visitor, context);
89681         }
89682         /**
89683          * Visits a VariableDeclaration node with a binding pattern.
89684          *
89685          * @param node A VariableDeclaration node.
89686          */
89687         function visitVariableDeclaration(node) {
89688             var ancestorFacts = enterSubtree(32 /* ExportedVariableStatement */, 0 /* None */);
89689             var updated;
89690             if (ts.isBindingPattern(node.name)) {
89691                 updated = ts.flattenDestructuringBinding(node, visitor, context, 0 /* All */, 
89692                 /*value*/ undefined, (ancestorFacts & 32 /* ExportedVariableStatement */) !== 0);
89693             }
89694             else {
89695                 updated = ts.visitEachChild(node, visitor, context);
89696             }
89697             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89698             return updated;
89699         }
89700         function recordLabel(node) {
89701             convertedLoopState.labels.set(ts.idText(node.label), true);
89702         }
89703         function resetLabel(node) {
89704             convertedLoopState.labels.set(ts.idText(node.label), false);
89705         }
89706         function visitLabeledStatement(node) {
89707             if (convertedLoopState && !convertedLoopState.labels) {
89708                 convertedLoopState.labels = new ts.Map();
89709             }
89710             var statement = ts.unwrapInnermostStatementOfLabel(node, convertedLoopState && recordLabel);
89711             return ts.isIterationStatement(statement, /*lookInLabeledStatements*/ false)
89712                 ? visitIterationStatement(statement, /*outermostLabeledStatement*/ node)
89713                 : factory.restoreEnclosingLabel(ts.visitNode(statement, visitor, ts.isStatement, factory.liftToBlock), node, convertedLoopState && resetLabel);
89714         }
89715         function visitIterationStatement(node, outermostLabeledStatement) {
89716             switch (node.kind) {
89717                 case 235 /* DoStatement */:
89718                 case 236 /* WhileStatement */:
89719                     return visitDoOrWhileStatement(node, outermostLabeledStatement);
89720                 case 237 /* ForStatement */:
89721                     return visitForStatement(node, outermostLabeledStatement);
89722                 case 238 /* ForInStatement */:
89723                     return visitForInStatement(node, outermostLabeledStatement);
89724                 case 239 /* ForOfStatement */:
89725                     return visitForOfStatement(node, outermostLabeledStatement);
89726             }
89727         }
89728         function visitIterationStatementWithFacts(excludeFacts, includeFacts, node, outermostLabeledStatement, convert) {
89729             var ancestorFacts = enterSubtree(excludeFacts, includeFacts);
89730             var updated = convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert);
89731             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
89732             return updated;
89733         }
89734         function visitDoOrWhileStatement(node, outermostLabeledStatement) {
89735             return visitIterationStatementWithFacts(0 /* DoOrWhileStatementExcludes */, 1280 /* DoOrWhileStatementIncludes */, node, outermostLabeledStatement);
89736         }
89737         function visitForStatement(node, outermostLabeledStatement) {
89738             return visitIterationStatementWithFacts(5056 /* ForStatementExcludes */, 3328 /* ForStatementIncludes */, node, outermostLabeledStatement);
89739         }
89740         function visitEachChildOfForStatement(node) {
89741             return factory.updateForStatement(node, ts.visitNode(node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
89742         }
89743         function visitForInStatement(node, outermostLabeledStatement) {
89744             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement);
89745         }
89746         function visitForOfStatement(node, outermostLabeledStatement) {
89747             return visitIterationStatementWithFacts(3008 /* ForInOrForOfStatementExcludes */, 5376 /* ForInOrForOfStatementIncludes */, node, outermostLabeledStatement, compilerOptions.downlevelIteration ? convertForOfStatementForIterable : convertForOfStatementForArray);
89748         }
89749         function convertForOfStatementHead(node, boundValue, convertedLoopBodyStatements) {
89750             var statements = [];
89751             var initializer = node.initializer;
89752             if (ts.isVariableDeclarationList(initializer)) {
89753                 if (node.initializer.flags & 3 /* BlockScoped */) {
89754                     enableSubstitutionsForBlockScopedBindings();
89755                 }
89756                 var firstOriginalDeclaration = ts.firstOrUndefined(initializer.declarations);
89757                 if (firstOriginalDeclaration && ts.isBindingPattern(firstOriginalDeclaration.name)) {
89758                     // This works whether the declaration is a var, let, or const.
89759                     // It will use rhsIterationValue _a[_i] as the initializer.
89760                     var declarations = ts.flattenDestructuringBinding(firstOriginalDeclaration, visitor, context, 0 /* All */, boundValue);
89761                     var declarationList = ts.setTextRange(factory.createVariableDeclarationList(declarations), node.initializer);
89762                     ts.setOriginalNode(declarationList, node.initializer);
89763                     // Adjust the source map range for the first declaration to align with the old
89764                     // emitter.
89765                     ts.setSourceMapRange(declarationList, ts.createRange(declarations[0].pos, ts.last(declarations).end));
89766                     statements.push(factory.createVariableStatement(
89767                     /*modifiers*/ undefined, declarationList));
89768                 }
89769                 else {
89770                     // The following call does not include the initializer, so we have
89771                     // to emit it separately.
89772                     statements.push(ts.setTextRange(factory.createVariableStatement(
89773                     /*modifiers*/ undefined, ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclarationList([
89774                         factory.createVariableDeclaration(firstOriginalDeclaration ? firstOriginalDeclaration.name : factory.createTempVariable(/*recordTempVariable*/ undefined), 
89775                         /*exclamationToken*/ undefined, 
89776                         /*type*/ undefined, boundValue)
89777                     ]), ts.moveRangePos(initializer, -1)), initializer)), ts.moveRangeEnd(initializer, -1)));
89778                 }
89779             }
89780             else {
89781                 // Initializer is an expression. Emit the expression in the body, so that it's
89782                 // evaluated on every iteration.
89783                 var assignment = factory.createAssignment(initializer, boundValue);
89784                 if (ts.isDestructuringAssignment(assignment)) {
89785                     statements.push(factory.createExpressionStatement(visitBinaryExpression(assignment, /*expressionResultIsUnused*/ true)));
89786                 }
89787                 else {
89788                     ts.setTextRangeEnd(assignment, initializer.end);
89789                     statements.push(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(assignment, visitor, ts.isExpression)), ts.moveRangeEnd(initializer, -1)));
89790                 }
89791             }
89792             if (convertedLoopBodyStatements) {
89793                 return createSyntheticBlockForConvertedStatements(ts.addRange(statements, convertedLoopBodyStatements));
89794             }
89795             else {
89796                 var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
89797                 if (ts.isBlock(statement)) {
89798                     return factory.updateBlock(statement, ts.setTextRange(factory.createNodeArray(ts.concatenate(statements, statement.statements)), statement.statements));
89799                 }
89800                 else {
89801                     statements.push(statement);
89802                     return createSyntheticBlockForConvertedStatements(statements);
89803                 }
89804             }
89805         }
89806         function createSyntheticBlockForConvertedStatements(statements) {
89807             return ts.setEmitFlags(factory.createBlock(factory.createNodeArray(statements), 
89808             /*multiLine*/ true), 48 /* NoSourceMap */ | 384 /* NoTokenSourceMaps */);
89809         }
89810         function convertForOfStatementForArray(node, outermostLabeledStatement, convertedLoopBodyStatements) {
89811             // The following ES6 code:
89812             //
89813             //    for (let v of expr) { }
89814             //
89815             // should be emitted as
89816             //
89817             //    for (var _i = 0, _a = expr; _i < _a.length; _i++) {
89818             //        var v = _a[_i];
89819             //    }
89820             //
89821             // where _a and _i are temps emitted to capture the RHS and the counter,
89822             // respectively.
89823             // When the left hand side is an expression instead of a let declaration,
89824             // the "let v" is not emitted.
89825             // When the left hand side is a let/const, the v is renamed if there is
89826             // another v in scope.
89827             // Note that all assignments to the LHS are emitted in the body, including
89828             // all destructuring.
89829             // Note also that because an extra statement is needed to assign to the LHS,
89830             // for-of bodies are always emitted as blocks.
89831             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
89832             // In the case where the user wrote an identifier as the RHS, like this:
89833             //
89834             //     for (let v of arr) { }
89835             //
89836             // we don't want to emit a temporary variable for the RHS, just use it directly.
89837             var counter = factory.createLoopVariable();
89838             var rhsReference = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
89839             // The old emitter does not emit source maps for the expression
89840             ts.setEmitFlags(expression, 48 /* NoSourceMap */ | ts.getEmitFlags(expression));
89841             var forStatement = ts.setTextRange(factory.createForStatement(
89842             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
89843                 ts.setTextRange(factory.createVariableDeclaration(counter, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createNumericLiteral(0)), ts.moveRangePos(node.expression, -1)),
89844                 ts.setTextRange(factory.createVariableDeclaration(rhsReference, /*exclamationToken*/ undefined, /*type*/ undefined, expression), node.expression)
89845             ]), node.expression), 2097152 /* NoHoisting */), 
89846             /*condition*/ ts.setTextRange(factory.createLessThan(counter, factory.createPropertyAccessExpression(rhsReference, "length")), node.expression), 
89847             /*incrementor*/ ts.setTextRange(factory.createPostfixIncrement(counter), node.expression), 
89848             /*statement*/ convertForOfStatementHead(node, factory.createElementAccessExpression(rhsReference, counter), convertedLoopBodyStatements)), 
89849             /*location*/ node);
89850             // Disable trailing source maps for the OpenParenToken to align source map emit with the old emitter.
89851             ts.setEmitFlags(forStatement, 256 /* NoTokenTrailingSourceMaps */);
89852             ts.setTextRange(forStatement, node);
89853             return factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel);
89854         }
89855         function convertForOfStatementForIterable(node, outermostLabeledStatement, convertedLoopBodyStatements, ancestorFacts) {
89856             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
89857             var iterator = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(expression) : factory.createTempVariable(/*recordTempVariable*/ undefined);
89858             var result = ts.isIdentifier(expression) ? factory.getGeneratedNameForNode(iterator) : factory.createTempVariable(/*recordTempVariable*/ undefined);
89859             var errorRecord = factory.createUniqueName("e");
89860             var catchVariable = factory.getGeneratedNameForNode(errorRecord);
89861             var returnMethod = factory.createTempVariable(/*recordTempVariable*/ undefined);
89862             var values = ts.setTextRange(emitHelpers().createValuesHelper(expression), node.expression);
89863             var next = factory.createCallExpression(factory.createPropertyAccessExpression(iterator, "next"), /*typeArguments*/ undefined, []);
89864             hoistVariableDeclaration(errorRecord);
89865             hoistVariableDeclaration(returnMethod);
89866             // if we are enclosed in an outer loop ensure we reset 'errorRecord' per each iteration
89867             var initializer = ancestorFacts & 1024 /* IterationContainer */
89868                 ? factory.inlineExpressions([factory.createAssignment(errorRecord, factory.createVoidZero()), values])
89869                 : values;
89870             var forStatement = ts.setEmitFlags(ts.setTextRange(factory.createForStatement(
89871             /*initializer*/ ts.setEmitFlags(ts.setTextRange(factory.createVariableDeclarationList([
89872                 ts.setTextRange(factory.createVariableDeclaration(iterator, /*exclamationToken*/ undefined, /*type*/ undefined, initializer), node.expression),
89873                 factory.createVariableDeclaration(result, /*exclamationToken*/ undefined, /*type*/ undefined, next)
89874             ]), node.expression), 2097152 /* NoHoisting */), 
89875             /*condition*/ factory.createLogicalNot(factory.createPropertyAccessExpression(result, "done")), 
89876             /*incrementor*/ factory.createAssignment(result, next), 
89877             /*statement*/ convertForOfStatementHead(node, factory.createPropertyAccessExpression(result, "value"), convertedLoopBodyStatements)), 
89878             /*location*/ node), 256 /* NoTokenTrailingSourceMaps */);
89879             return factory.createTryStatement(factory.createBlock([
89880                 factory.restoreEnclosingLabel(forStatement, outermostLabeledStatement, convertedLoopState && resetLabel)
89881             ]), factory.createCatchClause(factory.createVariableDeclaration(catchVariable), ts.setEmitFlags(factory.createBlock([
89882                 factory.createExpressionStatement(factory.createAssignment(errorRecord, factory.createObjectLiteralExpression([
89883                     factory.createPropertyAssignment("error", catchVariable)
89884                 ])))
89885             ]), 1 /* SingleLine */)), factory.createBlock([
89886                 factory.createTryStatement(
89887                 /*tryBlock*/ factory.createBlock([
89888                     ts.setEmitFlags(factory.createIfStatement(factory.createLogicalAnd(factory.createLogicalAnd(result, factory.createLogicalNot(factory.createPropertyAccessExpression(result, "done"))), factory.createAssignment(returnMethod, factory.createPropertyAccessExpression(iterator, "return"))), factory.createExpressionStatement(factory.createFunctionCallCall(returnMethod, iterator, []))), 1 /* SingleLine */),
89889                 ]), 
89890                 /*catchClause*/ undefined, 
89891                 /*finallyBlock*/ ts.setEmitFlags(factory.createBlock([
89892                     ts.setEmitFlags(factory.createIfStatement(errorRecord, factory.createThrowStatement(factory.createPropertyAccessExpression(errorRecord, "error"))), 1 /* SingleLine */)
89893                 ]), 1 /* SingleLine */))
89894             ]));
89895         }
89896         /**
89897          * Visits an ObjectLiteralExpression with computed property names.
89898          *
89899          * @param node An ObjectLiteralExpression node.
89900          */
89901         function visitObjectLiteralExpression(node) {
89902             var properties = node.properties;
89903             // Find the first computed property.
89904             // Everything until that point can be emitted as part of the initial object literal.
89905             var numInitialProperties = -1, hasComputed = false;
89906             for (var i = 0; i < properties.length; i++) {
89907                 var property = properties[i];
89908                 if ((property.transformFlags & 262144 /* ContainsYield */ &&
89909                     hierarchyFacts & 4 /* AsyncFunctionBody */)
89910                     || (hasComputed = ts.Debug.checkDefined(property.name).kind === 158 /* ComputedPropertyName */)) {
89911                     numInitialProperties = i;
89912                     break;
89913                 }
89914             }
89915             if (numInitialProperties < 0) {
89916                 return ts.visitEachChild(node, visitor, context);
89917             }
89918             // For computed properties, we need to create a unique handle to the object
89919             // literal so we can modify it without risking internal assignments tainting the object.
89920             var temp = factory.createTempVariable(hoistVariableDeclaration);
89921             // Write out the first non-computed properties, then emit the rest through indexing on the temp variable.
89922             var expressions = [];
89923             var assignment = factory.createAssignment(temp, ts.setEmitFlags(factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), node.multiLine), hasComputed ? 65536 /* Indented */ : 0));
89924             if (node.multiLine) {
89925                 ts.startOnNewLine(assignment);
89926             }
89927             expressions.push(assignment);
89928             addObjectLiteralMembers(expressions, node, temp, numInitialProperties);
89929             // We need to clone the temporary identifier so that we can write it on a
89930             // new line
89931             expressions.push(node.multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
89932             return factory.inlineExpressions(expressions);
89933         }
89934         function shouldConvertPartOfIterationStatement(node) {
89935             return (resolver.getNodeCheckFlags(node) & 131072 /* ContainsCapturedBlockScopeBinding */) !== 0;
89936         }
89937         function shouldConvertInitializerOfForStatement(node) {
89938             return ts.isForStatement(node) && !!node.initializer && shouldConvertPartOfIterationStatement(node.initializer);
89939         }
89940         function shouldConvertConditionOfForStatement(node) {
89941             return ts.isForStatement(node) && !!node.condition && shouldConvertPartOfIterationStatement(node.condition);
89942         }
89943         function shouldConvertIncrementorOfForStatement(node) {
89944             return ts.isForStatement(node) && !!node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
89945         }
89946         function shouldConvertIterationStatement(node) {
89947             return shouldConvertBodyOfIterationStatement(node)
89948                 || shouldConvertInitializerOfForStatement(node);
89949         }
89950         function shouldConvertBodyOfIterationStatement(node) {
89951             return (resolver.getNodeCheckFlags(node) & 65536 /* LoopWithCapturedBlockScopedBinding */) !== 0;
89952         }
89953         /**
89954          * Records constituents of name for the given variable to be hoisted in the outer scope.
89955          */
89956         function hoistVariableDeclarationDeclaredInConvertedLoop(state, node) {
89957             if (!state.hoistedLocalVariables) {
89958                 state.hoistedLocalVariables = [];
89959             }
89960             visit(node.name);
89961             function visit(node) {
89962                 if (node.kind === 78 /* Identifier */) {
89963                     state.hoistedLocalVariables.push(node);
89964                 }
89965                 else {
89966                     for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
89967                         var element = _a[_i];
89968                         if (!ts.isOmittedExpression(element)) {
89969                             visit(element.name);
89970                         }
89971                     }
89972                 }
89973             }
89974         }
89975         function convertIterationStatementBodyIfNecessary(node, outermostLabeledStatement, ancestorFacts, convert) {
89976             if (!shouldConvertIterationStatement(node)) {
89977                 var saveAllowedNonLabeledJumps = void 0;
89978                 if (convertedLoopState) {
89979                     // we get here if we are trying to emit normal loop loop inside converted loop
89980                     // set allowedNonLabeledJumps to Break | Continue to mark that break\continue inside the loop should be emitted as is
89981                     saveAllowedNonLabeledJumps = convertedLoopState.allowedNonLabeledJumps;
89982                     convertedLoopState.allowedNonLabeledJumps = 2 /* Break */ | 4 /* Continue */;
89983                 }
89984                 var result = convert
89985                     ? convert(node, outermostLabeledStatement, /*convertedLoopBodyStatements*/ undefined, ancestorFacts)
89986                     : factory.restoreEnclosingLabel(ts.isForStatement(node) ? visitEachChildOfForStatement(node) : ts.visitEachChild(node, visitor, context), outermostLabeledStatement, convertedLoopState && resetLabel);
89987                 if (convertedLoopState) {
89988                     convertedLoopState.allowedNonLabeledJumps = saveAllowedNonLabeledJumps;
89989                 }
89990                 return result;
89991             }
89992             var currentState = createConvertedLoopState(node);
89993             var statements = [];
89994             var outerConvertedLoopState = convertedLoopState;
89995             convertedLoopState = currentState;
89996             var initializerFunction = shouldConvertInitializerOfForStatement(node) ? createFunctionForInitializerOfForStatement(node, currentState) : undefined;
89997             var bodyFunction = shouldConvertBodyOfIterationStatement(node) ? createFunctionForBodyOfIterationStatement(node, currentState, outerConvertedLoopState) : undefined;
89998             convertedLoopState = outerConvertedLoopState;
89999             if (initializerFunction)
90000                 statements.push(initializerFunction.functionDeclaration);
90001             if (bodyFunction)
90002                 statements.push(bodyFunction.functionDeclaration);
90003             addExtraDeclarationsForConvertedLoop(statements, currentState, outerConvertedLoopState);
90004             if (initializerFunction) {
90005                 statements.push(generateCallToConvertedLoopInitializer(initializerFunction.functionName, initializerFunction.containsYield));
90006             }
90007             var loop;
90008             if (bodyFunction) {
90009                 if (convert) {
90010                     loop = convert(node, outermostLabeledStatement, bodyFunction.part, ancestorFacts);
90011                 }
90012                 else {
90013                     var clone_3 = convertIterationStatementCore(node, initializerFunction, factory.createBlock(bodyFunction.part, /*multiLine*/ true));
90014                     loop = factory.restoreEnclosingLabel(clone_3, outermostLabeledStatement, convertedLoopState && resetLabel);
90015                 }
90016             }
90017             else {
90018                 var clone_4 = convertIterationStatementCore(node, initializerFunction, ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
90019                 loop = factory.restoreEnclosingLabel(clone_4, outermostLabeledStatement, convertedLoopState && resetLabel);
90020             }
90021             statements.push(loop);
90022             return statements;
90023         }
90024         function convertIterationStatementCore(node, initializerFunction, convertedLoopBody) {
90025             switch (node.kind) {
90026                 case 237 /* ForStatement */: return convertForStatement(node, initializerFunction, convertedLoopBody);
90027                 case 238 /* ForInStatement */: return convertForInStatement(node, convertedLoopBody);
90028                 case 239 /* ForOfStatement */: return convertForOfStatement(node, convertedLoopBody);
90029                 case 235 /* DoStatement */: return convertDoStatement(node, convertedLoopBody);
90030                 case 236 /* WhileStatement */: return convertWhileStatement(node, convertedLoopBody);
90031                 default: return ts.Debug.failBadSyntaxKind(node, "IterationStatement expected");
90032             }
90033         }
90034         function convertForStatement(node, initializerFunction, convertedLoopBody) {
90035             var shouldConvertCondition = node.condition && shouldConvertPartOfIterationStatement(node.condition);
90036             var shouldConvertIncrementor = shouldConvertCondition || node.incrementor && shouldConvertPartOfIterationStatement(node.incrementor);
90037             return factory.updateForStatement(node, ts.visitNode(initializerFunction ? initializerFunction.part : node.initializer, visitorWithUnusedExpressionResult, ts.isForInitializer), ts.visitNode(shouldConvertCondition ? undefined : node.condition, visitor, ts.isExpression), ts.visitNode(shouldConvertIncrementor ? undefined : node.incrementor, visitorWithUnusedExpressionResult, ts.isExpression), convertedLoopBody);
90038         }
90039         function convertForOfStatement(node, convertedLoopBody) {
90040             return factory.updateForOfStatement(node, 
90041             /*awaitModifier*/ undefined, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
90042         }
90043         function convertForInStatement(node, convertedLoopBody) {
90044             return factory.updateForInStatement(node, ts.visitNode(node.initializer, visitor, ts.isForInitializer), ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
90045         }
90046         function convertDoStatement(node, convertedLoopBody) {
90047             return factory.updateDoStatement(node, convertedLoopBody, ts.visitNode(node.expression, visitor, ts.isExpression));
90048         }
90049         function convertWhileStatement(node, convertedLoopBody) {
90050             return factory.updateWhileStatement(node, ts.visitNode(node.expression, visitor, ts.isExpression), convertedLoopBody);
90051         }
90052         function createConvertedLoopState(node) {
90053             var loopInitializer;
90054             switch (node.kind) {
90055                 case 237 /* ForStatement */:
90056                 case 238 /* ForInStatement */:
90057                 case 239 /* ForOfStatement */:
90058                     var initializer = node.initializer;
90059                     if (initializer && initializer.kind === 250 /* VariableDeclarationList */) {
90060                         loopInitializer = initializer;
90061                     }
90062                     break;
90063             }
90064             // variables that will be passed to the loop as parameters
90065             var loopParameters = [];
90066             // variables declared in the loop initializer that will be changed inside the loop
90067             var loopOutParameters = [];
90068             if (loopInitializer && (ts.getCombinedNodeFlags(loopInitializer) & 3 /* BlockScoped */)) {
90069                 var hasCapturedBindingsInForInitializer = shouldConvertInitializerOfForStatement(node);
90070                 for (var _i = 0, _a = loopInitializer.declarations; _i < _a.length; _i++) {
90071                     var decl = _a[_i];
90072                     processLoopVariableDeclaration(node, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
90073                 }
90074             }
90075             var currentState = { loopParameters: loopParameters, loopOutParameters: loopOutParameters };
90076             if (convertedLoopState) {
90077                 // convertedOuterLoopState !== undefined means that this converted loop is nested in another converted loop.
90078                 // if outer converted loop has already accumulated some state - pass it through
90079                 if (convertedLoopState.argumentsName) {
90080                     // outer loop has already used 'arguments' so we've already have some name to alias it
90081                     // use the same name in all nested loops
90082                     currentState.argumentsName = convertedLoopState.argumentsName;
90083                 }
90084                 if (convertedLoopState.thisName) {
90085                     // outer loop has already used 'this' so we've already have some name to alias it
90086                     // use the same name in all nested loops
90087                     currentState.thisName = convertedLoopState.thisName;
90088                 }
90089                 if (convertedLoopState.hoistedLocalVariables) {
90090                     // we've already collected some non-block scoped variable declarations in enclosing loop
90091                     // use the same storage in nested loop
90092                     currentState.hoistedLocalVariables = convertedLoopState.hoistedLocalVariables;
90093                 }
90094             }
90095             return currentState;
90096         }
90097         function addExtraDeclarationsForConvertedLoop(statements, state, outerState) {
90098             var extraVariableDeclarations;
90099             // propagate state from the inner loop to the outer loop if necessary
90100             if (state.argumentsName) {
90101                 // if alias for arguments is set
90102                 if (outerState) {
90103                     // pass it to outer converted loop
90104                     outerState.argumentsName = state.argumentsName;
90105                 }
90106                 else {
90107                     // this is top level converted loop and we need to create an alias for 'arguments' object
90108                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.argumentsName, 
90109                     /*exclamationToken*/ undefined, 
90110                     /*type*/ undefined, factory.createIdentifier("arguments")));
90111                 }
90112             }
90113             if (state.thisName) {
90114                 // if alias for this is set
90115                 if (outerState) {
90116                     // pass it to outer converted loop
90117                     outerState.thisName = state.thisName;
90118                 }
90119                 else {
90120                     // this is top level converted loop so we need to create an alias for 'this' here
90121                     // NOTE:
90122                     // if converted loops were all nested in arrow function then we'll always emit '_this' so convertedLoopState.thisName will not be set.
90123                     // If it is set this means that all nested loops are not nested in arrow function and it is safe to capture 'this'.
90124                     (extraVariableDeclarations || (extraVariableDeclarations = [])).push(factory.createVariableDeclaration(state.thisName, 
90125                     /*exclamationToken*/ undefined, 
90126                     /*type*/ undefined, factory.createIdentifier("this")));
90127                 }
90128             }
90129             if (state.hoistedLocalVariables) {
90130                 // if hoistedLocalVariables !== undefined this means that we've possibly collected some variable declarations to be hoisted later
90131                 if (outerState) {
90132                     // pass them to outer converted loop
90133                     outerState.hoistedLocalVariables = state.hoistedLocalVariables;
90134                 }
90135                 else {
90136                     if (!extraVariableDeclarations) {
90137                         extraVariableDeclarations = [];
90138                     }
90139                     // hoist collected variable declarations
90140                     for (var _i = 0, _a = state.hoistedLocalVariables; _i < _a.length; _i++) {
90141                         var identifier = _a[_i];
90142                         extraVariableDeclarations.push(factory.createVariableDeclaration(identifier));
90143                     }
90144                 }
90145             }
90146             // add extra variables to hold out parameters if necessary
90147             if (state.loopOutParameters.length) {
90148                 if (!extraVariableDeclarations) {
90149                     extraVariableDeclarations = [];
90150                 }
90151                 for (var _b = 0, _c = state.loopOutParameters; _b < _c.length; _b++) {
90152                     var outParam = _c[_b];
90153                     extraVariableDeclarations.push(factory.createVariableDeclaration(outParam.outParamName));
90154                 }
90155             }
90156             if (state.conditionVariable) {
90157                 if (!extraVariableDeclarations) {
90158                     extraVariableDeclarations = [];
90159                 }
90160                 extraVariableDeclarations.push(factory.createVariableDeclaration(state.conditionVariable, /*exclamationToken*/ undefined, /*type*/ undefined, factory.createFalse()));
90161             }
90162             // create variable statement to hold all introduced variable declarations
90163             if (extraVariableDeclarations) {
90164                 statements.push(factory.createVariableStatement(
90165                 /*modifiers*/ undefined, factory.createVariableDeclarationList(extraVariableDeclarations)));
90166             }
90167         }
90168         function createOutVariable(p) {
90169             return factory.createVariableDeclaration(p.originalName, /*exclamationToken*/ undefined, /*type*/ undefined, p.outParamName);
90170         }
90171         /**
90172          * Creates a `_loop_init` function for a `ForStatement` with a block-scoped initializer
90173          * that is captured in a closure inside of the initializer. The `_loop_init` function is
90174          * used to preserve the per-iteration environment semantics of
90175          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
90176          */
90177         function createFunctionForInitializerOfForStatement(node, currentState) {
90178             var functionName = factory.createUniqueName("_loop_init");
90179             var containsYield = (node.initializer.transformFlags & 262144 /* ContainsYield */) !== 0;
90180             var emitFlags = 0 /* None */;
90181             if (currentState.containsLexicalThis)
90182                 emitFlags |= 8 /* CapturesThis */;
90183             if (containsYield && hierarchyFacts & 4 /* AsyncFunctionBody */)
90184                 emitFlags |= 262144 /* AsyncFunctionBody */;
90185             var statements = [];
90186             statements.push(factory.createVariableStatement(/*modifiers*/ undefined, node.initializer));
90187             copyOutParameters(currentState.loopOutParameters, 2 /* Initializer */, 1 /* ToOutParameter */, statements);
90188             // This transforms the following ES2015 syntax:
90189             //
90190             //  for (let i = (setImmediate(() => console.log(i)), 0); i < 2; i++) {
90191             //      // loop body
90192             //  }
90193             //
90194             // Into the following ES5 syntax:
90195             //
90196             //  var _loop_init_1 = function () {
90197             //      var i = (setImmediate(() => console.log(i)), 0);
90198             //      out_i_1 = i;
90199             //  };
90200             //  var out_i_1;
90201             //  _loop_init_1();
90202             //  for (var i = out_i_1; i < 2; i++) {
90203             //      // loop body
90204             //  }
90205             //
90206             // Which prevents mutations to `i` in the per-iteration environment of the body
90207             // from affecting the initial value for `i` outside of the per-iteration environment.
90208             var functionDeclaration = factory.createVariableStatement(
90209             /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
90210                 factory.createVariableDeclaration(functionName, 
90211                 /*exclamationToken*/ undefined, 
90212                 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
90213                 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined, 
90214                 /*name*/ undefined, 
90215                 /*typeParameters*/ undefined, 
90216                 /*parameters*/ undefined, 
90217                 /*type*/ undefined, ts.visitNode(factory.createBlock(statements, /*multiLine*/ true), visitor, ts.isBlock)), emitFlags))
90218             ]), 2097152 /* NoHoisting */));
90219             var part = factory.createVariableDeclarationList(ts.map(currentState.loopOutParameters, createOutVariable));
90220             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
90221         }
90222         /**
90223          * Creates a `_loop` function for an `IterationStatement` with a block-scoped initializer
90224          * that is captured in a closure inside of the loop body. The `_loop` function is used to
90225          * preserve the per-iteration environment semantics of
90226          * [13.7.4.8 RS: ForBodyEvaluation](https://tc39.github.io/ecma262/#sec-forbodyevaluation).
90227          */
90228         function createFunctionForBodyOfIterationStatement(node, currentState, outerState) {
90229             var functionName = factory.createUniqueName("_loop");
90230             startLexicalEnvironment();
90231             var statement = ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock);
90232             var lexicalEnvironment = endLexicalEnvironment();
90233             var statements = [];
90234             if (shouldConvertConditionOfForStatement(node) || shouldConvertIncrementorOfForStatement(node)) {
90235                 // If a block-scoped variable declared in the initializer of `node` is captured in
90236                 // the condition or incrementor, we must move the condition and incrementor into
90237                 // the body of the for loop.
90238                 //
90239                 // This transforms the following ES2015 syntax:
90240                 //
90241                 //  for (let i = 0; setImmediate(() => console.log(i)), i < 2; setImmediate(() => console.log(i)), i++) {
90242                 //      // loop body
90243                 //  }
90244                 //
90245                 // Into the following ES5 syntax:
90246                 //
90247                 //  var _loop_1 = function (i) {
90248                 //      if (inc_1)
90249                 //          setImmediate(() => console.log(i)), i++;
90250                 //      else
90251                 //          inc_1 = true;
90252                 //      if (!(setImmediate(() => console.log(i)), i < 2))
90253                 //          return out_i_1 = i, "break";
90254                 //      // loop body
90255                 //      out_i_1 = i;
90256                 //  }
90257                 //  var out_i_1, inc_1 = false;
90258                 //  for (var i = 0;;) {
90259                 //      var state_1 = _loop_1(i);
90260                 //      i = out_i_1;
90261                 //      if (state_1 === "break")
90262                 //          break;
90263                 //  }
90264                 //
90265                 // Which prevents mutations to `i` in the per-iteration environment of the body
90266                 // from affecting the value of `i` in the previous per-iteration environment.
90267                 //
90268                 // Note that the incrementor of a `for` loop is evaluated in a *new* per-iteration
90269                 // environment that is carried over to the next iteration of the loop. As a result,
90270                 // we must indicate whether this is the first evaluation of the loop body so that
90271                 // we only evaluate the incrementor on subsequent evaluations.
90272                 currentState.conditionVariable = factory.createUniqueName("inc");
90273                 if (node.incrementor) {
90274                     statements.push(factory.createIfStatement(currentState.conditionVariable, factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
90275                 }
90276                 else {
90277                     statements.push(factory.createIfStatement(factory.createLogicalNot(currentState.conditionVariable), factory.createExpressionStatement(factory.createAssignment(currentState.conditionVariable, factory.createTrue()))));
90278                 }
90279                 if (shouldConvertConditionOfForStatement(node)) {
90280                     statements.push(factory.createIfStatement(factory.createPrefixUnaryExpression(53 /* ExclamationToken */, ts.visitNode(node.condition, visitor, ts.isExpression)), ts.visitNode(factory.createBreakStatement(), visitor, ts.isStatement)));
90281                 }
90282             }
90283             if (ts.isBlock(statement)) {
90284                 ts.addRange(statements, statement.statements);
90285             }
90286             else {
90287                 statements.push(statement);
90288             }
90289             copyOutParameters(currentState.loopOutParameters, 1 /* Body */, 1 /* ToOutParameter */, statements);
90290             ts.insertStatementsAfterStandardPrologue(statements, lexicalEnvironment);
90291             var loopBody = factory.createBlock(statements, /*multiLine*/ true);
90292             if (ts.isBlock(statement))
90293                 ts.setOriginalNode(loopBody, statement);
90294             var containsYield = (node.statement.transformFlags & 262144 /* ContainsYield */) !== 0;
90295             var emitFlags = 0;
90296             if (currentState.containsLexicalThis)
90297                 emitFlags |= 8 /* CapturesThis */;
90298             if (containsYield && (hierarchyFacts & 4 /* AsyncFunctionBody */) !== 0)
90299                 emitFlags |= 262144 /* AsyncFunctionBody */;
90300             // This transforms the following ES2015 syntax (in addition to other variations):
90301             //
90302             //  for (let i = 0; i < 2; i++) {
90303             //      setImmediate(() => console.log(i));
90304             //  }
90305             //
90306             // Into the following ES5 syntax:
90307             //
90308             //  var _loop_1 = function (i) {
90309             //      setImmediate(() => console.log(i));
90310             //  };
90311             //  for (var i = 0; i < 2; i++) {
90312             //      _loop_1(i);
90313             //  }
90314             var functionDeclaration = factory.createVariableStatement(
90315             /*modifiers*/ undefined, ts.setEmitFlags(factory.createVariableDeclarationList([
90316                 factory.createVariableDeclaration(functionName, 
90317                 /*exclamationToken*/ undefined, 
90318                 /*type*/ undefined, ts.setEmitFlags(factory.createFunctionExpression(
90319                 /*modifiers*/ undefined, containsYield ? factory.createToken(41 /* AsteriskToken */) : undefined, 
90320                 /*name*/ undefined, 
90321                 /*typeParameters*/ undefined, currentState.loopParameters, 
90322                 /*type*/ undefined, loopBody), emitFlags))
90323             ]), 2097152 /* NoHoisting */));
90324             var part = generateCallToConvertedLoop(functionName, currentState, outerState, containsYield);
90325             return { functionName: functionName, containsYield: containsYield, functionDeclaration: functionDeclaration, part: part };
90326         }
90327         function copyOutParameter(outParam, copyDirection) {
90328             var source = copyDirection === 0 /* ToOriginal */ ? outParam.outParamName : outParam.originalName;
90329             var target = copyDirection === 0 /* ToOriginal */ ? outParam.originalName : outParam.outParamName;
90330             return factory.createBinaryExpression(target, 62 /* EqualsToken */, source);
90331         }
90332         function copyOutParameters(outParams, partFlags, copyDirection, statements) {
90333             for (var _i = 0, outParams_1 = outParams; _i < outParams_1.length; _i++) {
90334                 var outParam = outParams_1[_i];
90335                 if (outParam.flags & partFlags) {
90336                     statements.push(factory.createExpressionStatement(copyOutParameter(outParam, copyDirection)));
90337                 }
90338             }
90339         }
90340         function generateCallToConvertedLoopInitializer(initFunctionExpressionName, containsYield) {
90341             var call = factory.createCallExpression(initFunctionExpressionName, /*typeArguments*/ undefined, []);
90342             var callResult = containsYield
90343                 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
90344                 : call;
90345             return factory.createExpressionStatement(callResult);
90346         }
90347         function generateCallToConvertedLoop(loopFunctionExpressionName, state, outerState, containsYield) {
90348             var statements = [];
90349             // loop is considered simple if it does not have any return statements or break\continue that transfer control outside of the loop
90350             // simple loops are emitted as just 'loop()';
90351             // NOTE: if loop uses only 'continue' it still will be emitted as simple loop
90352             var isSimpleLoop = !(state.nonLocalJumps & ~4 /* Continue */) &&
90353                 !state.labeledNonLocalBreaks &&
90354                 !state.labeledNonLocalContinues;
90355             var call = factory.createCallExpression(loopFunctionExpressionName, /*typeArguments*/ undefined, ts.map(state.loopParameters, function (p) { return p.name; }));
90356             var callResult = containsYield
90357                 ? factory.createYieldExpression(factory.createToken(41 /* AsteriskToken */), ts.setEmitFlags(call, 8388608 /* Iterator */))
90358                 : call;
90359             if (isSimpleLoop) {
90360                 statements.push(factory.createExpressionStatement(callResult));
90361                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
90362             }
90363             else {
90364                 var loopResultName = factory.createUniqueName("state");
90365                 var stateVariable = factory.createVariableStatement(
90366                 /*modifiers*/ undefined, factory.createVariableDeclarationList([factory.createVariableDeclaration(loopResultName, /*exclamationToken*/ undefined, /*type*/ undefined, callResult)]));
90367                 statements.push(stateVariable);
90368                 copyOutParameters(state.loopOutParameters, 1 /* Body */, 0 /* ToOriginal */, statements);
90369                 if (state.nonLocalJumps & 8 /* Return */) {
90370                     var returnStatement = void 0;
90371                     if (outerState) {
90372                         outerState.nonLocalJumps |= 8 /* Return */;
90373                         returnStatement = factory.createReturnStatement(loopResultName);
90374                     }
90375                     else {
90376                         returnStatement = factory.createReturnStatement(factory.createPropertyAccessExpression(loopResultName, "value"));
90377                     }
90378                     statements.push(factory.createIfStatement(factory.createTypeCheck(loopResultName, "object"), returnStatement));
90379                 }
90380                 if (state.nonLocalJumps & 2 /* Break */) {
90381                     statements.push(factory.createIfStatement(factory.createStrictEquality(loopResultName, factory.createStringLiteral("break")), factory.createBreakStatement()));
90382                 }
90383                 if (state.labeledNonLocalBreaks || state.labeledNonLocalContinues) {
90384                     var caseClauses = [];
90385                     processLabeledJumps(state.labeledNonLocalBreaks, /*isBreak*/ true, loopResultName, outerState, caseClauses);
90386                     processLabeledJumps(state.labeledNonLocalContinues, /*isBreak*/ false, loopResultName, outerState, caseClauses);
90387                     statements.push(factory.createSwitchStatement(loopResultName, factory.createCaseBlock(caseClauses)));
90388                 }
90389             }
90390             return statements;
90391         }
90392         function setLabeledJump(state, isBreak, labelText, labelMarker) {
90393             if (isBreak) {
90394                 if (!state.labeledNonLocalBreaks) {
90395                     state.labeledNonLocalBreaks = new ts.Map();
90396                 }
90397                 state.labeledNonLocalBreaks.set(labelText, labelMarker);
90398             }
90399             else {
90400                 if (!state.labeledNonLocalContinues) {
90401                     state.labeledNonLocalContinues = new ts.Map();
90402                 }
90403                 state.labeledNonLocalContinues.set(labelText, labelMarker);
90404             }
90405         }
90406         function processLabeledJumps(table, isBreak, loopResultName, outerLoop, caseClauses) {
90407             if (!table) {
90408                 return;
90409             }
90410             table.forEach(function (labelMarker, labelText) {
90411                 var statements = [];
90412                 // if there are no outer converted loop or outer label in question is located inside outer converted loop
90413                 // then emit labeled break\continue
90414                 // otherwise propagate pair 'label -> marker' to outer converted loop and emit 'return labelMarker' so outer loop can later decide what to do
90415                 if (!outerLoop || (outerLoop.labels && outerLoop.labels.get(labelText))) {
90416                     var label = factory.createIdentifier(labelText);
90417                     statements.push(isBreak ? factory.createBreakStatement(label) : factory.createContinueStatement(label));
90418                 }
90419                 else {
90420                     setLabeledJump(outerLoop, isBreak, labelText, labelMarker);
90421                     statements.push(factory.createReturnStatement(loopResultName));
90422                 }
90423                 caseClauses.push(factory.createCaseClause(factory.createStringLiteral(labelMarker), statements));
90424             });
90425         }
90426         function processLoopVariableDeclaration(container, decl, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer) {
90427             var name = decl.name;
90428             if (ts.isBindingPattern(name)) {
90429                 for (var _i = 0, _a = name.elements; _i < _a.length; _i++) {
90430                     var element = _a[_i];
90431                     if (!ts.isOmittedExpression(element)) {
90432                         processLoopVariableDeclaration(container, element, loopParameters, loopOutParameters, hasCapturedBindingsInForInitializer);
90433                     }
90434                 }
90435             }
90436             else {
90437                 loopParameters.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, name));
90438                 var checkFlags = resolver.getNodeCheckFlags(decl);
90439                 if (checkFlags & 4194304 /* NeedsLoopOutParameter */ || hasCapturedBindingsInForInitializer) {
90440                     var outParamName = factory.createUniqueName("out_" + ts.idText(name));
90441                     var flags = 0;
90442                     if (checkFlags & 4194304 /* NeedsLoopOutParameter */) {
90443                         flags |= 1 /* Body */;
90444                     }
90445                     if (ts.isForStatement(container) && container.initializer && resolver.isBindingCapturedByNode(container.initializer, decl)) {
90446                         flags |= 2 /* Initializer */;
90447                     }
90448                     loopOutParameters.push({ flags: flags, originalName: name, outParamName: outParamName });
90449                 }
90450             }
90451         }
90452         /**
90453          * Adds the members of an object literal to an array of expressions.
90454          *
90455          * @param expressions An array of expressions.
90456          * @param node An ObjectLiteralExpression node.
90457          * @param receiver The receiver for members of the ObjectLiteralExpression.
90458          * @param numInitialNonComputedProperties The number of initial properties without
90459          *                                        computed property names.
90460          */
90461         function addObjectLiteralMembers(expressions, node, receiver, start) {
90462             var properties = node.properties;
90463             var numProperties = properties.length;
90464             for (var i = start; i < numProperties; i++) {
90465                 var property = properties[i];
90466                 switch (property.kind) {
90467                     case 167 /* GetAccessor */:
90468                     case 168 /* SetAccessor */:
90469                         var accessors = ts.getAllAccessorDeclarations(node.properties, property);
90470                         if (property === accessors.firstAccessor) {
90471                             expressions.push(transformAccessorsToExpression(receiver, accessors, node, !!node.multiLine));
90472                         }
90473                         break;
90474                     case 165 /* MethodDeclaration */:
90475                         expressions.push(transformObjectLiteralMethodDeclarationToExpression(property, receiver, node, node.multiLine));
90476                         break;
90477                     case 288 /* PropertyAssignment */:
90478                         expressions.push(transformPropertyAssignmentToExpression(property, receiver, node.multiLine));
90479                         break;
90480                     case 289 /* ShorthandPropertyAssignment */:
90481                         expressions.push(transformShorthandPropertyAssignmentToExpression(property, receiver, node.multiLine));
90482                         break;
90483                     default:
90484                         ts.Debug.failBadSyntaxKind(node);
90485                         break;
90486                 }
90487             }
90488         }
90489         /**
90490          * Transforms a PropertyAssignment node into an expression.
90491          *
90492          * @param node The ObjectLiteralExpression that contains the PropertyAssignment.
90493          * @param property The PropertyAssignment node.
90494          * @param receiver The receiver for the assignment.
90495          */
90496         function transformPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
90497             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), ts.visitNode(property.initializer, visitor, ts.isExpression));
90498             ts.setTextRange(expression, property);
90499             if (startsOnNewLine) {
90500                 ts.startOnNewLine(expression);
90501             }
90502             return expression;
90503         }
90504         /**
90505          * Transforms a ShorthandPropertyAssignment node into an expression.
90506          *
90507          * @param node The ObjectLiteralExpression that contains the ShorthandPropertyAssignment.
90508          * @param property The ShorthandPropertyAssignment node.
90509          * @param receiver The receiver for the assignment.
90510          */
90511         function transformShorthandPropertyAssignmentToExpression(property, receiver, startsOnNewLine) {
90512             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(property.name, visitor, ts.isPropertyName)), factory.cloneNode(property.name));
90513             ts.setTextRange(expression, property);
90514             if (startsOnNewLine) {
90515                 ts.startOnNewLine(expression);
90516             }
90517             return expression;
90518         }
90519         /**
90520          * Transforms a MethodDeclaration of an ObjectLiteralExpression into an expression.
90521          *
90522          * @param node The ObjectLiteralExpression that contains the MethodDeclaration.
90523          * @param method The MethodDeclaration node.
90524          * @param receiver The receiver for the assignment.
90525          */
90526         function transformObjectLiteralMethodDeclarationToExpression(method, receiver, container, startsOnNewLine) {
90527             var expression = factory.createAssignment(ts.createMemberAccessForPropertyName(factory, receiver, ts.visitNode(method.name, visitor, ts.isPropertyName)), transformFunctionLikeToExpression(method, /*location*/ method, /*name*/ undefined, container));
90528             ts.setTextRange(expression, method);
90529             if (startsOnNewLine) {
90530                 ts.startOnNewLine(expression);
90531             }
90532             return expression;
90533         }
90534         function visitCatchClause(node) {
90535             var ancestorFacts = enterSubtree(7104 /* BlockScopeExcludes */, 0 /* BlockScopeIncludes */);
90536             var updated;
90537             ts.Debug.assert(!!node.variableDeclaration, "Catch clause variable should always be present when downleveling ES2015.");
90538             if (ts.isBindingPattern(node.variableDeclaration.name)) {
90539                 var temp = factory.createTempVariable(/*recordTempVariable*/ undefined);
90540                 var newVariableDeclaration = factory.createVariableDeclaration(temp);
90541                 ts.setTextRange(newVariableDeclaration, node.variableDeclaration);
90542                 var vars = ts.flattenDestructuringBinding(node.variableDeclaration, visitor, context, 0 /* All */, temp);
90543                 var list = factory.createVariableDeclarationList(vars);
90544                 ts.setTextRange(list, node.variableDeclaration);
90545                 var destructure = factory.createVariableStatement(/*modifiers*/ undefined, list);
90546                 updated = factory.updateCatchClause(node, newVariableDeclaration, addStatementToStartOfBlock(node.block, destructure));
90547             }
90548             else {
90549                 updated = ts.visitEachChild(node, visitor, context);
90550             }
90551             exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
90552             return updated;
90553         }
90554         function addStatementToStartOfBlock(block, statement) {
90555             var transformedStatements = ts.visitNodes(block.statements, visitor, ts.isStatement);
90556             return factory.updateBlock(block, __spreadArrays([statement], transformedStatements));
90557         }
90558         /**
90559          * Visits a MethodDeclaration of an ObjectLiteralExpression and transforms it into a
90560          * PropertyAssignment.
90561          *
90562          * @param node A MethodDeclaration node.
90563          */
90564         function visitMethodDeclaration(node) {
90565             // We should only get here for methods on an object literal with regular identifier names.
90566             // Methods on classes are handled in visitClassDeclaration/visitClassExpression.
90567             // Methods with computed property names are handled in visitObjectLiteralExpression.
90568             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
90569             var functionExpression = transformFunctionLikeToExpression(node, /*location*/ ts.moveRangePos(node, -1), /*name*/ undefined, /*container*/ undefined);
90570             ts.setEmitFlags(functionExpression, 512 /* NoLeadingComments */ | ts.getEmitFlags(functionExpression));
90571             return ts.setTextRange(factory.createPropertyAssignment(node.name, functionExpression), 
90572             /*location*/ node);
90573         }
90574         /**
90575          * Visits an AccessorDeclaration of an ObjectLiteralExpression.
90576          *
90577          * @param node An AccessorDeclaration node.
90578          */
90579         function visitAccessorDeclaration(node) {
90580             ts.Debug.assert(!ts.isComputedPropertyName(node.name));
90581             var savedConvertedLoopState = convertedLoopState;
90582             convertedLoopState = undefined;
90583             var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, 65 /* FunctionIncludes */);
90584             var updated;
90585             var parameters = ts.visitParameterList(node.parameters, visitor, context);
90586             var body = transformFunctionBody(node);
90587             if (node.kind === 167 /* GetAccessor */) {
90588                 updated = factory.updateGetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, node.type, body);
90589             }
90590             else {
90591                 updated = factory.updateSetAccessorDeclaration(node, node.decorators, node.modifiers, node.name, parameters, body);
90592             }
90593             exitSubtree(ancestorFacts, 49152 /* FunctionSubtreeExcludes */, 0 /* None */);
90594             convertedLoopState = savedConvertedLoopState;
90595             return updated;
90596         }
90597         /**
90598          * Visits a ShorthandPropertyAssignment and transforms it into a PropertyAssignment.
90599          *
90600          * @param node A ShorthandPropertyAssignment node.
90601          */
90602         function visitShorthandPropertyAssignment(node) {
90603             return ts.setTextRange(factory.createPropertyAssignment(node.name, visitIdentifier(factory.cloneNode(node.name))), 
90604             /*location*/ node);
90605         }
90606         function visitComputedPropertyName(node) {
90607             return ts.visitEachChild(node, visitor, context);
90608         }
90609         /**
90610          * Visits a YieldExpression node.
90611          *
90612          * @param node A YieldExpression node.
90613          */
90614         function visitYieldExpression(node) {
90615             // `yield` expressions are transformed using the generators transformer.
90616             return ts.visitEachChild(node, visitor, context);
90617         }
90618         /**
90619          * Visits an ArrayLiteralExpression that contains a spread element.
90620          *
90621          * @param node An ArrayLiteralExpression node.
90622          */
90623         function visitArrayLiteralExpression(node) {
90624             if (ts.some(node.elements, ts.isSpreadElement)) {
90625                 // We are here because we contain a SpreadElementExpression.
90626                 return transformAndSpreadElements(node.elements, /*needsUniqueCopy*/ true, !!node.multiLine, /*hasTrailingComma*/ !!node.elements.hasTrailingComma);
90627             }
90628             return ts.visitEachChild(node, visitor, context);
90629         }
90630         /**
90631          * Visits a CallExpression that contains either a spread element or `super`.
90632          *
90633          * @param node a CallExpression.
90634          */
90635         function visitCallExpression(node) {
90636             if (ts.getEmitFlags(node) & 33554432 /* TypeScriptClassWrapper */) {
90637                 return visitTypeScriptClassWrapper(node);
90638             }
90639             var expression = ts.skipOuterExpressions(node.expression);
90640             if (expression.kind === 105 /* SuperKeyword */ ||
90641                 ts.isSuperProperty(expression) ||
90642                 ts.some(node.arguments, ts.isSpreadElement)) {
90643                 return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ true);
90644             }
90645             return factory.updateCallExpression(node, ts.visitNode(node.expression, callExpressionVisitor, ts.isExpression), 
90646             /*typeArguments*/ undefined, ts.visitNodes(node.arguments, visitor, ts.isExpression));
90647         }
90648         function visitTypeScriptClassWrapper(node) {
90649             // This is a call to a class wrapper function (an IIFE) created by the 'ts' transformer.
90650             // The wrapper has a form similar to:
90651             //
90652             //  (function() {
90653             //      class C { // 1
90654             //      }
90655             //      C.x = 1; // 2
90656             //      return C;
90657             //  }())
90658             //
90659             // When we transform the class, we end up with something like this:
90660             //
90661             //  (function () {
90662             //      var C = (function () { // 3
90663             //          function C() {
90664             //          }
90665             //          return C; // 4
90666             //      }());
90667             //      C.x = 1;
90668             //      return C;
90669             //  }())
90670             //
90671             // We want to simplify the two nested IIFEs to end up with something like this:
90672             //
90673             //  (function () {
90674             //      function C() {
90675             //      }
90676             //      C.x = 1;
90677             //      return C;
90678             //  }())
90679             // We skip any outer expressions in a number of places to get to the innermost
90680             // expression, but we will restore them later to preserve comments and source maps.
90681             var body = ts.cast(ts.cast(ts.skipOuterExpressions(node.expression), ts.isArrowFunction).body, ts.isBlock);
90682             // The class statements are the statements generated by visiting the first statement with initializer of the
90683             // body (1), while all other statements are added to remainingStatements (2)
90684             var isVariableStatementWithInitializer = function (stmt) { return ts.isVariableStatement(stmt) && !!ts.first(stmt.declarationList.declarations).initializer; };
90685             // visit the class body statements outside of any converted loop body.
90686             var savedConvertedLoopState = convertedLoopState;
90687             convertedLoopState = undefined;
90688             var bodyStatements = ts.visitNodes(body.statements, visitor, ts.isStatement);
90689             convertedLoopState = savedConvertedLoopState;
90690             var classStatements = ts.filter(bodyStatements, isVariableStatementWithInitializer);
90691             var remainingStatements = ts.filter(bodyStatements, function (stmt) { return !isVariableStatementWithInitializer(stmt); });
90692             var varStatement = ts.cast(ts.first(classStatements), ts.isVariableStatement);
90693             // We know there is only one variable declaration here as we verified this in an
90694             // earlier call to isTypeScriptClassWrapper
90695             var variable = varStatement.declarationList.declarations[0];
90696             var initializer = ts.skipOuterExpressions(variable.initializer);
90697             // Under certain conditions, the 'ts' transformer may introduce a class alias, which
90698             // we see as an assignment, for example:
90699             //
90700             //  (function () {
90701             //      var C_1;
90702             //      var C = C_1 = (function () {
90703             //          function C() {
90704             //          }
90705             //          C.x = function () { return C_1; }
90706             //          return C;
90707             //      }());
90708             //      C = C_1 = __decorate([dec], C);
90709             //      return C;
90710             //  }())
90711             //
90712             var aliasAssignment = ts.tryCast(initializer, ts.isAssignmentExpression);
90713             // The underlying call (3) is another IIFE that may contain a '_super' argument.
90714             var call = ts.cast(aliasAssignment ? ts.skipOuterExpressions(aliasAssignment.right) : initializer, ts.isCallExpression);
90715             var func = ts.cast(ts.skipOuterExpressions(call.expression), ts.isFunctionExpression);
90716             var funcStatements = func.body.statements;
90717             var classBodyStart = 0;
90718             var classBodyEnd = -1;
90719             var statements = [];
90720             if (aliasAssignment) {
90721                 // If we have a class alias assignment, we need to move it to the down-level constructor
90722                 // function we generated for the class.
90723                 var extendsCall = ts.tryCast(funcStatements[classBodyStart], ts.isExpressionStatement);
90724                 if (extendsCall) {
90725                     statements.push(extendsCall);
90726                     classBodyStart++;
90727                 }
90728                 // The next statement is the function declaration.
90729                 statements.push(funcStatements[classBodyStart]);
90730                 classBodyStart++;
90731                 // Add the class alias following the declaration.
90732                 statements.push(factory.createExpressionStatement(factory.createAssignment(aliasAssignment.left, ts.cast(variable.name, ts.isIdentifier))));
90733             }
90734             // Find the trailing 'return' statement (4)
90735             while (!ts.isReturnStatement(ts.elementAt(funcStatements, classBodyEnd))) {
90736                 classBodyEnd--;
90737             }
90738             // When we extract the statements of the inner IIFE, we exclude the 'return' statement (4)
90739             // as we already have one that has been introduced by the 'ts' transformer.
90740             ts.addRange(statements, funcStatements, classBodyStart, classBodyEnd);
90741             if (classBodyEnd < -1) {
90742                 // If there were any hoisted declarations following the return statement, we should
90743                 // append them.
90744                 ts.addRange(statements, funcStatements, classBodyEnd + 1);
90745             }
90746             // Add the remaining statements of the outer wrapper.
90747             ts.addRange(statements, remainingStatements);
90748             // The 'es2015' class transform may add an end-of-declaration marker. If so we will add it
90749             // after the remaining statements from the 'ts' transformer.
90750             ts.addRange(statements, classStatements, /*start*/ 1);
90751             // Recreate any outer parentheses or partially-emitted expressions to preserve source map
90752             // and comment locations.
90753             return factory.restoreOuterExpressions(node.expression, factory.restoreOuterExpressions(variable.initializer, factory.restoreOuterExpressions(aliasAssignment && aliasAssignment.right, factory.updateCallExpression(call, factory.restoreOuterExpressions(call.expression, factory.updateFunctionExpression(func, 
90754             /*modifiers*/ undefined, 
90755             /*asteriskToken*/ undefined, 
90756             /*name*/ undefined, 
90757             /*typeParameters*/ undefined, func.parameters, 
90758             /*type*/ undefined, factory.updateBlock(func.body, statements))), 
90759             /*typeArguments*/ undefined, call.arguments))));
90760         }
90761         function visitImmediateSuperCallInBody(node) {
90762             return visitCallExpressionWithPotentialCapturedThisAssignment(node, /*assignToCapturedThis*/ false);
90763         }
90764         function visitCallExpressionWithPotentialCapturedThisAssignment(node, assignToCapturedThis) {
90765             // We are here either because SuperKeyword was used somewhere in the expression, or
90766             // because we contain a SpreadElementExpression.
90767             if (node.transformFlags & 8192 /* ContainsRestOrSpread */ ||
90768                 node.expression.kind === 105 /* SuperKeyword */ ||
90769                 ts.isSuperProperty(ts.skipOuterExpressions(node.expression))) {
90770                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
90771                 if (node.expression.kind === 105 /* SuperKeyword */) {
90772                     ts.setEmitFlags(thisArg, 4 /* NoSubstitution */);
90773                 }
90774                 var resultingCall = void 0;
90775                 if (node.transformFlags & 8192 /* ContainsRestOrSpread */) {
90776                     // [source]
90777                     //      f(...a, b)
90778                     //      x.m(...a, b)
90779                     //      super(...a, b)
90780                     //      super.m(...a, b) // in static
90781                     //      super.m(...a, b) // in instance
90782                     //
90783                     // [output]
90784                     //      f.apply(void 0, a.concat([b]))
90785                     //      (_a = x).m.apply(_a, a.concat([b]))
90786                     //      _super.apply(this, a.concat([b]))
90787                     //      _super.m.apply(this, a.concat([b]))
90788                     //      _super.prototype.m.apply(this, a.concat([b]))
90789                     resultingCall = factory.createFunctionApplyCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 105 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), transformAndSpreadElements(node.arguments, /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false));
90790                 }
90791                 else {
90792                     // [source]
90793                     //      super(a)
90794                     //      super.m(a) // in static
90795                     //      super.m(a) // in instance
90796                     //
90797                     // [output]
90798                     //      _super.call(this, a)
90799                     //      _super.m.call(this, a)
90800                     //      _super.prototype.m.call(this, a)
90801                     resultingCall = ts.setTextRange(factory.createFunctionCallCall(ts.visitNode(target, callExpressionVisitor, ts.isExpression), node.expression.kind === 105 /* SuperKeyword */ ? thisArg : ts.visitNode(thisArg, visitor, ts.isExpression), ts.visitNodes(node.arguments, visitor, ts.isExpression)), node);
90802                 }
90803                 if (node.expression.kind === 105 /* SuperKeyword */) {
90804                     var initializer = factory.createLogicalOr(resultingCall, createActualThis());
90805                     resultingCall = assignToCapturedThis
90806                         ? factory.createAssignment(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), initializer)
90807                         : initializer;
90808                 }
90809                 return ts.setOriginalNode(resultingCall, node);
90810             }
90811             return ts.visitEachChild(node, visitor, context);
90812         }
90813         /**
90814          * Visits a NewExpression that contains a spread element.
90815          *
90816          * @param node A NewExpression node.
90817          */
90818         function visitNewExpression(node) {
90819             if (ts.some(node.arguments, ts.isSpreadElement)) {
90820                 // We are here because we contain a SpreadElementExpression.
90821                 // [source]
90822                 //      new C(...a)
90823                 //
90824                 // [output]
90825                 //      new ((_a = C).bind.apply(_a, [void 0].concat(a)))()
90826                 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
90827                 return factory.createNewExpression(factory.createFunctionApplyCall(ts.visitNode(target, visitor, ts.isExpression), thisArg, transformAndSpreadElements(factory.createNodeArray(__spreadArrays([factory.createVoidZero()], node.arguments)), /*needsUniqueCopy*/ false, /*multiLine*/ false, /*hasTrailingComma*/ false)), 
90828                 /*typeArguments*/ undefined, []);
90829             }
90830             return ts.visitEachChild(node, visitor, context);
90831         }
90832         /**
90833          * Transforms an array of Expression nodes that contains a SpreadExpression.
90834          *
90835          * @param elements The array of Expression nodes.
90836          * @param needsUniqueCopy A value indicating whether to ensure that the result is a fresh array.
90837          * @param multiLine A value indicating whether the result should be emitted on multiple lines.
90838          */
90839         function transformAndSpreadElements(elements, needsUniqueCopy, multiLine, hasTrailingComma) {
90840             // [source]
90841             //      [a, ...b, c]
90842             //
90843             // [output (downlevelIteration)]
90844             //      __spread([a], b, [c])
90845             //
90846             // [output]
90847             //      __spreadArrays([a], b, [c])
90848             // Map spans of spread expressions into their expressions and spans of other
90849             // expressions into an array literal.
90850             var numElements = elements.length;
90851             var segments = ts.flatten(ts.spanMap(elements, partitionSpread, function (partition, visitPartition, _start, end) {
90852                 return visitPartition(partition, multiLine, hasTrailingComma && end === numElements);
90853             }));
90854             if (compilerOptions.downlevelIteration) {
90855                 if (segments.length === 1) {
90856                     var firstSegment = segments[0];
90857                     if (isCallToHelper(firstSegment, "___spread")) {
90858                         return segments[0];
90859                     }
90860                 }
90861                 return emitHelpers().createSpreadHelper(segments);
90862             }
90863             else {
90864                 if (segments.length === 1) {
90865                     var firstSegment = segments[0];
90866                     if (!needsUniqueCopy
90867                         || isPackedArrayLiteral(firstSegment)
90868                         || isCallToHelper(firstSegment, "___spreadArrays")) {
90869                         return segments[0];
90870                     }
90871                 }
90872                 return emitHelpers().createSpreadArraysHelper(segments);
90873             }
90874         }
90875         function isPackedElement(node) {
90876             return !ts.isOmittedExpression(node);
90877         }
90878         function isPackedArrayLiteral(node) {
90879             return ts.isArrayLiteralExpression(node) && ts.every(node.elements, isPackedElement);
90880         }
90881         function isCallToHelper(firstSegment, helperName) {
90882             return ts.isCallExpression(firstSegment)
90883                 && ts.isIdentifier(firstSegment.expression)
90884                 && (ts.getEmitFlags(firstSegment.expression) & 4096 /* HelperName */)
90885                 && firstSegment.expression.escapedText === helperName;
90886         }
90887         function partitionSpread(node) {
90888             return ts.isSpreadElement(node)
90889                 ? visitSpanOfSpreads
90890                 : visitSpanOfNonSpreads;
90891         }
90892         function visitSpanOfSpreads(chunk) {
90893             return ts.map(chunk, visitExpressionOfSpread);
90894         }
90895         function visitSpanOfNonSpreads(chunk, multiLine, hasTrailingComma) {
90896             return factory.createArrayLiteralExpression(ts.visitNodes(factory.createNodeArray(chunk, hasTrailingComma), visitor, ts.isExpression), multiLine);
90897         }
90898         function visitSpreadElement(node) {
90899             return ts.visitNode(node.expression, visitor, ts.isExpression);
90900         }
90901         /**
90902          * Transforms the expression of a SpreadExpression node.
90903          *
90904          * @param node A SpreadExpression node.
90905          */
90906         function visitExpressionOfSpread(node) {
90907             return ts.visitNode(node.expression, visitor, ts.isExpression);
90908         }
90909         /**
90910          * Visits a template literal.
90911          *
90912          * @param node A template literal.
90913          */
90914         function visitTemplateLiteral(node) {
90915             return ts.setTextRange(factory.createStringLiteral(node.text), node);
90916         }
90917         /**
90918          * Visits a string literal with an extended unicode escape.
90919          *
90920          * @param node A string literal.
90921          */
90922         function visitStringLiteral(node) {
90923             if (node.hasExtendedUnicodeEscape) {
90924                 return ts.setTextRange(factory.createStringLiteral(node.text), node);
90925             }
90926             return node;
90927         }
90928         /**
90929          * Visits a binary or octal (ES6) numeric literal.
90930          *
90931          * @param node A string literal.
90932          */
90933         function visitNumericLiteral(node) {
90934             if (node.numericLiteralFlags & 384 /* BinaryOrOctalSpecifier */) {
90935                 return ts.setTextRange(factory.createNumericLiteral(node.text), node);
90936             }
90937             return node;
90938         }
90939         /**
90940          * Visits a TaggedTemplateExpression node.
90941          *
90942          * @param node A TaggedTemplateExpression node.
90943          */
90944         function visitTaggedTemplateExpression(node) {
90945             return ts.processTaggedTemplateExpression(context, node, visitor, currentSourceFile, recordTaggedTemplateString, ts.ProcessLevel.All);
90946         }
90947         /**
90948          * Visits a TemplateExpression node.
90949          *
90950          * @param node A TemplateExpression node.
90951          */
90952         function visitTemplateExpression(node) {
90953             var expressions = [];
90954             addTemplateHead(expressions, node);
90955             addTemplateSpans(expressions, node);
90956             // createAdd will check if each expression binds less closely than binary '+'.
90957             // If it does, it wraps the expression in parentheses. Otherwise, something like
90958             //    `abc${ 1 << 2 }`
90959             // becomes
90960             //    "abc" + 1 << 2 + ""
90961             // which is really
90962             //    ("abc" + 1) << (2 + "")
90963             // rather than
90964             //    "abc" + (1 << 2) + ""
90965             var expression = ts.reduceLeft(expressions, factory.createAdd);
90966             if (ts.nodeIsSynthesized(expression)) {
90967                 ts.setTextRange(expression, node);
90968             }
90969             return expression;
90970         }
90971         /**
90972          * Gets a value indicating whether we need to include the head of a TemplateExpression.
90973          *
90974          * @param node A TemplateExpression node.
90975          */
90976         function shouldAddTemplateHead(node) {
90977             // If this expression has an empty head literal and the first template span has a non-empty
90978             // literal, then emitting the empty head literal is not necessary.
90979             //     `${ foo } and ${ bar }`
90980             // can be emitted as
90981             //     foo + " and " + bar
90982             // This is because it is only required that one of the first two operands in the emit
90983             // output must be a string literal, so that the other operand and all following operands
90984             // are forced into strings.
90985             //
90986             // If the first template span has an empty literal, then the head must still be emitted.
90987             //     `${ foo }${ bar }`
90988             // must still be emitted as
90989             //     "" + foo + bar
90990             // There is always atleast one templateSpan in this code path, since
90991             // NoSubstitutionTemplateLiterals are directly emitted via emitLiteral()
90992             ts.Debug.assert(node.templateSpans.length !== 0);
90993             return node.head.text.length !== 0 || node.templateSpans[0].literal.text.length === 0;
90994         }
90995         /**
90996          * Adds the head of a TemplateExpression to an array of expressions.
90997          *
90998          * @param expressions An array of expressions.
90999          * @param node A TemplateExpression node.
91000          */
91001         function addTemplateHead(expressions, node) {
91002             if (!shouldAddTemplateHead(node)) {
91003                 return;
91004             }
91005             expressions.push(factory.createStringLiteral(node.head.text));
91006         }
91007         /**
91008          * Visits and adds the template spans of a TemplateExpression to an array of expressions.
91009          *
91010          * @param expressions An array of expressions.
91011          * @param node A TemplateExpression node.
91012          */
91013         function addTemplateSpans(expressions, node) {
91014             for (var _i = 0, _a = node.templateSpans; _i < _a.length; _i++) {
91015                 var span = _a[_i];
91016                 expressions.push(ts.visitNode(span.expression, visitor, ts.isExpression));
91017                 // Only emit if the literal is non-empty.
91018                 // The binary '+' operator is left-associative, so the first string concatenation
91019                 // with the head will force the result up to this point to be a string.
91020                 // Emitting a '+ ""' has no semantic effect for middles and tails.
91021                 if (span.literal.text.length !== 0) {
91022                     expressions.push(factory.createStringLiteral(span.literal.text));
91023                 }
91024             }
91025         }
91026         /**
91027          * Visits the `super` keyword
91028          */
91029         function visitSuperKeyword(isExpressionOfCall) {
91030             return hierarchyFacts & 8 /* NonStaticClassElement */
91031                 && !isExpressionOfCall
91032                 ? factory.createPropertyAccessExpression(factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */), "prototype")
91033                 : factory.createUniqueName("_super", 16 /* Optimistic */ | 32 /* FileLevel */);
91034         }
91035         function visitMetaProperty(node) {
91036             if (node.keywordToken === 102 /* NewKeyword */ && node.name.escapedText === "target") {
91037                 hierarchyFacts |= 16384 /* NewTarget */;
91038                 return factory.createUniqueName("_newTarget", 16 /* Optimistic */ | 32 /* FileLevel */);
91039             }
91040             return node;
91041         }
91042         /**
91043          * Called by the printer just before a node is printed.
91044          *
91045          * @param hint A hint as to the intended usage of the node.
91046          * @param node The node to be printed.
91047          * @param emitCallback The callback used to emit the node.
91048          */
91049         function onEmitNode(hint, node, emitCallback) {
91050             if (enabledSubstitutions & 1 /* CapturedThis */ && ts.isFunctionLike(node)) {
91051                 // If we are tracking a captured `this`, keep track of the enclosing function.
91052                 var ancestorFacts = enterSubtree(16286 /* FunctionExcludes */, ts.getEmitFlags(node) & 8 /* CapturesThis */
91053                     ? 65 /* FunctionIncludes */ | 16 /* CapturesThis */
91054                     : 65 /* FunctionIncludes */);
91055                 previousOnEmitNode(hint, node, emitCallback);
91056                 exitSubtree(ancestorFacts, 0 /* None */, 0 /* None */);
91057                 return;
91058             }
91059             previousOnEmitNode(hint, node, emitCallback);
91060         }
91061         /**
91062          * Enables a more costly code path for substitutions when we determine a source file
91063          * contains block-scoped bindings (e.g. `let` or `const`).
91064          */
91065         function enableSubstitutionsForBlockScopedBindings() {
91066             if ((enabledSubstitutions & 2 /* BlockScopedBindings */) === 0) {
91067                 enabledSubstitutions |= 2 /* BlockScopedBindings */;
91068                 context.enableSubstitution(78 /* Identifier */);
91069             }
91070         }
91071         /**
91072          * Enables a more costly code path for substitutions when we determine a source file
91073          * contains a captured `this`.
91074          */
91075         function enableSubstitutionsForCapturedThis() {
91076             if ((enabledSubstitutions & 1 /* CapturedThis */) === 0) {
91077                 enabledSubstitutions |= 1 /* CapturedThis */;
91078                 context.enableSubstitution(107 /* ThisKeyword */);
91079                 context.enableEmitNotification(166 /* Constructor */);
91080                 context.enableEmitNotification(165 /* MethodDeclaration */);
91081                 context.enableEmitNotification(167 /* GetAccessor */);
91082                 context.enableEmitNotification(168 /* SetAccessor */);
91083                 context.enableEmitNotification(209 /* ArrowFunction */);
91084                 context.enableEmitNotification(208 /* FunctionExpression */);
91085                 context.enableEmitNotification(251 /* FunctionDeclaration */);
91086             }
91087         }
91088         /**
91089          * Hooks node substitutions.
91090          *
91091          * @param hint The context for the emitter.
91092          * @param node The node to substitute.
91093          */
91094         function onSubstituteNode(hint, node) {
91095             node = previousOnSubstituteNode(hint, node);
91096             if (hint === 1 /* Expression */) {
91097                 return substituteExpression(node);
91098             }
91099             if (ts.isIdentifier(node)) {
91100                 return substituteIdentifier(node);
91101             }
91102             return node;
91103         }
91104         /**
91105          * Hooks substitutions for non-expression identifiers.
91106          */
91107         function substituteIdentifier(node) {
91108             // Only substitute the identifier if we have enabled substitutions for block-scoped
91109             // bindings.
91110             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
91111                 var original = ts.getParseTreeNode(node, ts.isIdentifier);
91112                 if (original && isNameOfDeclarationWithCollidingName(original)) {
91113                     return ts.setTextRange(factory.getGeneratedNameForNode(original), node);
91114                 }
91115             }
91116             return node;
91117         }
91118         /**
91119          * Determines whether a name is the name of a declaration with a colliding name.
91120          * NOTE: This function expects to be called with an original source tree node.
91121          *
91122          * @param node An original source tree node.
91123          */
91124         function isNameOfDeclarationWithCollidingName(node) {
91125             switch (node.parent.kind) {
91126                 case 198 /* BindingElement */:
91127                 case 252 /* ClassDeclaration */:
91128                 case 255 /* EnumDeclaration */:
91129                 case 249 /* VariableDeclaration */:
91130                     return node.parent.name === node
91131                         && resolver.isDeclarationWithCollidingName(node.parent);
91132             }
91133             return false;
91134         }
91135         /**
91136          * Substitutes an expression.
91137          *
91138          * @param node An Expression node.
91139          */
91140         function substituteExpression(node) {
91141             switch (node.kind) {
91142                 case 78 /* Identifier */:
91143                     return substituteExpressionIdentifier(node);
91144                 case 107 /* ThisKeyword */:
91145                     return substituteThisKeyword(node);
91146             }
91147             return node;
91148         }
91149         /**
91150          * Substitutes an expression identifier.
91151          *
91152          * @param node An Identifier node.
91153          */
91154         function substituteExpressionIdentifier(node) {
91155             if (enabledSubstitutions & 2 /* BlockScopedBindings */ && !ts.isInternalName(node)) {
91156                 var declaration = resolver.getReferencedDeclarationWithCollidingName(node);
91157                 if (declaration && !(ts.isClassLike(declaration) && isPartOfClassBody(declaration, node))) {
91158                     return ts.setTextRange(factory.getGeneratedNameForNode(ts.getNameOfDeclaration(declaration)), node);
91159                 }
91160             }
91161             return node;
91162         }
91163         function isPartOfClassBody(declaration, node) {
91164             var currentNode = ts.getParseTreeNode(node);
91165             if (!currentNode || currentNode === declaration || currentNode.end <= declaration.pos || currentNode.pos >= declaration.end) {
91166                 // if the node has no correlation to a parse tree node, its definitely not
91167                 // part of the body.
91168                 // if the node is outside of the document range of the declaration, its
91169                 // definitely not part of the body.
91170                 return false;
91171             }
91172             var blockScope = ts.getEnclosingBlockScopeContainer(declaration);
91173             while (currentNode) {
91174                 if (currentNode === blockScope || currentNode === declaration) {
91175                     // if we are in the enclosing block scope of the declaration, we are definitely
91176                     // not inside the class body.
91177                     return false;
91178                 }
91179                 if (ts.isClassElement(currentNode) && currentNode.parent === declaration) {
91180                     return true;
91181                 }
91182                 currentNode = currentNode.parent;
91183             }
91184             return false;
91185         }
91186         /**
91187          * Substitutes `this` when contained within an arrow function.
91188          *
91189          * @param node The ThisKeyword node.
91190          */
91191         function substituteThisKeyword(node) {
91192             if (enabledSubstitutions & 1 /* CapturedThis */
91193                 && hierarchyFacts & 16 /* CapturesThis */) {
91194                 return ts.setTextRange(factory.createUniqueName("_this", 16 /* Optimistic */ | 32 /* FileLevel */), node);
91195             }
91196             return node;
91197         }
91198         function getClassMemberPrefix(node, member) {
91199             return ts.hasSyntacticModifier(member, 32 /* Static */)
91200                 ? factory.getInternalName(node)
91201                 : factory.createPropertyAccessExpression(factory.getInternalName(node), "prototype");
91202         }
91203         function hasSynthesizedDefaultSuperCall(constructor, hasExtendsClause) {
91204             if (!constructor || !hasExtendsClause) {
91205                 return false;
91206             }
91207             if (ts.some(constructor.parameters)) {
91208                 return false;
91209             }
91210             var statement = ts.firstOrUndefined(constructor.body.statements);
91211             if (!statement || !ts.nodeIsSynthesized(statement) || statement.kind !== 233 /* ExpressionStatement */) {
91212                 return false;
91213             }
91214             var statementExpression = statement.expression;
91215             if (!ts.nodeIsSynthesized(statementExpression) || statementExpression.kind !== 203 /* CallExpression */) {
91216                 return false;
91217             }
91218             var callTarget = statementExpression.expression;
91219             if (!ts.nodeIsSynthesized(callTarget) || callTarget.kind !== 105 /* SuperKeyword */) {
91220                 return false;
91221             }
91222             var callArgument = ts.singleOrUndefined(statementExpression.arguments);
91223             if (!callArgument || !ts.nodeIsSynthesized(callArgument) || callArgument.kind !== 220 /* SpreadElement */) {
91224                 return false;
91225             }
91226             var expression = callArgument.expression;
91227             return ts.isIdentifier(expression) && expression.escapedText === "arguments";
91228         }
91229     }
91230     ts.transformES2015 = transformES2015;
91231 })(ts || (ts = {}));
91232 /*@internal*/
91233 var ts;
91234 (function (ts) {
91235     /**
91236      * Transforms ES5 syntax into ES3 syntax.
91237      *
91238      * @param context Context and state information for the transformation.
91239      */
91240     function transformES5(context) {
91241         var factory = context.factory;
91242         var compilerOptions = context.getCompilerOptions();
91243         // enable emit notification only if using --jsx preserve or react-native
91244         var previousOnEmitNode;
91245         var noSubstitution;
91246         if (compilerOptions.jsx === 1 /* Preserve */ || compilerOptions.jsx === 3 /* ReactNative */) {
91247             previousOnEmitNode = context.onEmitNode;
91248             context.onEmitNode = onEmitNode;
91249             context.enableEmitNotification(275 /* JsxOpeningElement */);
91250             context.enableEmitNotification(276 /* JsxClosingElement */);
91251             context.enableEmitNotification(274 /* JsxSelfClosingElement */);
91252             noSubstitution = [];
91253         }
91254         var previousOnSubstituteNode = context.onSubstituteNode;
91255         context.onSubstituteNode = onSubstituteNode;
91256         context.enableSubstitution(201 /* PropertyAccessExpression */);
91257         context.enableSubstitution(288 /* PropertyAssignment */);
91258         return ts.chainBundle(context, transformSourceFile);
91259         /**
91260          * Transforms an ES5 source file to ES3.
91261          *
91262          * @param node A SourceFile
91263          */
91264         function transformSourceFile(node) {
91265             return node;
91266         }
91267         /**
91268          * Called by the printer just before a node is printed.
91269          *
91270          * @param hint A hint as to the intended usage of the node.
91271          * @param node The node to emit.
91272          * @param emitCallback A callback used to emit the node.
91273          */
91274         function onEmitNode(hint, node, emitCallback) {
91275             switch (node.kind) {
91276                 case 275 /* JsxOpeningElement */:
91277                 case 276 /* JsxClosingElement */:
91278                 case 274 /* JsxSelfClosingElement */:
91279                     var tagName = node.tagName;
91280                     noSubstitution[ts.getOriginalNodeId(tagName)] = true;
91281                     break;
91282             }
91283             previousOnEmitNode(hint, node, emitCallback);
91284         }
91285         /**
91286          * Hooks node substitutions.
91287          *
91288          * @param hint A hint as to the intended usage of the node.
91289          * @param node The node to substitute.
91290          */
91291         function onSubstituteNode(hint, node) {
91292             if (node.id && noSubstitution && noSubstitution[node.id]) {
91293                 return previousOnSubstituteNode(hint, node);
91294             }
91295             node = previousOnSubstituteNode(hint, node);
91296             if (ts.isPropertyAccessExpression(node)) {
91297                 return substitutePropertyAccessExpression(node);
91298             }
91299             else if (ts.isPropertyAssignment(node)) {
91300                 return substitutePropertyAssignment(node);
91301             }
91302             return node;
91303         }
91304         /**
91305          * Substitutes a PropertyAccessExpression whose name is a reserved word.
91306          *
91307          * @param node A PropertyAccessExpression
91308          */
91309         function substitutePropertyAccessExpression(node) {
91310             if (ts.isPrivateIdentifier(node.name)) {
91311                 return node;
91312             }
91313             var literalName = trySubstituteReservedName(node.name);
91314             if (literalName) {
91315                 return ts.setTextRange(factory.createElementAccessExpression(node.expression, literalName), node);
91316             }
91317             return node;
91318         }
91319         /**
91320          * Substitutes a PropertyAssignment whose name is a reserved word.
91321          *
91322          * @param node A PropertyAssignment
91323          */
91324         function substitutePropertyAssignment(node) {
91325             var literalName = ts.isIdentifier(node.name) && trySubstituteReservedName(node.name);
91326             if (literalName) {
91327                 return factory.updatePropertyAssignment(node, literalName, node.initializer);
91328             }
91329             return node;
91330         }
91331         /**
91332          * If an identifier name is a reserved word, returns a string literal for the name.
91333          *
91334          * @param name An Identifier
91335          */
91336         function trySubstituteReservedName(name) {
91337             var token = name.originalKeywordKind || (ts.nodeIsSynthesized(name) ? ts.stringToToken(ts.idText(name)) : undefined);
91338             if (token !== undefined && token >= 80 /* FirstReservedWord */ && token <= 115 /* LastReservedWord */) {
91339                 return ts.setTextRange(factory.createStringLiteralFromNode(name), name);
91340             }
91341             return undefined;
91342         }
91343     }
91344     ts.transformES5 = transformES5;
91345 })(ts || (ts = {}));
91346 // Transforms generator functions into a compatible ES5 representation with similar runtime
91347 // semantics. This is accomplished by first transforming the body of each generator
91348 // function into an intermediate representation that is the compiled into a JavaScript
91349 // switch statement.
91350 //
91351 // Many functions in this transformer will contain comments indicating the expected
91352 // intermediate representation. For illustrative purposes, the following intermediate
91353 // language is used to define this intermediate representation:
91354 //
91355 //  .nop                            - Performs no operation.
91356 //  .local NAME, ...                - Define local variable declarations.
91357 //  .mark LABEL                     - Mark the location of a label.
91358 //  .br LABEL                       - Jump to a label. If jumping out of a protected
91359 //                                    region, all .finally blocks are executed.
91360 //  .brtrue LABEL, (x)              - Jump to a label IIF the expression `x` is truthy.
91361 //                                    If jumping out of a protected region, all .finally
91362 //                                    blocks are executed.
91363 //  .brfalse LABEL, (x)             - Jump to a label IIF the expression `x` is falsey.
91364 //                                    If jumping out of a protected region, all .finally
91365 //                                    blocks are executed.
91366 //  .yield (x)                      - Yield the value of the optional expression `x`.
91367 //                                    Resume at the next label.
91368 //  .yieldstar (x)                  - Delegate yield to the value of the optional
91369 //                                    expression `x`. Resume at the next label.
91370 //                                    NOTE: `x` must be an Iterator, not an Iterable.
91371 //  .loop CONTINUE, BREAK           - Marks the beginning of a loop. Any "continue" or
91372 //                                    "break" abrupt completions jump to the CONTINUE or
91373 //                                    BREAK labels, respectively.
91374 //  .endloop                        - Marks the end of a loop.
91375 //  .with (x)                       - Marks the beginning of a WithStatement block, using
91376 //                                    the supplied expression.
91377 //  .endwith                        - Marks the end of a WithStatement.
91378 //  .switch                         - Marks the beginning of a SwitchStatement.
91379 //  .endswitch                      - Marks the end of a SwitchStatement.
91380 //  .labeled NAME                   - Marks the beginning of a LabeledStatement with the
91381 //                                    supplied name.
91382 //  .endlabeled                     - Marks the end of a LabeledStatement.
91383 //  .try TRY, CATCH, FINALLY, END   - Marks the beginning of a protected region, and the
91384 //                                    labels for each block.
91385 //  .catch (x)                      - Marks the beginning of a catch block.
91386 //  .finally                        - Marks the beginning of a finally block.
91387 //  .endfinally                     - Marks the end of a finally block.
91388 //  .endtry                         - Marks the end of a protected region.
91389 //  .throw (x)                      - Throws the value of the expression `x`.
91390 //  .return (x)                     - Returns the value of the expression `x`.
91391 //
91392 // In addition, the illustrative intermediate representation introduces some special
91393 // variables:
91394 //
91395 //  %sent%                          - Either returns the next value sent to the generator,
91396 //                                    returns the result of a delegated yield, or throws
91397 //                                    the exception sent to the generator.
91398 //  %error%                         - Returns the value of the current exception in a
91399 //                                    catch block.
91400 //
91401 // This intermediate representation is then compiled into JavaScript syntax. The resulting
91402 // compilation output looks something like the following:
91403 //
91404 //  function f() {
91405 //      var /*locals*/;
91406 //      /*functions*/
91407 //      return __generator(function (state) {
91408 //          switch (state.label) {
91409 //              /*cases per label*/
91410 //          }
91411 //      });
91412 //  }
91413 //
91414 // Each of the above instructions corresponds to JavaScript emit similar to the following:
91415 //
91416 //  .local NAME                   | var NAME;
91417 // -------------------------------|----------------------------------------------
91418 //  .mark LABEL                   | case LABEL:
91419 // -------------------------------|----------------------------------------------
91420 //  .br LABEL                     |     return [3 /*break*/, LABEL];
91421 // -------------------------------|----------------------------------------------
91422 //  .brtrue LABEL, (x)            |     if (x) return [3 /*break*/, LABEL];
91423 // -------------------------------|----------------------------------------------
91424 //  .brfalse LABEL, (x)           |     if (!(x)) return [3, /*break*/, LABEL];
91425 // -------------------------------|----------------------------------------------
91426 //  .yield (x)                    |     return [4 /*yield*/, x];
91427 //  .mark RESUME                  | case RESUME:
91428 //      a = %sent%;               |     a = state.sent();
91429 // -------------------------------|----------------------------------------------
91430 //  .yieldstar (x)                |     return [5 /*yield**/, x];
91431 //  .mark RESUME                  | case RESUME:
91432 //      a = %sent%;               |     a = state.sent();
91433 // -------------------------------|----------------------------------------------
91434 //  .with (_a)                    |     with (_a) {
91435 //      a();                      |         a();
91436 //                                |     }
91437 //                                |     state.label = LABEL;
91438 //  .mark LABEL                   | case LABEL:
91439 //                                |     with (_a) {
91440 //      b();                      |         b();
91441 //                                |     }
91442 //  .endwith                      |
91443 // -------------------------------|----------------------------------------------
91444 //                                | case 0:
91445 //                                |     state.trys = [];
91446 //                                | ...
91447 //  .try TRY, CATCH, FINALLY, END |
91448 //  .mark TRY                     | case TRY:
91449 //                                |     state.trys.push([TRY, CATCH, FINALLY, END]);
91450 //  .nop                          |
91451 //      a();                      |     a();
91452 //  .br END                       |     return [3 /*break*/, END];
91453 //  .catch (e)                    |
91454 //  .mark CATCH                   | case CATCH:
91455 //                                |     e = state.sent();
91456 //      b();                      |     b();
91457 //  .br END                       |     return [3 /*break*/, END];
91458 //  .finally                      |
91459 //  .mark FINALLY                 | case FINALLY:
91460 //      c();                      |     c();
91461 //  .endfinally                   |     return [7 /*endfinally*/];
91462 //  .endtry                       |
91463 //  .mark END                     | case END:
91464 /*@internal*/
91465 var ts;
91466 (function (ts) {
91467     var OpCode;
91468     (function (OpCode) {
91469         OpCode[OpCode["Nop"] = 0] = "Nop";
91470         OpCode[OpCode["Statement"] = 1] = "Statement";
91471         OpCode[OpCode["Assign"] = 2] = "Assign";
91472         OpCode[OpCode["Break"] = 3] = "Break";
91473         OpCode[OpCode["BreakWhenTrue"] = 4] = "BreakWhenTrue";
91474         OpCode[OpCode["BreakWhenFalse"] = 5] = "BreakWhenFalse";
91475         OpCode[OpCode["Yield"] = 6] = "Yield";
91476         OpCode[OpCode["YieldStar"] = 7] = "YieldStar";
91477         OpCode[OpCode["Return"] = 8] = "Return";
91478         OpCode[OpCode["Throw"] = 9] = "Throw";
91479         OpCode[OpCode["Endfinally"] = 10] = "Endfinally"; // Marks the end of a `finally` block
91480     })(OpCode || (OpCode = {}));
91481     // whether a generated code block is opening or closing at the current operation for a FunctionBuilder
91482     var BlockAction;
91483     (function (BlockAction) {
91484         BlockAction[BlockAction["Open"] = 0] = "Open";
91485         BlockAction[BlockAction["Close"] = 1] = "Close";
91486     })(BlockAction || (BlockAction = {}));
91487     // the kind for a generated code block in a FunctionBuilder
91488     var CodeBlockKind;
91489     (function (CodeBlockKind) {
91490         CodeBlockKind[CodeBlockKind["Exception"] = 0] = "Exception";
91491         CodeBlockKind[CodeBlockKind["With"] = 1] = "With";
91492         CodeBlockKind[CodeBlockKind["Switch"] = 2] = "Switch";
91493         CodeBlockKind[CodeBlockKind["Loop"] = 3] = "Loop";
91494         CodeBlockKind[CodeBlockKind["Labeled"] = 4] = "Labeled";
91495     })(CodeBlockKind || (CodeBlockKind = {}));
91496     // the state for a generated code exception block
91497     var ExceptionBlockState;
91498     (function (ExceptionBlockState) {
91499         ExceptionBlockState[ExceptionBlockState["Try"] = 0] = "Try";
91500         ExceptionBlockState[ExceptionBlockState["Catch"] = 1] = "Catch";
91501         ExceptionBlockState[ExceptionBlockState["Finally"] = 2] = "Finally";
91502         ExceptionBlockState[ExceptionBlockState["Done"] = 3] = "Done";
91503     })(ExceptionBlockState || (ExceptionBlockState = {}));
91504     // NOTE: changes to this enum should be reflected in the __generator helper.
91505     var Instruction;
91506     (function (Instruction) {
91507         Instruction[Instruction["Next"] = 0] = "Next";
91508         Instruction[Instruction["Throw"] = 1] = "Throw";
91509         Instruction[Instruction["Return"] = 2] = "Return";
91510         Instruction[Instruction["Break"] = 3] = "Break";
91511         Instruction[Instruction["Yield"] = 4] = "Yield";
91512         Instruction[Instruction["YieldStar"] = 5] = "YieldStar";
91513         Instruction[Instruction["Catch"] = 6] = "Catch";
91514         Instruction[Instruction["Endfinally"] = 7] = "Endfinally";
91515     })(Instruction || (Instruction = {}));
91516     function getInstructionName(instruction) {
91517         switch (instruction) {
91518             case 2 /* Return */: return "return";
91519             case 3 /* Break */: return "break";
91520             case 4 /* Yield */: return "yield";
91521             case 5 /* YieldStar */: return "yield*";
91522             case 7 /* Endfinally */: return "endfinally";
91523             default: return undefined; // TODO: GH#18217
91524         }
91525     }
91526     function transformGenerators(context) {
91527         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, resumeLexicalEnvironment = context.resumeLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistFunctionDeclaration = context.hoistFunctionDeclaration, hoistVariableDeclaration = context.hoistVariableDeclaration;
91528         var compilerOptions = context.getCompilerOptions();
91529         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
91530         var resolver = context.getEmitResolver();
91531         var previousOnSubstituteNode = context.onSubstituteNode;
91532         context.onSubstituteNode = onSubstituteNode;
91533         var renamedCatchVariables;
91534         var renamedCatchVariableDeclarations;
91535         var inGeneratorFunctionBody;
91536         var inStatementContainingYield;
91537         // The following three arrays store information about generated code blocks.
91538         // All three arrays are correlated by their index. This approach is used over allocating
91539         // objects to store the same information to avoid GC overhead.
91540         //
91541         var blocks; // Information about the code block
91542         var blockOffsets; // The operation offset at which a code block begins or ends
91543         var blockActions; // Whether the code block is opened or closed
91544         var blockStack; // A stack of currently open code blocks
91545         // Labels are used to mark locations in the code that can be the target of a Break (jump)
91546         // operation. These are translated into case clauses in a switch statement.
91547         // The following two arrays are correlated by their index. This approach is used over
91548         // allocating objects to store the same information to avoid GC overhead.
91549         //
91550         var labelOffsets; // The operation offset at which the label is defined.
91551         var labelExpressions; // The NumericLiteral nodes bound to each label.
91552         var nextLabelId = 1; // The next label id to use.
91553         // Operations store information about generated code for the function body. This
91554         // Includes things like statements, assignments, breaks (jumps), and yields.
91555         // The following three arrays are correlated by their index. This approach is used over
91556         // allocating objects to store the same information to avoid GC overhead.
91557         //
91558         var operations; // The operation to perform.
91559         var operationArguments; // The arguments to the operation.
91560         var operationLocations; // The source map location for the operation.
91561         var state; // The name of the state object used by the generator at runtime.
91562         // The following variables store information used by the `build` function:
91563         //
91564         var blockIndex = 0; // The index of the current block.
91565         var labelNumber = 0; // The current label number.
91566         var labelNumbers;
91567         var lastOperationWasAbrupt; // Indicates whether the last operation was abrupt (break/continue).
91568         var lastOperationWasCompletion; // Indicates whether the last operation was a completion (return/throw).
91569         var clauses; // The case clauses generated for labels.
91570         var statements; // The statements for the current label.
91571         var exceptionBlockStack; // A stack of containing exception blocks.
91572         var currentExceptionBlock; // The current exception block.
91573         var withBlockStack; // A stack containing `with` blocks.
91574         return ts.chainBundle(context, transformSourceFile);
91575         function transformSourceFile(node) {
91576             if (node.isDeclarationFile || (node.transformFlags & 512 /* ContainsGenerator */) === 0) {
91577                 return node;
91578             }
91579             var visited = ts.visitEachChild(node, visitor, context);
91580             ts.addEmitHelpers(visited, context.readEmitHelpers());
91581             return visited;
91582         }
91583         /**
91584          * Visits a node.
91585          *
91586          * @param node The node to visit.
91587          */
91588         function visitor(node) {
91589             var transformFlags = node.transformFlags;
91590             if (inStatementContainingYield) {
91591                 return visitJavaScriptInStatementContainingYield(node);
91592             }
91593             else if (inGeneratorFunctionBody) {
91594                 return visitJavaScriptInGeneratorFunctionBody(node);
91595             }
91596             else if (ts.isFunctionLikeDeclaration(node) && node.asteriskToken) {
91597                 return visitGenerator(node);
91598             }
91599             else if (transformFlags & 512 /* ContainsGenerator */) {
91600                 return ts.visitEachChild(node, visitor, context);
91601             }
91602             else {
91603                 return node;
91604             }
91605         }
91606         /**
91607          * Visits a node that is contained within a statement that contains yield.
91608          *
91609          * @param node The node to visit.
91610          */
91611         function visitJavaScriptInStatementContainingYield(node) {
91612             switch (node.kind) {
91613                 case 235 /* DoStatement */:
91614                     return visitDoStatement(node);
91615                 case 236 /* WhileStatement */:
91616                     return visitWhileStatement(node);
91617                 case 244 /* SwitchStatement */:
91618                     return visitSwitchStatement(node);
91619                 case 245 /* LabeledStatement */:
91620                     return visitLabeledStatement(node);
91621                 default:
91622                     return visitJavaScriptInGeneratorFunctionBody(node);
91623             }
91624         }
91625         /**
91626          * Visits a node that is contained within a generator function.
91627          *
91628          * @param node The node to visit.
91629          */
91630         function visitJavaScriptInGeneratorFunctionBody(node) {
91631             switch (node.kind) {
91632                 case 251 /* FunctionDeclaration */:
91633                     return visitFunctionDeclaration(node);
91634                 case 208 /* FunctionExpression */:
91635                     return visitFunctionExpression(node);
91636                 case 167 /* GetAccessor */:
91637                 case 168 /* SetAccessor */:
91638                     return visitAccessorDeclaration(node);
91639                 case 232 /* VariableStatement */:
91640                     return visitVariableStatement(node);
91641                 case 237 /* ForStatement */:
91642                     return visitForStatement(node);
91643                 case 238 /* ForInStatement */:
91644                     return visitForInStatement(node);
91645                 case 241 /* BreakStatement */:
91646                     return visitBreakStatement(node);
91647                 case 240 /* ContinueStatement */:
91648                     return visitContinueStatement(node);
91649                 case 242 /* ReturnStatement */:
91650                     return visitReturnStatement(node);
91651                 default:
91652                     if (node.transformFlags & 262144 /* ContainsYield */) {
91653                         return visitJavaScriptContainingYield(node);
91654                     }
91655                     else if (node.transformFlags & (512 /* ContainsGenerator */ | 1048576 /* ContainsHoistedDeclarationOrCompletion */)) {
91656                         return ts.visitEachChild(node, visitor, context);
91657                     }
91658                     else {
91659                         return node;
91660                     }
91661             }
91662         }
91663         /**
91664          * Visits a node that contains a YieldExpression.
91665          *
91666          * @param node The node to visit.
91667          */
91668         function visitJavaScriptContainingYield(node) {
91669             switch (node.kind) {
91670                 case 216 /* BinaryExpression */:
91671                     return visitBinaryExpression(node);
91672                 case 337 /* CommaListExpression */:
91673                     return visitCommaListExpression(node);
91674                 case 217 /* ConditionalExpression */:
91675                     return visitConditionalExpression(node);
91676                 case 219 /* YieldExpression */:
91677                     return visitYieldExpression(node);
91678                 case 199 /* ArrayLiteralExpression */:
91679                     return visitArrayLiteralExpression(node);
91680                 case 200 /* ObjectLiteralExpression */:
91681                     return visitObjectLiteralExpression(node);
91682                 case 202 /* ElementAccessExpression */:
91683                     return visitElementAccessExpression(node);
91684                 case 203 /* CallExpression */:
91685                     return visitCallExpression(node);
91686                 case 204 /* NewExpression */:
91687                     return visitNewExpression(node);
91688                 default:
91689                     return ts.visitEachChild(node, visitor, context);
91690             }
91691         }
91692         /**
91693          * Visits a generator function.
91694          *
91695          * @param node The node to visit.
91696          */
91697         function visitGenerator(node) {
91698             switch (node.kind) {
91699                 case 251 /* FunctionDeclaration */:
91700                     return visitFunctionDeclaration(node);
91701                 case 208 /* FunctionExpression */:
91702                     return visitFunctionExpression(node);
91703                 default:
91704                     return ts.Debug.failBadSyntaxKind(node);
91705             }
91706         }
91707         /**
91708          * Visits a function declaration.
91709          *
91710          * This will be called when one of the following conditions are met:
91711          * - The function declaration is a generator function.
91712          * - The function declaration is contained within the body of a generator function.
91713          *
91714          * @param node The node to visit.
91715          */
91716         function visitFunctionDeclaration(node) {
91717             // Currently, we only support generators that were originally async functions.
91718             if (node.asteriskToken) {
91719                 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
91720                 /*decorators*/ undefined, node.modifiers, 
91721                 /*asteriskToken*/ undefined, node.name, 
91722                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
91723                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
91724                 /*location*/ node), node);
91725             }
91726             else {
91727                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
91728                 var savedInStatementContainingYield = inStatementContainingYield;
91729                 inGeneratorFunctionBody = false;
91730                 inStatementContainingYield = false;
91731                 node = ts.visitEachChild(node, visitor, context);
91732                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
91733                 inStatementContainingYield = savedInStatementContainingYield;
91734             }
91735             if (inGeneratorFunctionBody) {
91736                 // Function declarations in a generator function body are hoisted
91737                 // to the top of the lexical scope and elided from the current statement.
91738                 hoistFunctionDeclaration(node);
91739                 return undefined;
91740             }
91741             else {
91742                 return node;
91743             }
91744         }
91745         /**
91746          * Visits a function expression.
91747          *
91748          * This will be called when one of the following conditions are met:
91749          * - The function expression is a generator function.
91750          * - The function expression is contained within the body of a generator function.
91751          *
91752          * @param node The node to visit.
91753          */
91754         function visitFunctionExpression(node) {
91755             // Currently, we only support generators that were originally async functions.
91756             if (node.asteriskToken) {
91757                 node = ts.setOriginalNode(ts.setTextRange(factory.createFunctionExpression(
91758                 /*modifiers*/ undefined, 
91759                 /*asteriskToken*/ undefined, node.name, 
91760                 /*typeParameters*/ undefined, ts.visitParameterList(node.parameters, visitor, context), 
91761                 /*type*/ undefined, transformGeneratorFunctionBody(node.body)), 
91762                 /*location*/ node), node);
91763             }
91764             else {
91765                 var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
91766                 var savedInStatementContainingYield = inStatementContainingYield;
91767                 inGeneratorFunctionBody = false;
91768                 inStatementContainingYield = false;
91769                 node = ts.visitEachChild(node, visitor, context);
91770                 inGeneratorFunctionBody = savedInGeneratorFunctionBody;
91771                 inStatementContainingYield = savedInStatementContainingYield;
91772             }
91773             return node;
91774         }
91775         /**
91776          * Visits a get or set accessor declaration.
91777          *
91778          * This will be called when one of the following conditions are met:
91779          * - The accessor is contained within the body of a generator function.
91780          *
91781          * @param node The node to visit.
91782          */
91783         function visitAccessorDeclaration(node) {
91784             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
91785             var savedInStatementContainingYield = inStatementContainingYield;
91786             inGeneratorFunctionBody = false;
91787             inStatementContainingYield = false;
91788             node = ts.visitEachChild(node, visitor, context);
91789             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
91790             inStatementContainingYield = savedInStatementContainingYield;
91791             return node;
91792         }
91793         /**
91794          * Transforms the body of a generator function declaration.
91795          *
91796          * @param node The function body to transform.
91797          */
91798         function transformGeneratorFunctionBody(body) {
91799             // Save existing generator state
91800             var statements = [];
91801             var savedInGeneratorFunctionBody = inGeneratorFunctionBody;
91802             var savedInStatementContainingYield = inStatementContainingYield;
91803             var savedBlocks = blocks;
91804             var savedBlockOffsets = blockOffsets;
91805             var savedBlockActions = blockActions;
91806             var savedBlockStack = blockStack;
91807             var savedLabelOffsets = labelOffsets;
91808             var savedLabelExpressions = labelExpressions;
91809             var savedNextLabelId = nextLabelId;
91810             var savedOperations = operations;
91811             var savedOperationArguments = operationArguments;
91812             var savedOperationLocations = operationLocations;
91813             var savedState = state;
91814             // Initialize generator state
91815             inGeneratorFunctionBody = true;
91816             inStatementContainingYield = false;
91817             blocks = undefined;
91818             blockOffsets = undefined;
91819             blockActions = undefined;
91820             blockStack = undefined;
91821             labelOffsets = undefined;
91822             labelExpressions = undefined;
91823             nextLabelId = 1;
91824             operations = undefined;
91825             operationArguments = undefined;
91826             operationLocations = undefined;
91827             state = factory.createTempVariable(/*recordTempVariable*/ undefined);
91828             // Build the generator
91829             resumeLexicalEnvironment();
91830             var statementOffset = factory.copyPrologue(body.statements, statements, /*ensureUseStrict*/ false, visitor);
91831             transformAndEmitStatements(body.statements, statementOffset);
91832             var buildResult = build();
91833             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
91834             statements.push(factory.createReturnStatement(buildResult));
91835             // Restore previous generator state
91836             inGeneratorFunctionBody = savedInGeneratorFunctionBody;
91837             inStatementContainingYield = savedInStatementContainingYield;
91838             blocks = savedBlocks;
91839             blockOffsets = savedBlockOffsets;
91840             blockActions = savedBlockActions;
91841             blockStack = savedBlockStack;
91842             labelOffsets = savedLabelOffsets;
91843             labelExpressions = savedLabelExpressions;
91844             nextLabelId = savedNextLabelId;
91845             operations = savedOperations;
91846             operationArguments = savedOperationArguments;
91847             operationLocations = savedOperationLocations;
91848             state = savedState;
91849             return ts.setTextRange(factory.createBlock(statements, body.multiLine), body);
91850         }
91851         /**
91852          * Visits a variable statement.
91853          *
91854          * This will be called when one of the following conditions are met:
91855          * - The variable statement is contained within the body of a generator function.
91856          *
91857          * @param node The node to visit.
91858          */
91859         function visitVariableStatement(node) {
91860             if (node.transformFlags & 262144 /* ContainsYield */) {
91861                 transformAndEmitVariableDeclarationList(node.declarationList);
91862                 return undefined;
91863             }
91864             else {
91865                 // Do not hoist custom prologues.
91866                 if (ts.getEmitFlags(node) & 1048576 /* CustomPrologue */) {
91867                     return node;
91868                 }
91869                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
91870                     var variable = _a[_i];
91871                     hoistVariableDeclaration(variable.name);
91872                 }
91873                 var variables = ts.getInitializedVariables(node.declarationList);
91874                 if (variables.length === 0) {
91875                     return undefined;
91876                 }
91877                 return ts.setSourceMapRange(factory.createExpressionStatement(factory.inlineExpressions(ts.map(variables, transformInitializedVariable))), node);
91878             }
91879         }
91880         /**
91881          * Visits a binary expression.
91882          *
91883          * This will be called when one of the following conditions are met:
91884          * - The node contains a YieldExpression.
91885          *
91886          * @param node The node to visit.
91887          */
91888         function visitBinaryExpression(node) {
91889             var assoc = ts.getExpressionAssociativity(node);
91890             switch (assoc) {
91891                 case 0 /* Left */:
91892                     return visitLeftAssociativeBinaryExpression(node);
91893                 case 1 /* Right */:
91894                     return visitRightAssociativeBinaryExpression(node);
91895                 default:
91896                     return ts.Debug.assertNever(assoc);
91897             }
91898         }
91899         /**
91900          * Visits a right-associative binary expression containing `yield`.
91901          *
91902          * @param node The node to visit.
91903          */
91904         function visitRightAssociativeBinaryExpression(node) {
91905             var left = node.left, right = node.right;
91906             if (containsYield(right)) {
91907                 var target = void 0;
91908                 switch (left.kind) {
91909                     case 201 /* PropertyAccessExpression */:
91910                         // [source]
91911                         //      a.b = yield;
91912                         //
91913                         // [intermediate]
91914                         //  .local _a
91915                         //      _a = a;
91916                         //  .yield resumeLabel
91917                         //  .mark resumeLabel
91918                         //      _a.b = %sent%;
91919                         target = factory.updatePropertyAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), left.name);
91920                         break;
91921                     case 202 /* ElementAccessExpression */:
91922                         // [source]
91923                         //      a[b] = yield;
91924                         //
91925                         // [intermediate]
91926                         //  .local _a, _b
91927                         //      _a = a;
91928                         //      _b = b;
91929                         //  .yield resumeLabel
91930                         //  .mark resumeLabel
91931                         //      _a[_b] = %sent%;
91932                         target = factory.updateElementAccessExpression(left, cacheExpression(ts.visitNode(left.expression, visitor, ts.isLeftHandSideExpression)), cacheExpression(ts.visitNode(left.argumentExpression, visitor, ts.isExpression)));
91933                         break;
91934                     default:
91935                         target = ts.visitNode(left, visitor, ts.isExpression);
91936                         break;
91937                 }
91938                 var operator = node.operatorToken.kind;
91939                 if (ts.isCompoundAssignment(operator)) {
91940                     return ts.setTextRange(factory.createAssignment(target, ts.setTextRange(factory.createBinaryExpression(cacheExpression(target), ts.getNonAssignmentOperatorForCompoundAssignment(operator), ts.visitNode(right, visitor, ts.isExpression)), node)), node);
91941                 }
91942                 else {
91943                     return factory.updateBinaryExpression(node, target, node.operatorToken, ts.visitNode(right, visitor, ts.isExpression));
91944                 }
91945             }
91946             return ts.visitEachChild(node, visitor, context);
91947         }
91948         function visitLeftAssociativeBinaryExpression(node) {
91949             if (containsYield(node.right)) {
91950                 if (ts.isLogicalOperator(node.operatorToken.kind)) {
91951                     return visitLogicalBinaryExpression(node);
91952                 }
91953                 else if (node.operatorToken.kind === 27 /* CommaToken */) {
91954                     return visitCommaExpression(node);
91955                 }
91956                 // [source]
91957                 //      a() + (yield) + c()
91958                 //
91959                 // [intermediate]
91960                 //  .local _a
91961                 //      _a = a();
91962                 //  .yield resumeLabel
91963                 //      _a + %sent% + c()
91964                 return factory.updateBinaryExpression(node, cacheExpression(ts.visitNode(node.left, visitor, ts.isExpression)), node.operatorToken, ts.visitNode(node.right, visitor, ts.isExpression));
91965             }
91966             return ts.visitEachChild(node, visitor, context);
91967         }
91968         /**
91969          * Visits a comma expression containing `yield`.
91970          *
91971          * @param node The node to visit.
91972          */
91973         function visitCommaExpression(node) {
91974             // [source]
91975             //      x = a(), yield, b();
91976             //
91977             // [intermediate]
91978             //      a();
91979             //  .yield resumeLabel
91980             //  .mark resumeLabel
91981             //      x = %sent%, b();
91982             var pendingExpressions = [];
91983             visit(node.left);
91984             visit(node.right);
91985             return factory.inlineExpressions(pendingExpressions);
91986             function visit(node) {
91987                 if (ts.isBinaryExpression(node) && node.operatorToken.kind === 27 /* CommaToken */) {
91988                     visit(node.left);
91989                     visit(node.right);
91990                 }
91991                 else {
91992                     if (containsYield(node) && pendingExpressions.length > 0) {
91993                         emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
91994                         pendingExpressions = [];
91995                     }
91996                     pendingExpressions.push(ts.visitNode(node, visitor, ts.isExpression));
91997                 }
91998             }
91999         }
92000         /**
92001          * Visits a comma-list expression.
92002          *
92003          * @param node The node to visit.
92004          */
92005         function visitCommaListExpression(node) {
92006             // flattened version of `visitCommaExpression`
92007             var pendingExpressions = [];
92008             for (var _i = 0, _a = node.elements; _i < _a.length; _i++) {
92009                 var elem = _a[_i];
92010                 if (ts.isBinaryExpression(elem) && elem.operatorToken.kind === 27 /* CommaToken */) {
92011                     pendingExpressions.push(visitCommaExpression(elem));
92012                 }
92013                 else {
92014                     if (containsYield(elem) && pendingExpressions.length > 0) {
92015                         emitWorker(1 /* Statement */, [factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions))]);
92016                         pendingExpressions = [];
92017                     }
92018                     pendingExpressions.push(ts.visitNode(elem, visitor, ts.isExpression));
92019                 }
92020             }
92021             return factory.inlineExpressions(pendingExpressions);
92022         }
92023         /**
92024          * Visits a logical binary expression containing `yield`.
92025          *
92026          * @param node A node to visit.
92027          */
92028         function visitLogicalBinaryExpression(node) {
92029             // Logical binary expressions (`&&` and `||`) are shortcutting expressions and need
92030             // to be transformed as such:
92031             //
92032             // [source]
92033             //      x = a() && yield;
92034             //
92035             // [intermediate]
92036             //  .local _a
92037             //      _a = a();
92038             //  .brfalse resultLabel, (_a)
92039             //  .yield resumeLabel
92040             //  .mark resumeLabel
92041             //      _a = %sent%;
92042             //  .mark resultLabel
92043             //      x = _a;
92044             //
92045             // [source]
92046             //      x = a() || yield;
92047             //
92048             // [intermediate]
92049             //  .local _a
92050             //      _a = a();
92051             //  .brtrue resultLabel, (_a)
92052             //  .yield resumeLabel
92053             //  .mark resumeLabel
92054             //      _a = %sent%;
92055             //  .mark resultLabel
92056             //      x = _a;
92057             var resultLabel = defineLabel();
92058             var resultLocal = declareLocal();
92059             emitAssignment(resultLocal, ts.visitNode(node.left, visitor, ts.isExpression), /*location*/ node.left);
92060             if (node.operatorToken.kind === 55 /* AmpersandAmpersandToken */) {
92061                 // Logical `&&` shortcuts when the left-hand operand is falsey.
92062                 emitBreakWhenFalse(resultLabel, resultLocal, /*location*/ node.left);
92063             }
92064             else {
92065                 // Logical `||` shortcuts when the left-hand operand is truthy.
92066                 emitBreakWhenTrue(resultLabel, resultLocal, /*location*/ node.left);
92067             }
92068             emitAssignment(resultLocal, ts.visitNode(node.right, visitor, ts.isExpression), /*location*/ node.right);
92069             markLabel(resultLabel);
92070             return resultLocal;
92071         }
92072         /**
92073          * Visits a conditional expression containing `yield`.
92074          *
92075          * @param node The node to visit.
92076          */
92077         function visitConditionalExpression(node) {
92078             // [source]
92079             //      x = a() ? yield : b();
92080             //
92081             // [intermediate]
92082             //  .local _a
92083             //  .brfalse whenFalseLabel, (a())
92084             //  .yield resumeLabel
92085             //  .mark resumeLabel
92086             //      _a = %sent%;
92087             //  .br resultLabel
92088             //  .mark whenFalseLabel
92089             //      _a = b();
92090             //  .mark resultLabel
92091             //      x = _a;
92092             // We only need to perform a specific transformation if a `yield` expression exists
92093             // in either the `whenTrue` or `whenFalse` branches.
92094             // A `yield` in the condition will be handled by the normal visitor.
92095             if (containsYield(node.whenTrue) || containsYield(node.whenFalse)) {
92096                 var whenFalseLabel = defineLabel();
92097                 var resultLabel = defineLabel();
92098                 var resultLocal = declareLocal();
92099                 emitBreakWhenFalse(whenFalseLabel, ts.visitNode(node.condition, visitor, ts.isExpression), /*location*/ node.condition);
92100                 emitAssignment(resultLocal, ts.visitNode(node.whenTrue, visitor, ts.isExpression), /*location*/ node.whenTrue);
92101                 emitBreak(resultLabel);
92102                 markLabel(whenFalseLabel);
92103                 emitAssignment(resultLocal, ts.visitNode(node.whenFalse, visitor, ts.isExpression), /*location*/ node.whenFalse);
92104                 markLabel(resultLabel);
92105                 return resultLocal;
92106             }
92107             return ts.visitEachChild(node, visitor, context);
92108         }
92109         /**
92110          * Visits a `yield` expression.
92111          *
92112          * @param node The node to visit.
92113          */
92114         function visitYieldExpression(node) {
92115             // [source]
92116             //      x = yield a();
92117             //
92118             // [intermediate]
92119             //  .yield resumeLabel, (a())
92120             //  .mark resumeLabel
92121             //      x = %sent%;
92122             var resumeLabel = defineLabel();
92123             var expression = ts.visitNode(node.expression, visitor, ts.isExpression);
92124             if (node.asteriskToken) {
92125                 // NOTE: `expression` must be defined for `yield*`.
92126                 var iterator = (ts.getEmitFlags(node.expression) & 8388608 /* Iterator */) === 0
92127                     ? ts.setTextRange(emitHelpers().createValuesHelper(expression), node)
92128                     : expression;
92129                 emitYieldStar(iterator, /*location*/ node);
92130             }
92131             else {
92132                 emitYield(expression, /*location*/ node);
92133             }
92134             markLabel(resumeLabel);
92135             return createGeneratorResume(/*location*/ node);
92136         }
92137         /**
92138          * Visits an ArrayLiteralExpression that contains a YieldExpression.
92139          *
92140          * @param node The node to visit.
92141          */
92142         function visitArrayLiteralExpression(node) {
92143             return visitElements(node.elements, /*leadingElement*/ undefined, /*location*/ undefined, node.multiLine);
92144         }
92145         /**
92146          * Visits an array of expressions containing one or more YieldExpression nodes
92147          * and returns an expression for the resulting value.
92148          *
92149          * @param elements The elements to visit.
92150          * @param multiLine Whether array literals created should be emitted on multiple lines.
92151          */
92152         function visitElements(elements, leadingElement, location, multiLine) {
92153             // [source]
92154             //      ar = [1, yield, 2];
92155             //
92156             // [intermediate]
92157             //  .local _a
92158             //      _a = [1];
92159             //  .yield resumeLabel
92160             //  .mark resumeLabel
92161             //      ar = _a.concat([%sent%, 2]);
92162             var numInitialElements = countInitialNodesWithoutYield(elements);
92163             var temp;
92164             if (numInitialElements > 0) {
92165                 temp = declareLocal();
92166                 var initialElements = ts.visitNodes(elements, visitor, ts.isExpression, 0, numInitialElements);
92167                 emitAssignment(temp, factory.createArrayLiteralExpression(leadingElement
92168                     ? __spreadArrays([leadingElement], initialElements) : initialElements));
92169                 leadingElement = undefined;
92170             }
92171             var expressions = ts.reduceLeft(elements, reduceElement, [], numInitialElements);
92172             return temp
92173                 ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
92174                 : ts.setTextRange(factory.createArrayLiteralExpression(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine), location);
92175             function reduceElement(expressions, element) {
92176                 if (containsYield(element) && expressions.length > 0) {
92177                     var hasAssignedTemp = temp !== undefined;
92178                     if (!temp) {
92179                         temp = declareLocal();
92180                     }
92181                     emitAssignment(temp, hasAssignedTemp
92182                         ? factory.createArrayConcatCall(temp, [factory.createArrayLiteralExpression(expressions, multiLine)])
92183                         : factory.createArrayLiteralExpression(leadingElement ? __spreadArrays([leadingElement], expressions) : expressions, multiLine));
92184                     leadingElement = undefined;
92185                     expressions = [];
92186                 }
92187                 expressions.push(ts.visitNode(element, visitor, ts.isExpression));
92188                 return expressions;
92189             }
92190         }
92191         function visitObjectLiteralExpression(node) {
92192             // [source]
92193             //      o = {
92194             //          a: 1,
92195             //          b: yield,
92196             //          c: 2
92197             //      };
92198             //
92199             // [intermediate]
92200             //  .local _a
92201             //      _a = {
92202             //          a: 1
92203             //      };
92204             //  .yield resumeLabel
92205             //  .mark resumeLabel
92206             //      o = (_a.b = %sent%,
92207             //          _a.c = 2,
92208             //          _a);
92209             var properties = node.properties;
92210             var multiLine = node.multiLine;
92211             var numInitialProperties = countInitialNodesWithoutYield(properties);
92212             var temp = declareLocal();
92213             emitAssignment(temp, factory.createObjectLiteralExpression(ts.visitNodes(properties, visitor, ts.isObjectLiteralElementLike, 0, numInitialProperties), multiLine));
92214             var expressions = ts.reduceLeft(properties, reduceProperty, [], numInitialProperties);
92215             // TODO(rbuckton): Does this need to be parented?
92216             expressions.push(multiLine ? ts.startOnNewLine(ts.setParent(ts.setTextRange(factory.cloneNode(temp), temp), temp.parent)) : temp);
92217             return factory.inlineExpressions(expressions);
92218             function reduceProperty(expressions, property) {
92219                 if (containsYield(property) && expressions.length > 0) {
92220                     emitStatement(factory.createExpressionStatement(factory.inlineExpressions(expressions)));
92221                     expressions = [];
92222                 }
92223                 var expression = ts.createExpressionForObjectLiteralElementLike(factory, node, property, temp);
92224                 var visited = ts.visitNode(expression, visitor, ts.isExpression);
92225                 if (visited) {
92226                     if (multiLine) {
92227                         ts.startOnNewLine(visited);
92228                     }
92229                     expressions.push(visited);
92230                 }
92231                 return expressions;
92232             }
92233         }
92234         /**
92235          * Visits an ElementAccessExpression that contains a YieldExpression.
92236          *
92237          * @param node The node to visit.
92238          */
92239         function visitElementAccessExpression(node) {
92240             if (containsYield(node.argumentExpression)) {
92241                 // [source]
92242                 //      a = x[yield];
92243                 //
92244                 // [intermediate]
92245                 //  .local _a
92246                 //      _a = x;
92247                 //  .yield resumeLabel
92248                 //  .mark resumeLabel
92249                 //      a = _a[%sent%]
92250                 return factory.updateElementAccessExpression(node, cacheExpression(ts.visitNode(node.expression, visitor, ts.isLeftHandSideExpression)), ts.visitNode(node.argumentExpression, visitor, ts.isExpression));
92251             }
92252             return ts.visitEachChild(node, visitor, context);
92253         }
92254         function visitCallExpression(node) {
92255             if (!ts.isImportCall(node) && ts.forEach(node.arguments, containsYield)) {
92256                 // [source]
92257                 //      a.b(1, yield, 2);
92258                 //
92259                 // [intermediate]
92260                 //  .local _a, _b, _c
92261                 //      _b = (_a = a).b;
92262                 //      _c = [1];
92263                 //  .yield resumeLabel
92264                 //  .mark resumeLabel
92265                 //      _b.apply(_a, _c.concat([%sent%, 2]));
92266                 var _a = factory.createCallBinding(node.expression, hoistVariableDeclaration, languageVersion, /*cacheIdentifiers*/ true), target = _a.target, thisArg = _a.thisArg;
92267                 return ts.setOriginalNode(ts.setTextRange(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isLeftHandSideExpression)), thisArg, visitElements(node.arguments)), node), node);
92268             }
92269             return ts.visitEachChild(node, visitor, context);
92270         }
92271         function visitNewExpression(node) {
92272             if (ts.forEach(node.arguments, containsYield)) {
92273                 // [source]
92274                 //      new a.b(1, yield, 2);
92275                 //
92276                 // [intermediate]
92277                 //  .local _a, _b, _c
92278                 //      _b = (_a = a.b).bind;
92279                 //      _c = [1];
92280                 //  .yield resumeLabel
92281                 //  .mark resumeLabel
92282                 //      new (_b.apply(_a, _c.concat([%sent%, 2])));
92283                 var _a = factory.createCallBinding(factory.createPropertyAccessExpression(node.expression, "bind"), hoistVariableDeclaration), target = _a.target, thisArg = _a.thisArg;
92284                 return ts.setOriginalNode(ts.setTextRange(factory.createNewExpression(factory.createFunctionApplyCall(cacheExpression(ts.visitNode(target, visitor, ts.isExpression)), thisArg, visitElements(node.arguments, 
92285                 /*leadingElement*/ factory.createVoidZero())), 
92286                 /*typeArguments*/ undefined, []), node), node);
92287             }
92288             return ts.visitEachChild(node, visitor, context);
92289         }
92290         function transformAndEmitStatements(statements, start) {
92291             if (start === void 0) { start = 0; }
92292             var numStatements = statements.length;
92293             for (var i = start; i < numStatements; i++) {
92294                 transformAndEmitStatement(statements[i]);
92295             }
92296         }
92297         function transformAndEmitEmbeddedStatement(node) {
92298             if (ts.isBlock(node)) {
92299                 transformAndEmitStatements(node.statements);
92300             }
92301             else {
92302                 transformAndEmitStatement(node);
92303             }
92304         }
92305         function transformAndEmitStatement(node) {
92306             var savedInStatementContainingYield = inStatementContainingYield;
92307             if (!inStatementContainingYield) {
92308                 inStatementContainingYield = containsYield(node);
92309             }
92310             transformAndEmitStatementWorker(node);
92311             inStatementContainingYield = savedInStatementContainingYield;
92312         }
92313         function transformAndEmitStatementWorker(node) {
92314             switch (node.kind) {
92315                 case 230 /* Block */:
92316                     return transformAndEmitBlock(node);
92317                 case 233 /* ExpressionStatement */:
92318                     return transformAndEmitExpressionStatement(node);
92319                 case 234 /* IfStatement */:
92320                     return transformAndEmitIfStatement(node);
92321                 case 235 /* DoStatement */:
92322                     return transformAndEmitDoStatement(node);
92323                 case 236 /* WhileStatement */:
92324                     return transformAndEmitWhileStatement(node);
92325                 case 237 /* ForStatement */:
92326                     return transformAndEmitForStatement(node);
92327                 case 238 /* ForInStatement */:
92328                     return transformAndEmitForInStatement(node);
92329                 case 240 /* ContinueStatement */:
92330                     return transformAndEmitContinueStatement(node);
92331                 case 241 /* BreakStatement */:
92332                     return transformAndEmitBreakStatement(node);
92333                 case 242 /* ReturnStatement */:
92334                     return transformAndEmitReturnStatement(node);
92335                 case 243 /* WithStatement */:
92336                     return transformAndEmitWithStatement(node);
92337                 case 244 /* SwitchStatement */:
92338                     return transformAndEmitSwitchStatement(node);
92339                 case 245 /* LabeledStatement */:
92340                     return transformAndEmitLabeledStatement(node);
92341                 case 246 /* ThrowStatement */:
92342                     return transformAndEmitThrowStatement(node);
92343                 case 247 /* TryStatement */:
92344                     return transformAndEmitTryStatement(node);
92345                 default:
92346                     return emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92347             }
92348         }
92349         function transformAndEmitBlock(node) {
92350             if (containsYield(node)) {
92351                 transformAndEmitStatements(node.statements);
92352             }
92353             else {
92354                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92355             }
92356         }
92357         function transformAndEmitExpressionStatement(node) {
92358             emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92359         }
92360         function transformAndEmitVariableDeclarationList(node) {
92361             for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
92362                 var variable = _a[_i];
92363                 var name = factory.cloneNode(variable.name);
92364                 ts.setCommentRange(name, variable.name);
92365                 hoistVariableDeclaration(name);
92366             }
92367             var variables = ts.getInitializedVariables(node);
92368             var numVariables = variables.length;
92369             var variablesWritten = 0;
92370             var pendingExpressions = [];
92371             while (variablesWritten < numVariables) {
92372                 for (var i = variablesWritten; i < numVariables; i++) {
92373                     var variable = variables[i];
92374                     if (containsYield(variable.initializer) && pendingExpressions.length > 0) {
92375                         break;
92376                     }
92377                     pendingExpressions.push(transformInitializedVariable(variable));
92378                 }
92379                 if (pendingExpressions.length) {
92380                     emitStatement(factory.createExpressionStatement(factory.inlineExpressions(pendingExpressions)));
92381                     variablesWritten += pendingExpressions.length;
92382                     pendingExpressions = [];
92383                 }
92384             }
92385             return undefined;
92386         }
92387         function transformInitializedVariable(node) {
92388             return ts.setSourceMapRange(factory.createAssignment(ts.setSourceMapRange(factory.cloneNode(node.name), node.name), ts.visitNode(node.initializer, visitor, ts.isExpression)), node);
92389         }
92390         function transformAndEmitIfStatement(node) {
92391             if (containsYield(node)) {
92392                 // [source]
92393                 //      if (x)
92394                 //          /*thenStatement*/
92395                 //      else
92396                 //          /*elseStatement*/
92397                 //
92398                 // [intermediate]
92399                 //  .brfalse elseLabel, (x)
92400                 //      /*thenStatement*/
92401                 //  .br endLabel
92402                 //  .mark elseLabel
92403                 //      /*elseStatement*/
92404                 //  .mark endLabel
92405                 if (containsYield(node.thenStatement) || containsYield(node.elseStatement)) {
92406                     var endLabel = defineLabel();
92407                     var elseLabel = node.elseStatement ? defineLabel() : undefined;
92408                     emitBreakWhenFalse(node.elseStatement ? elseLabel : endLabel, ts.visitNode(node.expression, visitor, ts.isExpression), /*location*/ node.expression);
92409                     transformAndEmitEmbeddedStatement(node.thenStatement);
92410                     if (node.elseStatement) {
92411                         emitBreak(endLabel);
92412                         markLabel(elseLabel);
92413                         transformAndEmitEmbeddedStatement(node.elseStatement);
92414                     }
92415                     markLabel(endLabel);
92416                 }
92417                 else {
92418                     emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92419                 }
92420             }
92421             else {
92422                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92423             }
92424         }
92425         function transformAndEmitDoStatement(node) {
92426             if (containsYield(node)) {
92427                 // [source]
92428                 //      do {
92429                 //          /*body*/
92430                 //      }
92431                 //      while (i < 10);
92432                 //
92433                 // [intermediate]
92434                 //  .loop conditionLabel, endLabel
92435                 //  .mark loopLabel
92436                 //      /*body*/
92437                 //  .mark conditionLabel
92438                 //  .brtrue loopLabel, (i < 10)
92439                 //  .endloop
92440                 //  .mark endLabel
92441                 var conditionLabel = defineLabel();
92442                 var loopLabel = defineLabel();
92443                 beginLoopBlock(/*continueLabel*/ conditionLabel);
92444                 markLabel(loopLabel);
92445                 transformAndEmitEmbeddedStatement(node.statement);
92446                 markLabel(conditionLabel);
92447                 emitBreakWhenTrue(loopLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
92448                 endLoopBlock();
92449             }
92450             else {
92451                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92452             }
92453         }
92454         function visitDoStatement(node) {
92455             if (inStatementContainingYield) {
92456                 beginScriptLoopBlock();
92457                 node = ts.visitEachChild(node, visitor, context);
92458                 endLoopBlock();
92459                 return node;
92460             }
92461             else {
92462                 return ts.visitEachChild(node, visitor, context);
92463             }
92464         }
92465         function transformAndEmitWhileStatement(node) {
92466             if (containsYield(node)) {
92467                 // [source]
92468                 //      while (i < 10) {
92469                 //          /*body*/
92470                 //      }
92471                 //
92472                 // [intermediate]
92473                 //  .loop loopLabel, endLabel
92474                 //  .mark loopLabel
92475                 //  .brfalse endLabel, (i < 10)
92476                 //      /*body*/
92477                 //  .br loopLabel
92478                 //  .endloop
92479                 //  .mark endLabel
92480                 var loopLabel = defineLabel();
92481                 var endLabel = beginLoopBlock(loopLabel);
92482                 markLabel(loopLabel);
92483                 emitBreakWhenFalse(endLabel, ts.visitNode(node.expression, visitor, ts.isExpression));
92484                 transformAndEmitEmbeddedStatement(node.statement);
92485                 emitBreak(loopLabel);
92486                 endLoopBlock();
92487             }
92488             else {
92489                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92490             }
92491         }
92492         function visitWhileStatement(node) {
92493             if (inStatementContainingYield) {
92494                 beginScriptLoopBlock();
92495                 node = ts.visitEachChild(node, visitor, context);
92496                 endLoopBlock();
92497                 return node;
92498             }
92499             else {
92500                 return ts.visitEachChild(node, visitor, context);
92501             }
92502         }
92503         function transformAndEmitForStatement(node) {
92504             if (containsYield(node)) {
92505                 // [source]
92506                 //      for (var i = 0; i < 10; i++) {
92507                 //          /*body*/
92508                 //      }
92509                 //
92510                 // [intermediate]
92511                 //  .local i
92512                 //      i = 0;
92513                 //  .loop incrementLabel, endLoopLabel
92514                 //  .mark conditionLabel
92515                 //  .brfalse endLoopLabel, (i < 10)
92516                 //      /*body*/
92517                 //  .mark incrementLabel
92518                 //      i++;
92519                 //  .br conditionLabel
92520                 //  .endloop
92521                 //  .mark endLoopLabel
92522                 var conditionLabel = defineLabel();
92523                 var incrementLabel = defineLabel();
92524                 var endLabel = beginLoopBlock(incrementLabel);
92525                 if (node.initializer) {
92526                     var initializer = node.initializer;
92527                     if (ts.isVariableDeclarationList(initializer)) {
92528                         transformAndEmitVariableDeclarationList(initializer);
92529                     }
92530                     else {
92531                         emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(initializer, visitor, ts.isExpression)), initializer));
92532                     }
92533                 }
92534                 markLabel(conditionLabel);
92535                 if (node.condition) {
92536                     emitBreakWhenFalse(endLabel, ts.visitNode(node.condition, visitor, ts.isExpression));
92537                 }
92538                 transformAndEmitEmbeddedStatement(node.statement);
92539                 markLabel(incrementLabel);
92540                 if (node.incrementor) {
92541                     emitStatement(ts.setTextRange(factory.createExpressionStatement(ts.visitNode(node.incrementor, visitor, ts.isExpression)), node.incrementor));
92542                 }
92543                 emitBreak(conditionLabel);
92544                 endLoopBlock();
92545             }
92546             else {
92547                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92548             }
92549         }
92550         function visitForStatement(node) {
92551             if (inStatementContainingYield) {
92552                 beginScriptLoopBlock();
92553             }
92554             var initializer = node.initializer;
92555             if (initializer && ts.isVariableDeclarationList(initializer)) {
92556                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
92557                     var variable = _a[_i];
92558                     hoistVariableDeclaration(variable.name);
92559                 }
92560                 var variables = ts.getInitializedVariables(initializer);
92561                 node = factory.updateForStatement(node, variables.length > 0
92562                     ? factory.inlineExpressions(ts.map(variables, transformInitializedVariable))
92563                     : undefined, ts.visitNode(node.condition, visitor, ts.isExpression), ts.visitNode(node.incrementor, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
92564             }
92565             else {
92566                 node = ts.visitEachChild(node, visitor, context);
92567             }
92568             if (inStatementContainingYield) {
92569                 endLoopBlock();
92570             }
92571             return node;
92572         }
92573         function transformAndEmitForInStatement(node) {
92574             // TODO(rbuckton): Source map locations
92575             if (containsYield(node)) {
92576                 // [source]
92577                 //      for (var p in o) {
92578                 //          /*body*/
92579                 //      }
92580                 //
92581                 // [intermediate]
92582                 //  .local _a, _b, _i
92583                 //      _a = [];
92584                 //      for (_b in o) _a.push(_b);
92585                 //      _i = 0;
92586                 //  .loop incrementLabel, endLoopLabel
92587                 //  .mark conditionLabel
92588                 //  .brfalse endLoopLabel, (_i < _a.length)
92589                 //      p = _a[_i];
92590                 //      /*body*/
92591                 //  .mark incrementLabel
92592                 //      _b++;
92593                 //  .br conditionLabel
92594                 //  .endloop
92595                 //  .mark endLoopLabel
92596                 var keysArray = declareLocal(); // _a
92597                 var key = declareLocal(); // _b
92598                 var keysIndex = factory.createLoopVariable(); // _i
92599                 var initializer = node.initializer;
92600                 hoistVariableDeclaration(keysIndex);
92601                 emitAssignment(keysArray, factory.createArrayLiteralExpression());
92602                 emitStatement(factory.createForInStatement(key, ts.visitNode(node.expression, visitor, ts.isExpression), factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(keysArray, "push"), 
92603                 /*typeArguments*/ undefined, [key]))));
92604                 emitAssignment(keysIndex, factory.createNumericLiteral(0));
92605                 var conditionLabel = defineLabel();
92606                 var incrementLabel = defineLabel();
92607                 var endLabel = beginLoopBlock(incrementLabel);
92608                 markLabel(conditionLabel);
92609                 emitBreakWhenFalse(endLabel, factory.createLessThan(keysIndex, factory.createPropertyAccessExpression(keysArray, "length")));
92610                 var variable = void 0;
92611                 if (ts.isVariableDeclarationList(initializer)) {
92612                     for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
92613                         var variable_1 = _a[_i];
92614                         hoistVariableDeclaration(variable_1.name);
92615                     }
92616                     variable = factory.cloneNode(initializer.declarations[0].name);
92617                 }
92618                 else {
92619                     variable = ts.visitNode(initializer, visitor, ts.isExpression);
92620                     ts.Debug.assert(ts.isLeftHandSideExpression(variable));
92621                 }
92622                 emitAssignment(variable, factory.createElementAccessExpression(keysArray, keysIndex));
92623                 transformAndEmitEmbeddedStatement(node.statement);
92624                 markLabel(incrementLabel);
92625                 emitStatement(factory.createExpressionStatement(factory.createPostfixIncrement(keysIndex)));
92626                 emitBreak(conditionLabel);
92627                 endLoopBlock();
92628             }
92629             else {
92630                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92631             }
92632         }
92633         function visitForInStatement(node) {
92634             // [source]
92635             //      for (var x in a) {
92636             //          /*body*/
92637             //      }
92638             //
92639             // [intermediate]
92640             //  .local x
92641             //  .loop
92642             //      for (x in a) {
92643             //          /*body*/
92644             //      }
92645             //  .endloop
92646             if (inStatementContainingYield) {
92647                 beginScriptLoopBlock();
92648             }
92649             var initializer = node.initializer;
92650             if (ts.isVariableDeclarationList(initializer)) {
92651                 for (var _i = 0, _a = initializer.declarations; _i < _a.length; _i++) {
92652                     var variable = _a[_i];
92653                     hoistVariableDeclaration(variable.name);
92654                 }
92655                 node = factory.updateForInStatement(node, initializer.declarations[0].name, ts.visitNode(node.expression, visitor, ts.isExpression), ts.visitNode(node.statement, visitor, ts.isStatement, factory.liftToBlock));
92656             }
92657             else {
92658                 node = ts.visitEachChild(node, visitor, context);
92659             }
92660             if (inStatementContainingYield) {
92661                 endLoopBlock();
92662             }
92663             return node;
92664         }
92665         function transformAndEmitContinueStatement(node) {
92666             var label = findContinueTarget(node.label ? ts.idText(node.label) : undefined);
92667             if (label > 0) {
92668                 emitBreak(label, /*location*/ node);
92669             }
92670             else {
92671                 // invalid continue without a containing loop. Leave the node as is, per #17875.
92672                 emitStatement(node);
92673             }
92674         }
92675         function visitContinueStatement(node) {
92676             if (inStatementContainingYield) {
92677                 var label = findContinueTarget(node.label && ts.idText(node.label));
92678                 if (label > 0) {
92679                     return createInlineBreak(label, /*location*/ node);
92680                 }
92681             }
92682             return ts.visitEachChild(node, visitor, context);
92683         }
92684         function transformAndEmitBreakStatement(node) {
92685             var label = findBreakTarget(node.label ? ts.idText(node.label) : undefined);
92686             if (label > 0) {
92687                 emitBreak(label, /*location*/ node);
92688             }
92689             else {
92690                 // invalid break without a containing loop, switch, or labeled statement. Leave the node as is, per #17875.
92691                 emitStatement(node);
92692             }
92693         }
92694         function visitBreakStatement(node) {
92695             if (inStatementContainingYield) {
92696                 var label = findBreakTarget(node.label && ts.idText(node.label));
92697                 if (label > 0) {
92698                     return createInlineBreak(label, /*location*/ node);
92699                 }
92700             }
92701             return ts.visitEachChild(node, visitor, context);
92702         }
92703         function transformAndEmitReturnStatement(node) {
92704             emitReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
92705             /*location*/ node);
92706         }
92707         function visitReturnStatement(node) {
92708             return createInlineReturn(ts.visitNode(node.expression, visitor, ts.isExpression), 
92709             /*location*/ node);
92710         }
92711         function transformAndEmitWithStatement(node) {
92712             if (containsYield(node)) {
92713                 // [source]
92714                 //      with (x) {
92715                 //          /*body*/
92716                 //      }
92717                 //
92718                 // [intermediate]
92719                 //  .with (x)
92720                 //      /*body*/
92721                 //  .endwith
92722                 beginWithBlock(cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression)));
92723                 transformAndEmitEmbeddedStatement(node.statement);
92724                 endWithBlock();
92725             }
92726             else {
92727                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92728             }
92729         }
92730         function transformAndEmitSwitchStatement(node) {
92731             if (containsYield(node.caseBlock)) {
92732                 // [source]
92733                 //      switch (x) {
92734                 //          case a:
92735                 //              /*caseStatements*/
92736                 //          case b:
92737                 //              /*caseStatements*/
92738                 //          default:
92739                 //              /*defaultStatements*/
92740                 //      }
92741                 //
92742                 // [intermediate]
92743                 //  .local _a
92744                 //  .switch endLabel
92745                 //      _a = x;
92746                 //      switch (_a) {
92747                 //          case a:
92748                 //  .br clauseLabels[0]
92749                 //      }
92750                 //      switch (_a) {
92751                 //          case b:
92752                 //  .br clauseLabels[1]
92753                 //      }
92754                 //  .br clauseLabels[2]
92755                 //  .mark clauseLabels[0]
92756                 //      /*caseStatements*/
92757                 //  .mark clauseLabels[1]
92758                 //      /*caseStatements*/
92759                 //  .mark clauseLabels[2]
92760                 //      /*caseStatements*/
92761                 //  .endswitch
92762                 //  .mark endLabel
92763                 var caseBlock = node.caseBlock;
92764                 var numClauses = caseBlock.clauses.length;
92765                 var endLabel = beginSwitchBlock();
92766                 var expression = cacheExpression(ts.visitNode(node.expression, visitor, ts.isExpression));
92767                 // Create labels for each clause and find the index of the first default clause.
92768                 var clauseLabels = [];
92769                 var defaultClauseIndex = -1;
92770                 for (var i = 0; i < numClauses; i++) {
92771                     var clause = caseBlock.clauses[i];
92772                     clauseLabels.push(defineLabel());
92773                     if (clause.kind === 285 /* DefaultClause */ && defaultClauseIndex === -1) {
92774                         defaultClauseIndex = i;
92775                     }
92776                 }
92777                 // Emit switch statements for each run of case clauses either from the first case
92778                 // clause or the next case clause with a `yield` in its expression, up to the next
92779                 // case clause with a `yield` in its expression.
92780                 var clausesWritten = 0;
92781                 var pendingClauses = [];
92782                 while (clausesWritten < numClauses) {
92783                     var defaultClausesSkipped = 0;
92784                     for (var i = clausesWritten; i < numClauses; i++) {
92785                         var clause = caseBlock.clauses[i];
92786                         if (clause.kind === 284 /* CaseClause */) {
92787                             if (containsYield(clause.expression) && pendingClauses.length > 0) {
92788                                 break;
92789                             }
92790                             pendingClauses.push(factory.createCaseClause(ts.visitNode(clause.expression, visitor, ts.isExpression), [
92791                                 createInlineBreak(clauseLabels[i], /*location*/ clause.expression)
92792                             ]));
92793                         }
92794                         else {
92795                             defaultClausesSkipped++;
92796                         }
92797                     }
92798                     if (pendingClauses.length) {
92799                         emitStatement(factory.createSwitchStatement(expression, factory.createCaseBlock(pendingClauses)));
92800                         clausesWritten += pendingClauses.length;
92801                         pendingClauses = [];
92802                     }
92803                     if (defaultClausesSkipped > 0) {
92804                         clausesWritten += defaultClausesSkipped;
92805                         defaultClausesSkipped = 0;
92806                     }
92807                 }
92808                 if (defaultClauseIndex >= 0) {
92809                     emitBreak(clauseLabels[defaultClauseIndex]);
92810                 }
92811                 else {
92812                     emitBreak(endLabel);
92813                 }
92814                 for (var i = 0; i < numClauses; i++) {
92815                     markLabel(clauseLabels[i]);
92816                     transformAndEmitStatements(caseBlock.clauses[i].statements);
92817                 }
92818                 endSwitchBlock();
92819             }
92820             else {
92821                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92822             }
92823         }
92824         function visitSwitchStatement(node) {
92825             if (inStatementContainingYield) {
92826                 beginScriptSwitchBlock();
92827             }
92828             node = ts.visitEachChild(node, visitor, context);
92829             if (inStatementContainingYield) {
92830                 endSwitchBlock();
92831             }
92832             return node;
92833         }
92834         function transformAndEmitLabeledStatement(node) {
92835             if (containsYield(node)) {
92836                 // [source]
92837                 //      x: {
92838                 //          /*body*/
92839                 //      }
92840                 //
92841                 // [intermediate]
92842                 //  .labeled "x", endLabel
92843                 //      /*body*/
92844                 //  .endlabeled
92845                 //  .mark endLabel
92846                 beginLabeledBlock(ts.idText(node.label));
92847                 transformAndEmitEmbeddedStatement(node.statement);
92848                 endLabeledBlock();
92849             }
92850             else {
92851                 emitStatement(ts.visitNode(node, visitor, ts.isStatement));
92852             }
92853         }
92854         function visitLabeledStatement(node) {
92855             if (inStatementContainingYield) {
92856                 beginScriptLabeledBlock(ts.idText(node.label));
92857             }
92858             node = ts.visitEachChild(node, visitor, context);
92859             if (inStatementContainingYield) {
92860                 endLabeledBlock();
92861             }
92862             return node;
92863         }
92864         function transformAndEmitThrowStatement(node) {
92865             var _a;
92866             // TODO(rbuckton): `expression` should be required on `throw`.
92867             emitThrow(ts.visitNode((_a = node.expression) !== null && _a !== void 0 ? _a : factory.createVoidZero(), visitor, ts.isExpression), 
92868             /*location*/ node);
92869         }
92870         function transformAndEmitTryStatement(node) {
92871             if (containsYield(node)) {
92872                 // [source]
92873                 //      try {
92874                 //          /*tryBlock*/
92875                 //      }
92876                 //      catch (e) {
92877                 //          /*catchBlock*/
92878                 //      }
92879                 //      finally {
92880                 //          /*finallyBlock*/
92881                 //      }
92882                 //
92883                 // [intermediate]
92884                 //  .local _a
92885                 //  .try tryLabel, catchLabel, finallyLabel, endLabel
92886                 //  .mark tryLabel
92887                 //  .nop
92888                 //      /*tryBlock*/
92889                 //  .br endLabel
92890                 //  .catch
92891                 //  .mark catchLabel
92892                 //      _a = %error%;
92893                 //      /*catchBlock*/
92894                 //  .br endLabel
92895                 //  .finally
92896                 //  .mark finallyLabel
92897                 //      /*finallyBlock*/
92898                 //  .endfinally
92899                 //  .endtry
92900                 //  .mark endLabel
92901                 beginExceptionBlock();
92902                 transformAndEmitEmbeddedStatement(node.tryBlock);
92903                 if (node.catchClause) {
92904                     beginCatchBlock(node.catchClause.variableDeclaration); // TODO: GH#18217
92905                     transformAndEmitEmbeddedStatement(node.catchClause.block);
92906                 }
92907                 if (node.finallyBlock) {
92908                     beginFinallyBlock();
92909                     transformAndEmitEmbeddedStatement(node.finallyBlock);
92910                 }
92911                 endExceptionBlock();
92912             }
92913             else {
92914                 emitStatement(ts.visitEachChild(node, visitor, context));
92915             }
92916         }
92917         function containsYield(node) {
92918             return !!node && (node.transformFlags & 262144 /* ContainsYield */) !== 0;
92919         }
92920         function countInitialNodesWithoutYield(nodes) {
92921             var numNodes = nodes.length;
92922             for (var i = 0; i < numNodes; i++) {
92923                 if (containsYield(nodes[i])) {
92924                     return i;
92925                 }
92926             }
92927             return -1;
92928         }
92929         function onSubstituteNode(hint, node) {
92930             node = previousOnSubstituteNode(hint, node);
92931             if (hint === 1 /* Expression */) {
92932                 return substituteExpression(node);
92933             }
92934             return node;
92935         }
92936         function substituteExpression(node) {
92937             if (ts.isIdentifier(node)) {
92938                 return substituteExpressionIdentifier(node);
92939             }
92940             return node;
92941         }
92942         function substituteExpressionIdentifier(node) {
92943             if (!ts.isGeneratedIdentifier(node) && renamedCatchVariables && renamedCatchVariables.has(ts.idText(node))) {
92944                 var original = ts.getOriginalNode(node);
92945                 if (ts.isIdentifier(original) && original.parent) {
92946                     var declaration = resolver.getReferencedValueDeclaration(original);
92947                     if (declaration) {
92948                         var name = renamedCatchVariableDeclarations[ts.getOriginalNodeId(declaration)];
92949                         if (name) {
92950                             // TODO(rbuckton): Does this need to be parented?
92951                             var clone_5 = ts.setParent(ts.setTextRange(factory.cloneNode(name), name), name.parent);
92952                             ts.setSourceMapRange(clone_5, node);
92953                             ts.setCommentRange(clone_5, node);
92954                             return clone_5;
92955                         }
92956                     }
92957                 }
92958             }
92959             return node;
92960         }
92961         function cacheExpression(node) {
92962             if (ts.isGeneratedIdentifier(node) || ts.getEmitFlags(node) & 4096 /* HelperName */) {
92963                 return node;
92964             }
92965             var temp = factory.createTempVariable(hoistVariableDeclaration);
92966             emitAssignment(temp, node, /*location*/ node);
92967             return temp;
92968         }
92969         function declareLocal(name) {
92970             var temp = name
92971                 ? factory.createUniqueName(name)
92972                 : factory.createTempVariable(/*recordTempVariable*/ undefined);
92973             hoistVariableDeclaration(temp);
92974             return temp;
92975         }
92976         /**
92977          * Defines a label, uses as the target of a Break operation.
92978          */
92979         function defineLabel() {
92980             if (!labelOffsets) {
92981                 labelOffsets = [];
92982             }
92983             var label = nextLabelId;
92984             nextLabelId++;
92985             labelOffsets[label] = -1;
92986             return label;
92987         }
92988         /**
92989          * Marks the current operation with the specified label.
92990          */
92991         function markLabel(label) {
92992             ts.Debug.assert(labelOffsets !== undefined, "No labels were defined.");
92993             labelOffsets[label] = operations ? operations.length : 0;
92994         }
92995         /**
92996          * Begins a block operation (With, Break/Continue, Try/Catch/Finally)
92997          *
92998          * @param block Information about the block.
92999          */
93000         function beginBlock(block) {
93001             if (!blocks) {
93002                 blocks = [];
93003                 blockActions = [];
93004                 blockOffsets = [];
93005                 blockStack = [];
93006             }
93007             var index = blockActions.length;
93008             blockActions[index] = 0 /* Open */;
93009             blockOffsets[index] = operations ? operations.length : 0;
93010             blocks[index] = block;
93011             blockStack.push(block);
93012             return index;
93013         }
93014         /**
93015          * Ends the current block operation.
93016          */
93017         function endBlock() {
93018             var block = peekBlock();
93019             if (block === undefined)
93020                 return ts.Debug.fail("beginBlock was never called.");
93021             var index = blockActions.length;
93022             blockActions[index] = 1 /* Close */;
93023             blockOffsets[index] = operations ? operations.length : 0;
93024             blocks[index] = block;
93025             blockStack.pop();
93026             return block;
93027         }
93028         /**
93029          * Gets the current open block.
93030          */
93031         function peekBlock() {
93032             return ts.lastOrUndefined(blockStack);
93033         }
93034         /**
93035          * Gets the kind of the current open block.
93036          */
93037         function peekBlockKind() {
93038             var block = peekBlock();
93039             return block && block.kind;
93040         }
93041         /**
93042          * Begins a code block for a generated `with` statement.
93043          *
93044          * @param expression An identifier representing expression for the `with` block.
93045          */
93046         function beginWithBlock(expression) {
93047             var startLabel = defineLabel();
93048             var endLabel = defineLabel();
93049             markLabel(startLabel);
93050             beginBlock({
93051                 kind: 1 /* With */,
93052                 expression: expression,
93053                 startLabel: startLabel,
93054                 endLabel: endLabel
93055             });
93056         }
93057         /**
93058          * Ends a code block for a generated `with` statement.
93059          */
93060         function endWithBlock() {
93061             ts.Debug.assert(peekBlockKind() === 1 /* With */);
93062             var block = endBlock();
93063             markLabel(block.endLabel);
93064         }
93065         /**
93066          * Begins a code block for a generated `try` statement.
93067          */
93068         function beginExceptionBlock() {
93069             var startLabel = defineLabel();
93070             var endLabel = defineLabel();
93071             markLabel(startLabel);
93072             beginBlock({
93073                 kind: 0 /* Exception */,
93074                 state: 0 /* Try */,
93075                 startLabel: startLabel,
93076                 endLabel: endLabel
93077             });
93078             emitNop();
93079             return endLabel;
93080         }
93081         /**
93082          * Enters the `catch` clause of a generated `try` statement.
93083          *
93084          * @param variable The catch variable.
93085          */
93086         function beginCatchBlock(variable) {
93087             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
93088             // generated identifiers should already be unique within a file
93089             var name;
93090             if (ts.isGeneratedIdentifier(variable.name)) {
93091                 name = variable.name;
93092                 hoistVariableDeclaration(variable.name);
93093             }
93094             else {
93095                 var text = ts.idText(variable.name);
93096                 name = declareLocal(text);
93097                 if (!renamedCatchVariables) {
93098                     renamedCatchVariables = new ts.Map();
93099                     renamedCatchVariableDeclarations = [];
93100                     context.enableSubstitution(78 /* Identifier */);
93101                 }
93102                 renamedCatchVariables.set(text, true);
93103                 renamedCatchVariableDeclarations[ts.getOriginalNodeId(variable)] = name;
93104             }
93105             var exception = peekBlock();
93106             ts.Debug.assert(exception.state < 1 /* Catch */);
93107             var endLabel = exception.endLabel;
93108             emitBreak(endLabel);
93109             var catchLabel = defineLabel();
93110             markLabel(catchLabel);
93111             exception.state = 1 /* Catch */;
93112             exception.catchVariable = name;
93113             exception.catchLabel = catchLabel;
93114             emitAssignment(name, factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), /*typeArguments*/ undefined, []));
93115             emitNop();
93116         }
93117         /**
93118          * Enters the `finally` block of a generated `try` statement.
93119          */
93120         function beginFinallyBlock() {
93121             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
93122             var exception = peekBlock();
93123             ts.Debug.assert(exception.state < 2 /* Finally */);
93124             var endLabel = exception.endLabel;
93125             emitBreak(endLabel);
93126             var finallyLabel = defineLabel();
93127             markLabel(finallyLabel);
93128             exception.state = 2 /* Finally */;
93129             exception.finallyLabel = finallyLabel;
93130         }
93131         /**
93132          * Ends the code block for a generated `try` statement.
93133          */
93134         function endExceptionBlock() {
93135             ts.Debug.assert(peekBlockKind() === 0 /* Exception */);
93136             var exception = endBlock();
93137             var state = exception.state;
93138             if (state < 2 /* Finally */) {
93139                 emitBreak(exception.endLabel);
93140             }
93141             else {
93142                 emitEndfinally();
93143             }
93144             markLabel(exception.endLabel);
93145             emitNop();
93146             exception.state = 3 /* Done */;
93147         }
93148         /**
93149          * Begins a code block that supports `break` or `continue` statements that are defined in
93150          * the source tree and not from generated code.
93151          *
93152          * @param labelText Names from containing labeled statements.
93153          */
93154         function beginScriptLoopBlock() {
93155             beginBlock({
93156                 kind: 3 /* Loop */,
93157                 isScript: true,
93158                 breakLabel: -1,
93159                 continueLabel: -1
93160             });
93161         }
93162         /**
93163          * Begins a code block that supports `break` or `continue` statements that are defined in
93164          * generated code. Returns a label used to mark the operation to which to jump when a
93165          * `break` statement targets this block.
93166          *
93167          * @param continueLabel A Label used to mark the operation to which to jump when a
93168          *                      `continue` statement targets this block.
93169          */
93170         function beginLoopBlock(continueLabel) {
93171             var breakLabel = defineLabel();
93172             beginBlock({
93173                 kind: 3 /* Loop */,
93174                 isScript: false,
93175                 breakLabel: breakLabel,
93176                 continueLabel: continueLabel,
93177             });
93178             return breakLabel;
93179         }
93180         /**
93181          * Ends a code block that supports `break` or `continue` statements that are defined in
93182          * generated code or in the source tree.
93183          */
93184         function endLoopBlock() {
93185             ts.Debug.assert(peekBlockKind() === 3 /* Loop */);
93186             var block = endBlock();
93187             var breakLabel = block.breakLabel;
93188             if (!block.isScript) {
93189                 markLabel(breakLabel);
93190             }
93191         }
93192         /**
93193          * Begins a code block that supports `break` statements that are defined in the source
93194          * tree and not from generated code.
93195          *
93196          */
93197         function beginScriptSwitchBlock() {
93198             beginBlock({
93199                 kind: 2 /* Switch */,
93200                 isScript: true,
93201                 breakLabel: -1
93202             });
93203         }
93204         /**
93205          * Begins a code block that supports `break` statements that are defined in generated code.
93206          * Returns a label used to mark the operation to which to jump when a `break` statement
93207          * targets this block.
93208          */
93209         function beginSwitchBlock() {
93210             var breakLabel = defineLabel();
93211             beginBlock({
93212                 kind: 2 /* Switch */,
93213                 isScript: false,
93214                 breakLabel: breakLabel,
93215             });
93216             return breakLabel;
93217         }
93218         /**
93219          * Ends a code block that supports `break` statements that are defined in generated code.
93220          */
93221         function endSwitchBlock() {
93222             ts.Debug.assert(peekBlockKind() === 2 /* Switch */);
93223             var block = endBlock();
93224             var breakLabel = block.breakLabel;
93225             if (!block.isScript) {
93226                 markLabel(breakLabel);
93227             }
93228         }
93229         function beginScriptLabeledBlock(labelText) {
93230             beginBlock({
93231                 kind: 4 /* Labeled */,
93232                 isScript: true,
93233                 labelText: labelText,
93234                 breakLabel: -1
93235             });
93236         }
93237         function beginLabeledBlock(labelText) {
93238             var breakLabel = defineLabel();
93239             beginBlock({
93240                 kind: 4 /* Labeled */,
93241                 isScript: false,
93242                 labelText: labelText,
93243                 breakLabel: breakLabel
93244             });
93245         }
93246         function endLabeledBlock() {
93247             ts.Debug.assert(peekBlockKind() === 4 /* Labeled */);
93248             var block = endBlock();
93249             if (!block.isScript) {
93250                 markLabel(block.breakLabel);
93251             }
93252         }
93253         /**
93254          * Indicates whether the provided block supports `break` statements.
93255          *
93256          * @param block A code block.
93257          */
93258         function supportsUnlabeledBreak(block) {
93259             return block.kind === 2 /* Switch */
93260                 || block.kind === 3 /* Loop */;
93261         }
93262         /**
93263          * Indicates whether the provided block supports `break` statements with labels.
93264          *
93265          * @param block A code block.
93266          */
93267         function supportsLabeledBreakOrContinue(block) {
93268             return block.kind === 4 /* Labeled */;
93269         }
93270         /**
93271          * Indicates whether the provided block supports `continue` statements.
93272          *
93273          * @param block A code block.
93274          */
93275         function supportsUnlabeledContinue(block) {
93276             return block.kind === 3 /* Loop */;
93277         }
93278         function hasImmediateContainingLabeledBlock(labelText, start) {
93279             for (var j = start; j >= 0; j--) {
93280                 var containingBlock = blockStack[j];
93281                 if (supportsLabeledBreakOrContinue(containingBlock)) {
93282                     if (containingBlock.labelText === labelText) {
93283                         return true;
93284                     }
93285                 }
93286                 else {
93287                     break;
93288                 }
93289             }
93290             return false;
93291         }
93292         /**
93293          * Finds the label that is the target for a `break` statement.
93294          *
93295          * @param labelText An optional name of a containing labeled statement.
93296          */
93297         function findBreakTarget(labelText) {
93298             if (blockStack) {
93299                 if (labelText) {
93300                     for (var i = blockStack.length - 1; i >= 0; i--) {
93301                         var block = blockStack[i];
93302                         if (supportsLabeledBreakOrContinue(block) && block.labelText === labelText) {
93303                             return block.breakLabel;
93304                         }
93305                         else if (supportsUnlabeledBreak(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
93306                             return block.breakLabel;
93307                         }
93308                     }
93309                 }
93310                 else {
93311                     for (var i = blockStack.length - 1; i >= 0; i--) {
93312                         var block = blockStack[i];
93313                         if (supportsUnlabeledBreak(block)) {
93314                             return block.breakLabel;
93315                         }
93316                     }
93317                 }
93318             }
93319             return 0;
93320         }
93321         /**
93322          * Finds the label that is the target for a `continue` statement.
93323          *
93324          * @param labelText An optional name of a containing labeled statement.
93325          */
93326         function findContinueTarget(labelText) {
93327             if (blockStack) {
93328                 if (labelText) {
93329                     for (var i = blockStack.length - 1; i >= 0; i--) {
93330                         var block = blockStack[i];
93331                         if (supportsUnlabeledContinue(block) && hasImmediateContainingLabeledBlock(labelText, i - 1)) {
93332                             return block.continueLabel;
93333                         }
93334                     }
93335                 }
93336                 else {
93337                     for (var i = blockStack.length - 1; i >= 0; i--) {
93338                         var block = blockStack[i];
93339                         if (supportsUnlabeledContinue(block)) {
93340                             return block.continueLabel;
93341                         }
93342                     }
93343                 }
93344             }
93345             return 0;
93346         }
93347         /**
93348          * Creates an expression that can be used to indicate the value for a label.
93349          *
93350          * @param label A label.
93351          */
93352         function createLabel(label) {
93353             if (label !== undefined && label > 0) {
93354                 if (labelExpressions === undefined) {
93355                     labelExpressions = [];
93356                 }
93357                 var expression = factory.createNumericLiteral(-1);
93358                 if (labelExpressions[label] === undefined) {
93359                     labelExpressions[label] = [expression];
93360                 }
93361                 else {
93362                     labelExpressions[label].push(expression);
93363                 }
93364                 return expression;
93365             }
93366             return factory.createOmittedExpression();
93367         }
93368         /**
93369          * Creates a numeric literal for the provided instruction.
93370          */
93371         function createInstruction(instruction) {
93372             var literal = factory.createNumericLiteral(instruction);
93373             ts.addSyntheticTrailingComment(literal, 3 /* MultiLineCommentTrivia */, getInstructionName(instruction));
93374             return literal;
93375         }
93376         /**
93377          * Creates a statement that can be used indicate a Break operation to the provided label.
93378          *
93379          * @param label A label.
93380          * @param location An optional source map location for the statement.
93381          */
93382         function createInlineBreak(label, location) {
93383             ts.Debug.assertLessThan(0, label, "Invalid label");
93384             return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93385                 createInstruction(3 /* Break */),
93386                 createLabel(label)
93387             ])), location);
93388         }
93389         /**
93390          * Creates a statement that can be used indicate a Return operation.
93391          *
93392          * @param expression The expression for the return statement.
93393          * @param location An optional source map location for the statement.
93394          */
93395         function createInlineReturn(expression, location) {
93396             return ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
93397                 ? [createInstruction(2 /* Return */), expression]
93398                 : [createInstruction(2 /* Return */)])), location);
93399         }
93400         /**
93401          * Creates an expression that can be used to resume from a Yield operation.
93402          */
93403         function createGeneratorResume(location) {
93404             return ts.setTextRange(factory.createCallExpression(factory.createPropertyAccessExpression(state, "sent"), 
93405             /*typeArguments*/ undefined, []), location);
93406         }
93407         /**
93408          * Emits an empty instruction.
93409          */
93410         function emitNop() {
93411             emitWorker(0 /* Nop */);
93412         }
93413         /**
93414          * Emits a Statement.
93415          *
93416          * @param node A statement.
93417          */
93418         function emitStatement(node) {
93419             if (node) {
93420                 emitWorker(1 /* Statement */, [node]);
93421             }
93422             else {
93423                 emitNop();
93424             }
93425         }
93426         /**
93427          * Emits an Assignment operation.
93428          *
93429          * @param left The left-hand side of the assignment.
93430          * @param right The right-hand side of the assignment.
93431          * @param location An optional source map location for the assignment.
93432          */
93433         function emitAssignment(left, right, location) {
93434             emitWorker(2 /* Assign */, [left, right], location);
93435         }
93436         /**
93437          * Emits a Break operation to the specified label.
93438          *
93439          * @param label A label.
93440          * @param location An optional source map location for the assignment.
93441          */
93442         function emitBreak(label, location) {
93443             emitWorker(3 /* Break */, [label], location);
93444         }
93445         /**
93446          * Emits a Break operation to the specified label when a condition evaluates to a truthy
93447          * value at runtime.
93448          *
93449          * @param label A label.
93450          * @param condition The condition.
93451          * @param location An optional source map location for the assignment.
93452          */
93453         function emitBreakWhenTrue(label, condition, location) {
93454             emitWorker(4 /* BreakWhenTrue */, [label, condition], location);
93455         }
93456         /**
93457          * Emits a Break to the specified label when a condition evaluates to a falsey value at
93458          * runtime.
93459          *
93460          * @param label A label.
93461          * @param condition The condition.
93462          * @param location An optional source map location for the assignment.
93463          */
93464         function emitBreakWhenFalse(label, condition, location) {
93465             emitWorker(5 /* BreakWhenFalse */, [label, condition], location);
93466         }
93467         /**
93468          * Emits a YieldStar operation for the provided expression.
93469          *
93470          * @param expression An optional value for the yield operation.
93471          * @param location An optional source map location for the assignment.
93472          */
93473         function emitYieldStar(expression, location) {
93474             emitWorker(7 /* YieldStar */, [expression], location);
93475         }
93476         /**
93477          * Emits a Yield operation for the provided expression.
93478          *
93479          * @param expression An optional value for the yield operation.
93480          * @param location An optional source map location for the assignment.
93481          */
93482         function emitYield(expression, location) {
93483             emitWorker(6 /* Yield */, [expression], location);
93484         }
93485         /**
93486          * Emits a Return operation for the provided expression.
93487          *
93488          * @param expression An optional value for the operation.
93489          * @param location An optional source map location for the assignment.
93490          */
93491         function emitReturn(expression, location) {
93492             emitWorker(8 /* Return */, [expression], location);
93493         }
93494         /**
93495          * Emits a Throw operation for the provided expression.
93496          *
93497          * @param expression A value for the operation.
93498          * @param location An optional source map location for the assignment.
93499          */
93500         function emitThrow(expression, location) {
93501             emitWorker(9 /* Throw */, [expression], location);
93502         }
93503         /**
93504          * Emits an Endfinally operation. This is used to handle `finally` block semantics.
93505          */
93506         function emitEndfinally() {
93507             emitWorker(10 /* Endfinally */);
93508         }
93509         /**
93510          * Emits an operation.
93511          *
93512          * @param code The OpCode for the operation.
93513          * @param args The optional arguments for the operation.
93514          */
93515         function emitWorker(code, args, location) {
93516             if (operations === undefined) {
93517                 operations = [];
93518                 operationArguments = [];
93519                 operationLocations = [];
93520             }
93521             if (labelOffsets === undefined) {
93522                 // mark entry point
93523                 markLabel(defineLabel());
93524             }
93525             var operationIndex = operations.length;
93526             operations[operationIndex] = code;
93527             operationArguments[operationIndex] = args;
93528             operationLocations[operationIndex] = location;
93529         }
93530         /**
93531          * Builds the generator function body.
93532          */
93533         function build() {
93534             blockIndex = 0;
93535             labelNumber = 0;
93536             labelNumbers = undefined;
93537             lastOperationWasAbrupt = false;
93538             lastOperationWasCompletion = false;
93539             clauses = undefined;
93540             statements = undefined;
93541             exceptionBlockStack = undefined;
93542             currentExceptionBlock = undefined;
93543             withBlockStack = undefined;
93544             var buildResult = buildStatements();
93545             return emitHelpers().createGeneratorHelper(ts.setEmitFlags(factory.createFunctionExpression(
93546             /*modifiers*/ undefined, 
93547             /*asteriskToken*/ undefined, 
93548             /*name*/ undefined, 
93549             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, state)], 
93550             /*type*/ undefined, factory.createBlock(buildResult, 
93551             /*multiLine*/ buildResult.length > 0)), 524288 /* ReuseTempVariableScope */));
93552         }
93553         /**
93554          * Builds the statements for the generator function body.
93555          */
93556         function buildStatements() {
93557             if (operations) {
93558                 for (var operationIndex = 0; operationIndex < operations.length; operationIndex++) {
93559                     writeOperation(operationIndex);
93560                 }
93561                 flushFinalLabel(operations.length);
93562             }
93563             else {
93564                 flushFinalLabel(0);
93565             }
93566             if (clauses) {
93567                 var labelExpression = factory.createPropertyAccessExpression(state, "label");
93568                 var switchStatement = factory.createSwitchStatement(labelExpression, factory.createCaseBlock(clauses));
93569                 return [ts.startOnNewLine(switchStatement)];
93570             }
93571             if (statements) {
93572                 return statements;
93573             }
93574             return [];
93575         }
93576         /**
93577          * Flush the current label and advance to a new label.
93578          */
93579         function flushLabel() {
93580             if (!statements) {
93581                 return;
93582             }
93583             appendLabel(/*markLabelEnd*/ !lastOperationWasAbrupt);
93584             lastOperationWasAbrupt = false;
93585             lastOperationWasCompletion = false;
93586             labelNumber++;
93587         }
93588         /**
93589          * Flush the final label of the generator function body.
93590          */
93591         function flushFinalLabel(operationIndex) {
93592             if (isFinalLabelReachable(operationIndex)) {
93593                 tryEnterLabel(operationIndex);
93594                 withBlockStack = undefined;
93595                 writeReturn(/*expression*/ undefined, /*operationLocation*/ undefined);
93596             }
93597             if (statements && clauses) {
93598                 appendLabel(/*markLabelEnd*/ false);
93599             }
93600             updateLabelExpressions();
93601         }
93602         /**
93603          * Tests whether the final label of the generator function body
93604          * is reachable by user code.
93605          */
93606         function isFinalLabelReachable(operationIndex) {
93607             // if the last operation was *not* a completion (return/throw) then
93608             // the final label is reachable.
93609             if (!lastOperationWasCompletion) {
93610                 return true;
93611             }
93612             // if there are no labels defined or referenced, then the final label is
93613             // not reachable.
93614             if (!labelOffsets || !labelExpressions) {
93615                 return false;
93616             }
93617             // if the label for this offset is referenced, then the final label
93618             // is reachable.
93619             for (var label = 0; label < labelOffsets.length; label++) {
93620                 if (labelOffsets[label] === operationIndex && labelExpressions[label]) {
93621                     return true;
93622                 }
93623             }
93624             return false;
93625         }
93626         /**
93627          * Appends a case clause for the last label and sets the new label.
93628          *
93629          * @param markLabelEnd Indicates that the transition between labels was a fall-through
93630          *                     from a previous case clause and the change in labels should be
93631          *                     reflected on the `state` object.
93632          */
93633         function appendLabel(markLabelEnd) {
93634             if (!clauses) {
93635                 clauses = [];
93636             }
93637             if (statements) {
93638                 if (withBlockStack) {
93639                     // The previous label was nested inside one or more `with` blocks, so we
93640                     // surround the statements in generated `with` blocks to create the same environment.
93641                     for (var i = withBlockStack.length - 1; i >= 0; i--) {
93642                         var withBlock = withBlockStack[i];
93643                         statements = [factory.createWithStatement(withBlock.expression, factory.createBlock(statements))];
93644                     }
93645                 }
93646                 if (currentExceptionBlock) {
93647                     // The previous label was nested inside of an exception block, so we must
93648                     // indicate entry into a protected region by pushing the label numbers
93649                     // for each block in the protected region.
93650                     var startLabel = currentExceptionBlock.startLabel, catchLabel = currentExceptionBlock.catchLabel, finallyLabel = currentExceptionBlock.finallyLabel, endLabel = currentExceptionBlock.endLabel;
93651                     statements.unshift(factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createPropertyAccessExpression(state, "trys"), "push"), 
93652                     /*typeArguments*/ undefined, [
93653                         factory.createArrayLiteralExpression([
93654                             createLabel(startLabel),
93655                             createLabel(catchLabel),
93656                             createLabel(finallyLabel),
93657                             createLabel(endLabel)
93658                         ])
93659                     ])));
93660                     currentExceptionBlock = undefined;
93661                 }
93662                 if (markLabelEnd) {
93663                     // The case clause for the last label falls through to this label, so we
93664                     // add an assignment statement to reflect the change in labels.
93665                     statements.push(factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(state, "label"), factory.createNumericLiteral(labelNumber + 1))));
93666                 }
93667             }
93668             clauses.push(factory.createCaseClause(factory.createNumericLiteral(labelNumber), statements || []));
93669             statements = undefined;
93670         }
93671         /**
93672          * Tries to enter into a new label at the current operation index.
93673          */
93674         function tryEnterLabel(operationIndex) {
93675             if (!labelOffsets) {
93676                 return;
93677             }
93678             for (var label = 0; label < labelOffsets.length; label++) {
93679                 if (labelOffsets[label] === operationIndex) {
93680                     flushLabel();
93681                     if (labelNumbers === undefined) {
93682                         labelNumbers = [];
93683                     }
93684                     if (labelNumbers[labelNumber] === undefined) {
93685                         labelNumbers[labelNumber] = [label];
93686                     }
93687                     else {
93688                         labelNumbers[labelNumber].push(label);
93689                     }
93690                 }
93691             }
93692         }
93693         /**
93694          * Updates literal expressions for labels with actual label numbers.
93695          */
93696         function updateLabelExpressions() {
93697             if (labelExpressions !== undefined && labelNumbers !== undefined) {
93698                 for (var labelNumber_1 = 0; labelNumber_1 < labelNumbers.length; labelNumber_1++) {
93699                     var labels = labelNumbers[labelNumber_1];
93700                     if (labels !== undefined) {
93701                         for (var _i = 0, labels_1 = labels; _i < labels_1.length; _i++) {
93702                             var label = labels_1[_i];
93703                             var expressions = labelExpressions[label];
93704                             if (expressions !== undefined) {
93705                                 for (var _a = 0, expressions_1 = expressions; _a < expressions_1.length; _a++) {
93706                                     var expression = expressions_1[_a];
93707                                     expression.text = String(labelNumber_1);
93708                                 }
93709                             }
93710                         }
93711                     }
93712                 }
93713             }
93714         }
93715         /**
93716          * Tries to enter or leave a code block.
93717          */
93718         function tryEnterOrLeaveBlock(operationIndex) {
93719             if (blocks) {
93720                 for (; blockIndex < blockActions.length && blockOffsets[blockIndex] <= operationIndex; blockIndex++) {
93721                     var block = blocks[blockIndex];
93722                     var blockAction = blockActions[blockIndex];
93723                     switch (block.kind) {
93724                         case 0 /* Exception */:
93725                             if (blockAction === 0 /* Open */) {
93726                                 if (!exceptionBlockStack) {
93727                                     exceptionBlockStack = [];
93728                                 }
93729                                 if (!statements) {
93730                                     statements = [];
93731                                 }
93732                                 exceptionBlockStack.push(currentExceptionBlock);
93733                                 currentExceptionBlock = block;
93734                             }
93735                             else if (blockAction === 1 /* Close */) {
93736                                 currentExceptionBlock = exceptionBlockStack.pop();
93737                             }
93738                             break;
93739                         case 1 /* With */:
93740                             if (blockAction === 0 /* Open */) {
93741                                 if (!withBlockStack) {
93742                                     withBlockStack = [];
93743                                 }
93744                                 withBlockStack.push(block);
93745                             }
93746                             else if (blockAction === 1 /* Close */) {
93747                                 withBlockStack.pop();
93748                             }
93749                             break;
93750                         // default: do nothing
93751                     }
93752                 }
93753             }
93754         }
93755         /**
93756          * Writes an operation as a statement to the current label's statement list.
93757          *
93758          * @param operation The OpCode of the operation
93759          */
93760         function writeOperation(operationIndex) {
93761             tryEnterLabel(operationIndex);
93762             tryEnterOrLeaveBlock(operationIndex);
93763             // early termination, nothing else to process in this label
93764             if (lastOperationWasAbrupt) {
93765                 return;
93766             }
93767             lastOperationWasAbrupt = false;
93768             lastOperationWasCompletion = false;
93769             var opcode = operations[operationIndex];
93770             if (opcode === 0 /* Nop */) {
93771                 return;
93772             }
93773             else if (opcode === 10 /* Endfinally */) {
93774                 return writeEndfinally();
93775             }
93776             var args = operationArguments[operationIndex];
93777             if (opcode === 1 /* Statement */) {
93778                 return writeStatement(args[0]);
93779             }
93780             var location = operationLocations[operationIndex];
93781             switch (opcode) {
93782                 case 2 /* Assign */:
93783                     return writeAssign(args[0], args[1], location);
93784                 case 3 /* Break */:
93785                     return writeBreak(args[0], location);
93786                 case 4 /* BreakWhenTrue */:
93787                     return writeBreakWhenTrue(args[0], args[1], location);
93788                 case 5 /* BreakWhenFalse */:
93789                     return writeBreakWhenFalse(args[0], args[1], location);
93790                 case 6 /* Yield */:
93791                     return writeYield(args[0], location);
93792                 case 7 /* YieldStar */:
93793                     return writeYieldStar(args[0], location);
93794                 case 8 /* Return */:
93795                     return writeReturn(args[0], location);
93796                 case 9 /* Throw */:
93797                     return writeThrow(args[0], location);
93798             }
93799         }
93800         /**
93801          * Writes a statement to the current label's statement list.
93802          *
93803          * @param statement A statement to write.
93804          */
93805         function writeStatement(statement) {
93806             if (statement) {
93807                 if (!statements) {
93808                     statements = [statement];
93809                 }
93810                 else {
93811                     statements.push(statement);
93812                 }
93813             }
93814         }
93815         /**
93816          * Writes an Assign operation to the current label's statement list.
93817          *
93818          * @param left The left-hand side of the assignment.
93819          * @param right The right-hand side of the assignment.
93820          * @param operationLocation The source map location for the operation.
93821          */
93822         function writeAssign(left, right, operationLocation) {
93823             writeStatement(ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(left, right)), operationLocation));
93824         }
93825         /**
93826          * Writes a Throw operation to the current label's statement list.
93827          *
93828          * @param expression The value to throw.
93829          * @param operationLocation The source map location for the operation.
93830          */
93831         function writeThrow(expression, operationLocation) {
93832             lastOperationWasAbrupt = true;
93833             lastOperationWasCompletion = true;
93834             writeStatement(ts.setTextRange(factory.createThrowStatement(expression), operationLocation));
93835         }
93836         /**
93837          * Writes a Return operation to the current label's statement list.
93838          *
93839          * @param expression The value to return.
93840          * @param operationLocation The source map location for the operation.
93841          */
93842         function writeReturn(expression, operationLocation) {
93843             lastOperationWasAbrupt = true;
93844             lastOperationWasCompletion = true;
93845             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
93846                 ? [createInstruction(2 /* Return */), expression]
93847                 : [createInstruction(2 /* Return */)])), operationLocation), 384 /* NoTokenSourceMaps */));
93848         }
93849         /**
93850          * Writes a Break operation to the current label's statement list.
93851          *
93852          * @param label The label for the Break.
93853          * @param operationLocation The source map location for the operation.
93854          */
93855         function writeBreak(label, operationLocation) {
93856             lastOperationWasAbrupt = true;
93857             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93858                 createInstruction(3 /* Break */),
93859                 createLabel(label)
93860             ])), operationLocation), 384 /* NoTokenSourceMaps */));
93861         }
93862         /**
93863          * Writes a BreakWhenTrue operation to the current label's statement list.
93864          *
93865          * @param label The label for the Break.
93866          * @param condition The condition for the Break.
93867          * @param operationLocation The source map location for the operation.
93868          */
93869         function writeBreakWhenTrue(label, condition, operationLocation) {
93870             writeStatement(ts.setEmitFlags(factory.createIfStatement(condition, ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93871                 createInstruction(3 /* Break */),
93872                 createLabel(label)
93873             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
93874         }
93875         /**
93876          * Writes a BreakWhenFalse operation to the current label's statement list.
93877          *
93878          * @param label The label for the Break.
93879          * @param condition The condition for the Break.
93880          * @param operationLocation The source map location for the operation.
93881          */
93882         function writeBreakWhenFalse(label, condition, operationLocation) {
93883             writeStatement(ts.setEmitFlags(factory.createIfStatement(factory.createLogicalNot(condition), ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93884                 createInstruction(3 /* Break */),
93885                 createLabel(label)
93886             ])), operationLocation), 384 /* NoTokenSourceMaps */)), 1 /* SingleLine */));
93887         }
93888         /**
93889          * Writes a Yield operation to the current label's statement list.
93890          *
93891          * @param expression The expression to yield.
93892          * @param operationLocation The source map location for the operation.
93893          */
93894         function writeYield(expression, operationLocation) {
93895             lastOperationWasAbrupt = true;
93896             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression(expression
93897                 ? [createInstruction(4 /* Yield */), expression]
93898                 : [createInstruction(4 /* Yield */)])), operationLocation), 384 /* NoTokenSourceMaps */));
93899         }
93900         /**
93901          * Writes a YieldStar instruction to the current label's statement list.
93902          *
93903          * @param expression The expression to yield.
93904          * @param operationLocation The source map location for the operation.
93905          */
93906         function writeYieldStar(expression, operationLocation) {
93907             lastOperationWasAbrupt = true;
93908             writeStatement(ts.setEmitFlags(ts.setTextRange(factory.createReturnStatement(factory.createArrayLiteralExpression([
93909                 createInstruction(5 /* YieldStar */),
93910                 expression
93911             ])), operationLocation), 384 /* NoTokenSourceMaps */));
93912         }
93913         /**
93914          * Writes an Endfinally instruction to the current label's statement list.
93915          */
93916         function writeEndfinally() {
93917             lastOperationWasAbrupt = true;
93918             writeStatement(factory.createReturnStatement(factory.createArrayLiteralExpression([
93919                 createInstruction(7 /* Endfinally */)
93920             ])));
93921         }
93922     }
93923     ts.transformGenerators = transformGenerators;
93924 })(ts || (ts = {}));
93925 /*@internal*/
93926 var ts;
93927 (function (ts) {
93928     function transformModule(context) {
93929         function getTransformModuleDelegate(moduleKind) {
93930             switch (moduleKind) {
93931                 case ts.ModuleKind.AMD: return transformAMDModule;
93932                 case ts.ModuleKind.UMD: return transformUMDModule;
93933                 default: return transformCommonJSModule;
93934             }
93935         }
93936         var factory = context.factory, emitHelpers = context.getEmitHelperFactory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
93937         var compilerOptions = context.getCompilerOptions();
93938         var resolver = context.getEmitResolver();
93939         var host = context.getEmitHost();
93940         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
93941         var moduleKind = ts.getEmitModuleKind(compilerOptions);
93942         var previousOnSubstituteNode = context.onSubstituteNode;
93943         var previousOnEmitNode = context.onEmitNode;
93944         context.onSubstituteNode = onSubstituteNode;
93945         context.onEmitNode = onEmitNode;
93946         context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers with imported/exported symbols.
93947         context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols.
93948         context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
93949         context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
93950         context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes shorthand property assignments for imported/exported symbols.
93951         context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file.
93952         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
93953         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
93954         var currentSourceFile; // The current file.
93955         var currentModuleInfo; // The ExternalModuleInfo for the current file.
93956         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
93957         var needUMDDynamicImportHelper;
93958         return ts.chainBundle(context, transformSourceFile);
93959         /**
93960          * Transforms the module aspects of a SourceFile.
93961          *
93962          * @param node The SourceFile node.
93963          */
93964         function transformSourceFile(node) {
93965             if (node.isDeclarationFile ||
93966                 !(ts.isEffectiveExternalModule(node, compilerOptions) ||
93967                     node.transformFlags & 2097152 /* ContainsDynamicImport */ ||
93968                     (ts.isJsonSourceFile(node) && ts.hasJsonModuleEmitEnabled(compilerOptions) && ts.outFile(compilerOptions)))) {
93969                 return node;
93970             }
93971             currentSourceFile = node;
93972             currentModuleInfo = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
93973             moduleInfoMap[ts.getOriginalNodeId(node)] = currentModuleInfo;
93974             // Perform the transformation.
93975             var transformModule = getTransformModuleDelegate(moduleKind);
93976             var updated = transformModule(node);
93977             currentSourceFile = undefined;
93978             currentModuleInfo = undefined;
93979             needUMDDynamicImportHelper = false;
93980             return updated;
93981         }
93982         function shouldEmitUnderscoreUnderscoreESModule() {
93983             if (!currentModuleInfo.exportEquals && ts.isExternalModule(currentSourceFile)) {
93984                 return true;
93985             }
93986             return false;
93987         }
93988         /**
93989          * Transforms a SourceFile into a CommonJS module.
93990          *
93991          * @param node The SourceFile node.
93992          */
93993         function transformCommonJSModule(node) {
93994             startLexicalEnvironment();
93995             var statements = [];
93996             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
93997             var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict && !ts.isJsonSourceFile(node), sourceElementVisitor);
93998             if (shouldEmitUnderscoreUnderscoreESModule()) {
93999                 ts.append(statements, createUnderscoreUnderscoreESModule());
94000             }
94001             if (ts.length(currentModuleInfo.exportedNames)) {
94002                 var chunkSize = 50;
94003                 for (var i = 0; i < currentModuleInfo.exportedNames.length; i += chunkSize) {
94004                     ts.append(statements, factory.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames.slice(i, i + chunkSize), function (prev, nextId) { return factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(ts.idText(nextId))), prev); }, factory.createVoidZero())));
94005                 }
94006             }
94007             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
94008             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
94009             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ false);
94010             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
94011             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
94012             ts.addEmitHelpers(updated, context.readEmitHelpers());
94013             return updated;
94014         }
94015         /**
94016          * Transforms a SourceFile into an AMD module.
94017          *
94018          * @param node The SourceFile node.
94019          */
94020         function transformAMDModule(node) {
94021             var define = factory.createIdentifier("define");
94022             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
94023             var jsonSourceFile = ts.isJsonSourceFile(node) && node;
94024             // An AMD define function has the following shape:
94025             //
94026             //     define(id?, dependencies?, factory);
94027             //
94028             // This has the shape of the following:
94029             //
94030             //     define(name, ["module1", "module2"], function (module1Alias) { ... }
94031             //
94032             // The location of the alias in the parameter list in the factory function needs to
94033             // match the position of the module name in the dependency list.
94034             //
94035             // To ensure this is true in cases of modules with no aliases, e.g.:
94036             //
94037             //     import "module"
94038             //
94039             // or
94040             //
94041             //     /// <amd-dependency path= "a.css" />
94042             //
94043             // we need to add modules without alias names to the end of the dependencies list
94044             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ true), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
94045             // Create an updated SourceFile:
94046             //
94047             //     define(mofactory.updateSourceFile", "module2"], function ...
94048             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
94049                 factory.createExpressionStatement(factory.createCallExpression(define, 
94050                 /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
94051                     // Add the dependency array argument:
94052                     //
94053                     //     ["require", "exports", module1", "module2", ...]
94054                     factory.createArrayLiteralExpression(jsonSourceFile ? ts.emptyArray : __spreadArrays([
94055                         factory.createStringLiteral("require"),
94056                         factory.createStringLiteral("exports")
94057                     ], aliasedModuleNames, unaliasedModuleNames)),
94058                     // Add the module body function argument:
94059                     //
94060                     //     function (require, exports, module1, module2) ...
94061                     jsonSourceFile ?
94062                         jsonSourceFile.statements.length ? jsonSourceFile.statements[0].expression : factory.createObjectLiteralExpression() :
94063                         factory.createFunctionExpression(
94064                         /*modifiers*/ undefined, 
94065                         /*asteriskToken*/ undefined, 
94066                         /*name*/ undefined, 
94067                         /*typeParameters*/ undefined, __spreadArrays([
94068                             factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
94069                             factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
94070                         ], importAliasNames), 
94071                         /*type*/ undefined, transformAsynchronousModuleBody(node))
94072                 ])))
94073             ]), 
94074             /*location*/ node.statements));
94075             ts.addEmitHelpers(updated, context.readEmitHelpers());
94076             return updated;
94077         }
94078         /**
94079          * Transforms a SourceFile into a UMD module.
94080          *
94081          * @param node The SourceFile node.
94082          */
94083         function transformUMDModule(node) {
94084             var _a = collectAsynchronousDependencies(node, /*includeNonAmdDependencies*/ false), aliasedModuleNames = _a.aliasedModuleNames, unaliasedModuleNames = _a.unaliasedModuleNames, importAliasNames = _a.importAliasNames;
94085             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
94086             var umdHeader = factory.createFunctionExpression(
94087             /*modifiers*/ undefined, 
94088             /*asteriskToken*/ undefined, 
94089             /*name*/ undefined, 
94090             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "factory")], 
94091             /*type*/ undefined, ts.setTextRange(factory.createBlock([
94092                 factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("module"), "object"), factory.createTypeCheck(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), "object")), factory.createBlock([
94093                     factory.createVariableStatement(
94094                     /*modifiers*/ undefined, [
94095                         factory.createVariableDeclaration("v", 
94096                         /*exclamationToken*/ undefined, 
94097                         /*type*/ undefined, factory.createCallExpression(factory.createIdentifier("factory"), 
94098                         /*typeArguments*/ undefined, [
94099                             factory.createIdentifier("require"),
94100                             factory.createIdentifier("exports")
94101                         ]))
94102                     ]),
94103                     ts.setEmitFlags(factory.createIfStatement(factory.createStrictInequality(factory.createIdentifier("v"), factory.createIdentifier("undefined")), factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), factory.createIdentifier("v")))), 1 /* SingleLine */)
94104                 ]), factory.createIfStatement(factory.createLogicalAnd(factory.createTypeCheck(factory.createIdentifier("define"), "function"), factory.createPropertyAccessExpression(factory.createIdentifier("define"), "amd")), factory.createBlock([
94105                     factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("define"), 
94106                     /*typeArguments*/ undefined, __spreadArrays((moduleName ? [moduleName] : []), [
94107                         factory.createArrayLiteralExpression(__spreadArrays([
94108                             factory.createStringLiteral("require"),
94109                             factory.createStringLiteral("exports")
94110                         ], aliasedModuleNames, unaliasedModuleNames)),
94111                         factory.createIdentifier("factory")
94112                     ])))
94113                 ])))
94114             ], 
94115             /*multiLine*/ true), 
94116             /*location*/ undefined));
94117             // Create an updated SourceFile:
94118             //
94119             //  (function (factory) {
94120             //      if (typeof module === "object" && typeof module.exports === "object") {
94121             //          var v = factory(require, exports);
94122             //          if (v !== undefined) module.exports = v;
94123             //      }
94124             //      else if (typeof define === 'function' && define.amd) {
94125             //          define(["require", "exports"], factory);
94126             //      }
94127             //  })(function ...)
94128             var updated = factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
94129                 factory.createExpressionStatement(factory.createCallExpression(umdHeader, 
94130                 /*typeArguments*/ undefined, [
94131                     // Add the module body function argument:
94132                     //
94133                     //     function (require, exports) ...
94134                     factory.createFunctionExpression(
94135                     /*modifiers*/ undefined, 
94136                     /*asteriskToken*/ undefined, 
94137                     /*name*/ undefined, 
94138                     /*typeParameters*/ undefined, __spreadArrays([
94139                         factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "require"),
94140                         factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, "exports")
94141                     ], importAliasNames), 
94142                     /*type*/ undefined, transformAsynchronousModuleBody(node))
94143                 ]))
94144             ]), 
94145             /*location*/ node.statements));
94146             ts.addEmitHelpers(updated, context.readEmitHelpers());
94147             return updated;
94148         }
94149         /**
94150          * Collect the additional asynchronous dependencies for the module.
94151          *
94152          * @param node The source file.
94153          * @param includeNonAmdDependencies A value indicating whether to include non-AMD dependencies.
94154          */
94155         function collectAsynchronousDependencies(node, includeNonAmdDependencies) {
94156             // names of modules with corresponding parameter in the factory function
94157             var aliasedModuleNames = [];
94158             // names of modules with no corresponding parameters in factory function
94159             var unaliasedModuleNames = [];
94160             // names of the parameters in the factory function; these
94161             // parameters need to match the indexes of the corresponding
94162             // module names in aliasedModuleNames.
94163             var importAliasNames = [];
94164             // Fill in amd-dependency tags
94165             for (var _i = 0, _a = node.amdDependencies; _i < _a.length; _i++) {
94166                 var amdDependency = _a[_i];
94167                 if (amdDependency.name) {
94168                     aliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
94169                     importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, amdDependency.name));
94170                 }
94171                 else {
94172                     unaliasedModuleNames.push(factory.createStringLiteral(amdDependency.path));
94173                 }
94174             }
94175             for (var _b = 0, _c = currentModuleInfo.externalImports; _b < _c.length; _b++) {
94176                 var importNode = _c[_b];
94177                 // Find the name of the external module
94178                 var externalModuleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
94179                 // Find the name of the module alias, if there is one
94180                 var importAliasName = ts.getLocalNameForExternalImport(factory, importNode, currentSourceFile);
94181                 // It is possible that externalModuleName is undefined if it is not string literal.
94182                 // This can happen in the invalid import syntax.
94183                 // E.g : "import * from alias from 'someLib';"
94184                 if (externalModuleName) {
94185                     if (includeNonAmdDependencies && importAliasName) {
94186                         // Set emitFlags on the name of the classDeclaration
94187                         // This is so that when printer will not substitute the identifier
94188                         ts.setEmitFlags(importAliasName, 4 /* NoSubstitution */);
94189                         aliasedModuleNames.push(externalModuleName);
94190                         importAliasNames.push(factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, importAliasName));
94191                     }
94192                     else {
94193                         unaliasedModuleNames.push(externalModuleName);
94194                     }
94195                 }
94196             }
94197             return { aliasedModuleNames: aliasedModuleNames, unaliasedModuleNames: unaliasedModuleNames, importAliasNames: importAliasNames };
94198         }
94199         function getAMDImportExpressionForImport(node) {
94200             if (ts.isImportEqualsDeclaration(node) || ts.isExportDeclaration(node) || !ts.getExternalModuleNameLiteral(factory, node, currentSourceFile, host, resolver, compilerOptions)) {
94201                 return undefined;
94202             }
94203             var name = ts.getLocalNameForExternalImport(factory, node, currentSourceFile); // TODO: GH#18217
94204             var expr = getHelperExpressionForImport(node, name);
94205             if (expr === name) {
94206                 return undefined;
94207             }
94208             return factory.createExpressionStatement(factory.createAssignment(name, expr));
94209         }
94210         /**
94211          * Transforms a SourceFile into an AMD or UMD module body.
94212          *
94213          * @param node The SourceFile node.
94214          */
94215         function transformAsynchronousModuleBody(node) {
94216             startLexicalEnvironment();
94217             var statements = [];
94218             var statementOffset = factory.copyPrologue(node.statements, statements, /*ensureUseStrict*/ !compilerOptions.noImplicitUseStrict, sourceElementVisitor);
94219             if (shouldEmitUnderscoreUnderscoreESModule()) {
94220                 ts.append(statements, createUnderscoreUnderscoreESModule());
94221             }
94222             if (ts.length(currentModuleInfo.exportedNames)) {
94223                 ts.append(statements, factory.createExpressionStatement(ts.reduceLeft(currentModuleInfo.exportedNames, function (prev, nextId) { return factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.createIdentifier(ts.idText(nextId))), prev); }, factory.createVoidZero())));
94224             }
94225             // Visit each statement of the module body.
94226             ts.append(statements, ts.visitNode(currentModuleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement));
94227             if (moduleKind === ts.ModuleKind.AMD) {
94228                 ts.addRange(statements, ts.mapDefined(currentModuleInfo.externalImports, getAMDImportExpressionForImport));
94229             }
94230             ts.addRange(statements, ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset));
94231             // Append the 'export =' statement if provided.
94232             addExportEqualsIfNeeded(statements, /*emitAsReturn*/ true);
94233             // End the lexical environment for the module body
94234             // and merge any new lexical declarations.
94235             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
94236             var body = factory.createBlock(statements, /*multiLine*/ true);
94237             if (needUMDDynamicImportHelper) {
94238                 ts.addEmitHelper(body, dynamicImportUMDHelper);
94239             }
94240             return body;
94241         }
94242         /**
94243          * Adds the down-level representation of `export=` to the statement list if one exists
94244          * in the source file.
94245          *
94246          * @param statements The Statement list to modify.
94247          * @param emitAsReturn A value indicating whether to emit the `export=` statement as a
94248          * return statement.
94249          */
94250         function addExportEqualsIfNeeded(statements, emitAsReturn) {
94251             if (currentModuleInfo.exportEquals) {
94252                 var expressionResult = ts.visitNode(currentModuleInfo.exportEquals.expression, moduleExpressionElementVisitor);
94253                 if (expressionResult) {
94254                     if (emitAsReturn) {
94255                         var statement = factory.createReturnStatement(expressionResult);
94256                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
94257                         ts.setEmitFlags(statement, 384 /* NoTokenSourceMaps */ | 1536 /* NoComments */);
94258                         statements.push(statement);
94259                     }
94260                     else {
94261                         var statement = factory.createExpressionStatement(factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("module"), "exports"), expressionResult));
94262                         ts.setTextRange(statement, currentModuleInfo.exportEquals);
94263                         ts.setEmitFlags(statement, 1536 /* NoComments */);
94264                         statements.push(statement);
94265                     }
94266                 }
94267             }
94268         }
94269         //
94270         // Top-Level Source Element Visitors
94271         //
94272         /**
94273          * Visits a node at the top level of the source file.
94274          *
94275          * @param node The node to visit.
94276          */
94277         function sourceElementVisitor(node) {
94278             switch (node.kind) {
94279                 case 261 /* ImportDeclaration */:
94280                     return visitImportDeclaration(node);
94281                 case 260 /* ImportEqualsDeclaration */:
94282                     return visitImportEqualsDeclaration(node);
94283                 case 267 /* ExportDeclaration */:
94284                     return visitExportDeclaration(node);
94285                 case 266 /* ExportAssignment */:
94286                     return visitExportAssignment(node);
94287                 case 232 /* VariableStatement */:
94288                     return visitVariableStatement(node);
94289                 case 251 /* FunctionDeclaration */:
94290                     return visitFunctionDeclaration(node);
94291                 case 252 /* ClassDeclaration */:
94292                     return visitClassDeclaration(node);
94293                 case 338 /* MergeDeclarationMarker */:
94294                     return visitMergeDeclarationMarker(node);
94295                 case 339 /* EndOfDeclarationMarker */:
94296                     return visitEndOfDeclarationMarker(node);
94297                 default:
94298                     return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
94299             }
94300         }
94301         function moduleExpressionElementVisitor(node) {
94302             // This visitor does not need to descend into the tree if there is no dynamic import or destructuring assignment,
94303             // as export/import statements are only transformed at the top level of a file.
94304             if (!(node.transformFlags & 2097152 /* ContainsDynamicImport */) && !(node.transformFlags & 1024 /* ContainsDestructuringAssignment */)) {
94305                 return node;
94306             }
94307             if (ts.isImportCall(node)) {
94308                 return visitImportCallExpression(node);
94309             }
94310             else if (ts.isDestructuringAssignment(node)) {
94311                 return visitDestructuringAssignment(node);
94312             }
94313             else {
94314                 return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
94315             }
94316         }
94317         function destructuringNeedsFlattening(node) {
94318             if (ts.isObjectLiteralExpression(node)) {
94319                 for (var _i = 0, _a = node.properties; _i < _a.length; _i++) {
94320                     var elem = _a[_i];
94321                     switch (elem.kind) {
94322                         case 288 /* PropertyAssignment */:
94323                             if (destructuringNeedsFlattening(elem.initializer)) {
94324                                 return true;
94325                             }
94326                             break;
94327                         case 289 /* ShorthandPropertyAssignment */:
94328                             if (destructuringNeedsFlattening(elem.name)) {
94329                                 return true;
94330                             }
94331                             break;
94332                         case 290 /* SpreadAssignment */:
94333                             if (destructuringNeedsFlattening(elem.expression)) {
94334                                 return true;
94335                             }
94336                             break;
94337                         case 165 /* MethodDeclaration */:
94338                         case 167 /* GetAccessor */:
94339                         case 168 /* SetAccessor */:
94340                             return false;
94341                         default: ts.Debug.assertNever(elem, "Unhandled object member kind");
94342                     }
94343                 }
94344             }
94345             else if (ts.isArrayLiteralExpression(node)) {
94346                 for (var _b = 0, _c = node.elements; _b < _c.length; _b++) {
94347                     var elem = _c[_b];
94348                     if (ts.isSpreadElement(elem)) {
94349                         if (destructuringNeedsFlattening(elem.expression)) {
94350                             return true;
94351                         }
94352                     }
94353                     else if (destructuringNeedsFlattening(elem)) {
94354                         return true;
94355                     }
94356                 }
94357             }
94358             else if (ts.isIdentifier(node)) {
94359                 return ts.length(getExports(node)) > (ts.isExportName(node) ? 1 : 0);
94360             }
94361             return false;
94362         }
94363         function visitDestructuringAssignment(node) {
94364             if (destructuringNeedsFlattening(node.left)) {
94365                 return ts.flattenDestructuringAssignment(node, moduleExpressionElementVisitor, context, 0 /* All */, /*needsValue*/ false, createAllExportExpressions);
94366             }
94367             return ts.visitEachChild(node, moduleExpressionElementVisitor, context);
94368         }
94369         function visitImportCallExpression(node) {
94370             var argument = ts.visitNode(ts.firstOrUndefined(node.arguments), moduleExpressionElementVisitor);
94371             var containsLexicalThis = !!(node.transformFlags & 4096 /* ContainsLexicalThis */);
94372             switch (compilerOptions.module) {
94373                 case ts.ModuleKind.AMD:
94374                     return createImportCallExpressionAMD(argument, containsLexicalThis);
94375                 case ts.ModuleKind.UMD:
94376                     return createImportCallExpressionUMD(argument !== null && argument !== void 0 ? argument : factory.createVoidZero(), containsLexicalThis);
94377                 case ts.ModuleKind.CommonJS:
94378                 default:
94379                     return createImportCallExpressionCommonJS(argument, containsLexicalThis);
94380             }
94381         }
94382         function createImportCallExpressionUMD(arg, containsLexicalThis) {
94383             // (function (factory) {
94384             //      ... (regular UMD)
94385             // }
94386             // })(function (require, exports, useSyncRequire) {
94387             //      "use strict";
94388             //      Object.defineProperty(exports, "__esModule", { value: true });
94389             //      var __syncRequire = typeof module === "object" && typeof module.exports === "object";
94390             //      var __resolved = new Promise(function (resolve) { resolve(); });
94391             //      .....
94392             //      __syncRequire
94393             //          ? __resolved.then(function () { return require(x); }) /*CommonJs Require*/
94394             //          : new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
94395             // });
94396             needUMDDynamicImportHelper = true;
94397             if (ts.isSimpleCopiableExpression(arg)) {
94398                 var argClone = ts.isGeneratedIdentifier(arg) ? arg : ts.isStringLiteral(arg) ? factory.createStringLiteralFromNode(arg) : ts.setEmitFlags(ts.setTextRange(factory.cloneNode(arg), arg), 1536 /* NoComments */);
94399                 return factory.createConditionalExpression(
94400                 /*condition*/ factory.createIdentifier("__syncRequire"), 
94401                 /*questionToken*/ undefined, 
94402                 /*whenTrue*/ createImportCallExpressionCommonJS(arg, containsLexicalThis), 
94403                 /*colonToken*/ undefined, 
94404                 /*whenFalse*/ createImportCallExpressionAMD(argClone, containsLexicalThis));
94405             }
94406             else {
94407                 var temp = factory.createTempVariable(hoistVariableDeclaration);
94408                 return factory.createComma(factory.createAssignment(temp, arg), factory.createConditionalExpression(
94409                 /*condition*/ factory.createIdentifier("__syncRequire"), 
94410                 /*questionToken*/ undefined, 
94411                 /*whenTrue*/ createImportCallExpressionCommonJS(temp, containsLexicalThis), 
94412                 /*colonToken*/ undefined, 
94413                 /*whenFalse*/ createImportCallExpressionAMD(temp, containsLexicalThis)));
94414             }
94415         }
94416         function createImportCallExpressionAMD(arg, containsLexicalThis) {
94417             // improt("./blah")
94418             // emit as
94419             // define(["require", "exports", "blah"], function (require, exports) {
94420             //     ...
94421             //     new Promise(function (_a, _b) { require([x], _a, _b); }); /*Amd Require*/
94422             // });
94423             var resolve = factory.createUniqueName("resolve");
94424             var reject = factory.createUniqueName("reject");
94425             var parameters = [
94426                 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ resolve),
94427                 factory.createParameterDeclaration(/*decorator*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, /*name*/ reject)
94428             ];
94429             var body = factory.createBlock([
94430                 factory.createExpressionStatement(factory.createCallExpression(factory.createIdentifier("require"), 
94431                 /*typeArguments*/ undefined, [factory.createArrayLiteralExpression([arg || factory.createOmittedExpression()]), resolve, reject]))
94432             ]);
94433             var func;
94434             if (languageVersion >= 2 /* ES2015 */) {
94435                 func = factory.createArrowFunction(
94436                 /*modifiers*/ undefined, 
94437                 /*typeParameters*/ undefined, parameters, 
94438                 /*type*/ undefined, 
94439                 /*equalsGreaterThanToken*/ undefined, body);
94440             }
94441             else {
94442                 func = factory.createFunctionExpression(
94443                 /*modifiers*/ undefined, 
94444                 /*asteriskToken*/ undefined, 
94445                 /*name*/ undefined, 
94446                 /*typeParameters*/ undefined, parameters, 
94447                 /*type*/ undefined, body);
94448                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
94449                 // that this new function expression indicates it captures 'this' so that the
94450                 // es2015 transformer will properly substitute 'this' with '_this'.
94451                 if (containsLexicalThis) {
94452                     ts.setEmitFlags(func, 8 /* CapturesThis */);
94453                 }
94454             }
94455             var promise = factory.createNewExpression(factory.createIdentifier("Promise"), /*typeArguments*/ undefined, [func]);
94456             if (compilerOptions.esModuleInterop) {
94457                 return factory.createCallExpression(factory.createPropertyAccessExpression(promise, factory.createIdentifier("then")), /*typeArguments*/ undefined, [emitHelpers().createImportStarCallbackHelper()]);
94458             }
94459             return promise;
94460         }
94461         function createImportCallExpressionCommonJS(arg, containsLexicalThis) {
94462             // import("./blah")
94463             // emit as
94464             // Promise.resolve().then(function () { return require(x); }) /*CommonJs Require*/
94465             // We have to wrap require in then callback so that require is done in asynchronously
94466             // if we simply do require in resolve callback in Promise constructor. We will execute the loading immediately
94467             var promiseResolveCall = factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Promise"), "resolve"), /*typeArguments*/ undefined, /*argumentsArray*/ []);
94468             var requireCall = factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, arg ? [arg] : []);
94469             if (compilerOptions.esModuleInterop) {
94470                 requireCall = emitHelpers().createImportStarHelper(requireCall);
94471             }
94472             var func;
94473             if (languageVersion >= 2 /* ES2015 */) {
94474                 func = factory.createArrowFunction(
94475                 /*modifiers*/ undefined, 
94476                 /*typeParameters*/ undefined, 
94477                 /*parameters*/ [], 
94478                 /*type*/ undefined, 
94479                 /*equalsGreaterThanToken*/ undefined, requireCall);
94480             }
94481             else {
94482                 func = factory.createFunctionExpression(
94483                 /*modifiers*/ undefined, 
94484                 /*asteriskToken*/ undefined, 
94485                 /*name*/ undefined, 
94486                 /*typeParameters*/ undefined, 
94487                 /*parameters*/ [], 
94488                 /*type*/ undefined, factory.createBlock([factory.createReturnStatement(requireCall)]));
94489                 // if there is a lexical 'this' in the import call arguments, ensure we indicate
94490                 // that this new function expression indicates it captures 'this' so that the
94491                 // es2015 transformer will properly substitute 'this' with '_this'.
94492                 if (containsLexicalThis) {
94493                     ts.setEmitFlags(func, 8 /* CapturesThis */);
94494                 }
94495             }
94496             return factory.createCallExpression(factory.createPropertyAccessExpression(promiseResolveCall, "then"), /*typeArguments*/ undefined, [func]);
94497         }
94498         function getHelperExpressionForExport(node, innerExpr) {
94499             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
94500                 return innerExpr;
94501             }
94502             if (ts.getExportNeedsImportStarHelper(node)) {
94503                 return emitHelpers().createImportStarHelper(innerExpr);
94504             }
94505             return innerExpr;
94506         }
94507         function getHelperExpressionForImport(node, innerExpr) {
94508             if (!compilerOptions.esModuleInterop || ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) {
94509                 return innerExpr;
94510             }
94511             if (ts.getImportNeedsImportStarHelper(node)) {
94512                 return emitHelpers().createImportStarHelper(innerExpr);
94513             }
94514             if (ts.getImportNeedsImportDefaultHelper(node)) {
94515                 return emitHelpers().createImportDefaultHelper(innerExpr);
94516             }
94517             return innerExpr;
94518         }
94519         /**
94520          * Visits an ImportDeclaration node.
94521          *
94522          * @param node The node to visit.
94523          */
94524         function visitImportDeclaration(node) {
94525             var statements;
94526             var namespaceDeclaration = ts.getNamespaceDeclarationNode(node);
94527             if (moduleKind !== ts.ModuleKind.AMD) {
94528                 if (!node.importClause) {
94529                     // import "mod";
94530                     return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createRequireCall(node)), node), node);
94531                 }
94532                 else {
94533                     var variables = [];
94534                     if (namespaceDeclaration && !ts.isDefaultImport(node)) {
94535                         // import * as n from "mod";
94536                         variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
94537                         /*exclamationToken*/ undefined, 
94538                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
94539                     }
94540                     else {
94541                         // import d from "mod";
94542                         // import { x, y } from "mod";
94543                         // import d, { x, y } from "mod";
94544                         // import d, * as n from "mod";
94545                         variables.push(factory.createVariableDeclaration(factory.getGeneratedNameForNode(node), 
94546                         /*exclamationToken*/ undefined, 
94547                         /*type*/ undefined, getHelperExpressionForImport(node, createRequireCall(node))));
94548                         if (namespaceDeclaration && ts.isDefaultImport(node)) {
94549                             variables.push(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
94550                             /*exclamationToken*/ undefined, 
94551                             /*type*/ undefined, factory.getGeneratedNameForNode(node)));
94552                         }
94553                     }
94554                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
94555                     /*modifiers*/ undefined, factory.createVariableDeclarationList(variables, languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), 
94556                     /*location*/ node), 
94557                     /*original*/ node));
94558                 }
94559             }
94560             else if (namespaceDeclaration && ts.isDefaultImport(node)) {
94561                 // import d, * as n from "mod";
94562                 statements = ts.append(statements, factory.createVariableStatement(
94563                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
94564                     ts.setOriginalNode(ts.setTextRange(factory.createVariableDeclaration(factory.cloneNode(namespaceDeclaration.name), 
94565                     /*exclamationToken*/ undefined, 
94566                     /*type*/ undefined, factory.getGeneratedNameForNode(node)), 
94567                     /*location*/ node), 
94568                     /*original*/ node)
94569                 ], languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)));
94570             }
94571             if (hasAssociatedEndOfDeclarationMarker(node)) {
94572                 // Defer exports until we encounter an EndOfDeclarationMarker node
94573                 var id = ts.getOriginalNodeId(node);
94574                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
94575             }
94576             else {
94577                 statements = appendExportsOfImportDeclaration(statements, node);
94578             }
94579             return ts.singleOrMany(statements);
94580         }
94581         /**
94582          * Creates a `require()` call to import an external module.
94583          *
94584          * @param importNode The declararation to import.
94585          */
94586         function createRequireCall(importNode) {
94587             var moduleName = ts.getExternalModuleNameLiteral(factory, importNode, currentSourceFile, host, resolver, compilerOptions);
94588             var args = [];
94589             if (moduleName) {
94590                 args.push(moduleName);
94591             }
94592             return factory.createCallExpression(factory.createIdentifier("require"), /*typeArguments*/ undefined, args);
94593         }
94594         /**
94595          * Visits an ImportEqualsDeclaration node.
94596          *
94597          * @param node The node to visit.
94598          */
94599         function visitImportEqualsDeclaration(node) {
94600             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
94601             var statements;
94602             if (moduleKind !== ts.ModuleKind.AMD) {
94603                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94604                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(node.name, createRequireCall(node))), node), node));
94605                 }
94606                 else {
94607                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
94608                     /*modifiers*/ undefined, factory.createVariableDeclarationList([
94609                         factory.createVariableDeclaration(factory.cloneNode(node.name), 
94610                         /*exclamationToken*/ undefined, 
94611                         /*type*/ undefined, createRequireCall(node))
94612                     ], 
94613                     /*flags*/ languageVersion >= 2 /* ES2015 */ ? 2 /* Const */ : 0 /* None */)), node), node));
94614                 }
94615             }
94616             else {
94617                 if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94618                     statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(node), factory.getLocalName(node))), node), node));
94619                 }
94620             }
94621             if (hasAssociatedEndOfDeclarationMarker(node)) {
94622                 // Defer exports until we encounter an EndOfDeclarationMarker node
94623                 var id = ts.getOriginalNodeId(node);
94624                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
94625             }
94626             else {
94627                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
94628             }
94629             return ts.singleOrMany(statements);
94630         }
94631         /**
94632          * Visits an ExportDeclaration node.
94633          *
94634          * @param The node to visit.
94635          */
94636         function visitExportDeclaration(node) {
94637             if (!node.moduleSpecifier) {
94638                 // Elide export declarations with no module specifier as they are handled
94639                 // elsewhere.
94640                 return undefined;
94641             }
94642             var generatedName = factory.getGeneratedNameForNode(node);
94643             if (node.exportClause && ts.isNamedExports(node.exportClause)) {
94644                 var statements = [];
94645                 // export { x, y } from "mod";
94646                 if (moduleKind !== ts.ModuleKind.AMD) {
94647                     statements.push(ts.setOriginalNode(ts.setTextRange(factory.createVariableStatement(
94648                     /*modifiers*/ undefined, factory.createVariableDeclarationList([
94649                         factory.createVariableDeclaration(generatedName, 
94650                         /*exclamationToken*/ undefined, 
94651                         /*type*/ undefined, createRequireCall(node))
94652                     ])), 
94653                     /*location*/ node), 
94654                     /* original */ node));
94655                 }
94656                 for (var _i = 0, _a = node.exportClause.elements; _i < _a.length; _i++) {
94657                     var specifier = _a[_i];
94658                     if (languageVersion === 0 /* ES3 */) {
94659                         statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createCreateBindingHelper(generatedName, factory.createStringLiteralFromNode(specifier.propertyName || specifier.name), specifier.propertyName ? factory.createStringLiteralFromNode(specifier.name) : undefined)), specifier), specifier));
94660                     }
94661                     else {
94662                         var exportNeedsImportDefault = !!compilerOptions.esModuleInterop &&
94663                             !(ts.getEmitFlags(node) & 67108864 /* NeverApplyImportHelper */) &&
94664                             ts.idText(specifier.propertyName || specifier.name) === "default";
94665                         var exportedValue = factory.createPropertyAccessExpression(exportNeedsImportDefault ? emitHelpers().createImportDefaultHelper(generatedName) : generatedName, specifier.propertyName || specifier.name);
94666                         statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.getExportName(specifier), exportedValue, /* location */ undefined, /* liveBinding */ true)), specifier), specifier));
94667                     }
94668                 }
94669                 return ts.singleOrMany(statements);
94670             }
94671             else if (node.exportClause) {
94672                 var statements = [];
94673                 // export * as ns from "mod";
94674                 // export * as default from "mod";
94675                 statements.push(ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(createExportExpression(factory.cloneNode(node.exportClause.name), getHelperExpressionForExport(node, moduleKind !== ts.ModuleKind.AMD ?
94676                     createRequireCall(node) :
94677                     ts.isExportNamespaceAsDefaultDeclaration(node) ? generatedName :
94678                         factory.createIdentifier(ts.idText(node.exportClause.name))))), node), node));
94679                 return ts.singleOrMany(statements);
94680             }
94681             else {
94682                 // export * from "mod";
94683                 return ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(emitHelpers().createExportStarHelper(moduleKind !== ts.ModuleKind.AMD ? createRequireCall(node) : generatedName)), node), node);
94684             }
94685         }
94686         /**
94687          * Visits an ExportAssignment node.
94688          *
94689          * @param node The node to visit.
94690          */
94691         function visitExportAssignment(node) {
94692             if (node.isExportEquals) {
94693                 return undefined;
94694             }
94695             var statements;
94696             var original = node.original;
94697             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
94698                 // Defer exports until we encounter an EndOfDeclarationMarker node
94699                 var id = ts.getOriginalNodeId(node);
94700                 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
94701             }
94702             else {
94703                 statements = appendExportStatement(statements, factory.createIdentifier("default"), ts.visitNode(node.expression, moduleExpressionElementVisitor), /*location*/ node, /*allowComments*/ true);
94704             }
94705             return ts.singleOrMany(statements);
94706         }
94707         /**
94708          * Visits a FunctionDeclaration node.
94709          *
94710          * @param node The node to visit.
94711          */
94712         function visitFunctionDeclaration(node) {
94713             var statements;
94714             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94715                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createFunctionDeclaration(
94716                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
94717                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, moduleExpressionElementVisitor), 
94718                 /*type*/ undefined, ts.visitEachChild(node.body, moduleExpressionElementVisitor, context)), 
94719                 /*location*/ node), 
94720                 /*original*/ node));
94721             }
94722             else {
94723                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
94724             }
94725             if (hasAssociatedEndOfDeclarationMarker(node)) {
94726                 // Defer exports until we encounter an EndOfDeclarationMarker node
94727                 var id = ts.getOriginalNodeId(node);
94728                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
94729             }
94730             else {
94731                 statements = appendExportsOfHoistedDeclaration(statements, node);
94732             }
94733             return ts.singleOrMany(statements);
94734         }
94735         /**
94736          * Visits a ClassDeclaration node.
94737          *
94738          * @param node The node to visit.
94739          */
94740         function visitClassDeclaration(node) {
94741             var statements;
94742             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94743                 statements = ts.append(statements, ts.setOriginalNode(ts.setTextRange(factory.createClassDeclaration(
94744                 /*decorators*/ undefined, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
94745                 /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, moduleExpressionElementVisitor), ts.visitNodes(node.members, moduleExpressionElementVisitor)), node), node));
94746             }
94747             else {
94748                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
94749             }
94750             if (hasAssociatedEndOfDeclarationMarker(node)) {
94751                 // Defer exports until we encounter an EndOfDeclarationMarker node
94752                 var id = ts.getOriginalNodeId(node);
94753                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
94754             }
94755             else {
94756                 statements = appendExportsOfHoistedDeclaration(statements, node);
94757             }
94758             return ts.singleOrMany(statements);
94759         }
94760         /**
94761          * Visits a VariableStatement node.
94762          *
94763          * @param node The node to visit.
94764          */
94765         function visitVariableStatement(node) {
94766             var statements;
94767             var variables;
94768             var expressions;
94769             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
94770                 var modifiers = void 0;
94771                 var removeCommentsOnExpressions = false;
94772                 // If we're exporting these variables, then these just become assignments to 'exports.x'.
94773                 for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
94774                     var variable = _a[_i];
94775                     if (ts.isIdentifier(variable.name) && ts.isLocalName(variable.name)) {
94776                         if (!modifiers) {
94777                             modifiers = ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier);
94778                         }
94779                         variables = ts.append(variables, variable);
94780                     }
94781                     else if (variable.initializer) {
94782                         if (!ts.isBindingPattern(variable.name) && (ts.isArrowFunction(variable.initializer) || ts.isFunctionExpression(variable.initializer) || ts.isClassExpression(variable.initializer))) {
94783                             var expression = factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), variable.name), 
94784                             /*location*/ variable.name), factory.createIdentifier(ts.getTextOfIdentifierOrLiteral(variable.name)));
94785                             var updatedVariable = factory.createVariableDeclaration(variable.name, variable.exclamationToken, variable.type, ts.visitNode(variable.initializer, moduleExpressionElementVisitor));
94786                             variables = ts.append(variables, updatedVariable);
94787                             expressions = ts.append(expressions, expression);
94788                             removeCommentsOnExpressions = true;
94789                         }
94790                         else {
94791                             expressions = ts.append(expressions, transformInitializedVariable(variable));
94792                         }
94793                     }
94794                 }
94795                 if (variables) {
94796                     statements = ts.append(statements, factory.updateVariableStatement(node, modifiers, factory.updateVariableDeclarationList(node.declarationList, variables)));
94797                 }
94798                 if (expressions) {
94799                     var statement = ts.setOriginalNode(ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node), node);
94800                     if (removeCommentsOnExpressions) {
94801                         ts.removeAllComments(statement);
94802                     }
94803                     statements = ts.append(statements, statement);
94804                 }
94805             }
94806             else {
94807                 statements = ts.append(statements, ts.visitEachChild(node, moduleExpressionElementVisitor, context));
94808             }
94809             if (hasAssociatedEndOfDeclarationMarker(node)) {
94810                 // Defer exports until we encounter an EndOfDeclarationMarker node
94811                 var id = ts.getOriginalNodeId(node);
94812                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node);
94813             }
94814             else {
94815                 statements = appendExportsOfVariableStatement(statements, node);
94816             }
94817             return ts.singleOrMany(statements);
94818         }
94819         function createAllExportExpressions(name, value, location) {
94820             var exportedNames = getExports(name);
94821             if (exportedNames) {
94822                 // For each additional export of the declaration, apply an export assignment.
94823                 var expression = ts.isExportName(name) ? value : factory.createAssignment(name, value);
94824                 for (var _i = 0, exportedNames_1 = exportedNames; _i < exportedNames_1.length; _i++) {
94825                     var exportName = exportedNames_1[_i];
94826                     // Mark the node to prevent triggering substitution.
94827                     ts.setEmitFlags(expression, 4 /* NoSubstitution */);
94828                     expression = createExportExpression(exportName, expression, /*location*/ location);
94829                 }
94830                 return expression;
94831             }
94832             return factory.createAssignment(name, value);
94833         }
94834         /**
94835          * Transforms an exported variable with an initializer into an expression.
94836          *
94837          * @param node The node to transform.
94838          */
94839         function transformInitializedVariable(node) {
94840             if (ts.isBindingPattern(node.name)) {
94841                 return ts.flattenDestructuringAssignment(ts.visitNode(node, moduleExpressionElementVisitor), 
94842                 /*visitor*/ undefined, context, 0 /* All */, 
94843                 /*needsValue*/ false, createAllExportExpressions);
94844             }
94845             else {
94846                 return factory.createAssignment(ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), node.name), 
94847                 /*location*/ node.name), node.initializer ? ts.visitNode(node.initializer, moduleExpressionElementVisitor) : factory.createVoidZero());
94848             }
94849         }
94850         /**
94851          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
94852          * and transformed declaration.
94853          *
94854          * @param node The node to visit.
94855          */
94856         function visitMergeDeclarationMarker(node) {
94857             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
94858             // declaration we do not emit a leading variable declaration. To preserve the
94859             // begin/end semantics of the declararation and to properly handle exports
94860             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
94861             //
94862             // To balance the declaration, add the exports of the elided variable
94863             // statement.
94864             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) {
94865                 var id = ts.getOriginalNodeId(node);
94866                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original);
94867             }
94868             return node;
94869         }
94870         /**
94871          * Determines whether a node has an associated EndOfDeclarationMarker.
94872          *
94873          * @param node The node to test.
94874          */
94875         function hasAssociatedEndOfDeclarationMarker(node) {
94876             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
94877         }
94878         /**
94879          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
94880          * declaration.
94881          *
94882          * @param node The node to visit.
94883          */
94884         function visitEndOfDeclarationMarker(node) {
94885             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
94886             // end of the transformed declaration. We use this marker to emit any deferred exports
94887             // of the declaration.
94888             var id = ts.getOriginalNodeId(node);
94889             var statements = deferredExports[id];
94890             if (statements) {
94891                 delete deferredExports[id];
94892                 return ts.append(statements, node);
94893             }
94894             return node;
94895         }
94896         /**
94897          * Appends the exports of an ImportDeclaration to a statement list, returning the
94898          * statement list.
94899          *
94900          * @param statements A statement list to which the down-level export statements are to be
94901          * appended. If `statements` is `undefined`, a new array is allocated if statements are
94902          * appended.
94903          * @param decl The declaration whose exports are to be recorded.
94904          */
94905         function appendExportsOfImportDeclaration(statements, decl) {
94906             if (currentModuleInfo.exportEquals) {
94907                 return statements;
94908             }
94909             var importClause = decl.importClause;
94910             if (!importClause) {
94911                 return statements;
94912             }
94913             if (importClause.name) {
94914                 statements = appendExportsOfDeclaration(statements, importClause);
94915             }
94916             var namedBindings = importClause.namedBindings;
94917             if (namedBindings) {
94918                 switch (namedBindings.kind) {
94919                     case 263 /* NamespaceImport */:
94920                         statements = appendExportsOfDeclaration(statements, namedBindings);
94921                         break;
94922                     case 264 /* NamedImports */:
94923                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
94924                             var importBinding = _a[_i];
94925                             statements = appendExportsOfDeclaration(statements, importBinding, /* liveBinding */ true);
94926                         }
94927                         break;
94928                 }
94929             }
94930             return statements;
94931         }
94932         /**
94933          * Appends the exports of an ImportEqualsDeclaration to a statement list, returning the
94934          * statement list.
94935          *
94936          * @param statements A statement list to which the down-level export statements are to be
94937          * appended. If `statements` is `undefined`, a new array is allocated if statements are
94938          * appended.
94939          * @param decl The declaration whose exports are to be recorded.
94940          */
94941         function appendExportsOfImportEqualsDeclaration(statements, decl) {
94942             if (currentModuleInfo.exportEquals) {
94943                 return statements;
94944             }
94945             return appendExportsOfDeclaration(statements, decl);
94946         }
94947         /**
94948          * Appends the exports of a VariableStatement to a statement list, returning the statement
94949          * list.
94950          *
94951          * @param statements A statement list to which the down-level export statements are to be
94952          * appended. If `statements` is `undefined`, a new array is allocated if statements are
94953          * appended.
94954          * @param node The VariableStatement whose exports are to be recorded.
94955          */
94956         function appendExportsOfVariableStatement(statements, node) {
94957             if (currentModuleInfo.exportEquals) {
94958                 return statements;
94959             }
94960             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
94961                 var decl = _a[_i];
94962                 statements = appendExportsOfBindingElement(statements, decl);
94963             }
94964             return statements;
94965         }
94966         /**
94967          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
94968          * returning the statement list.
94969          *
94970          * @param statements A statement list to which the down-level export statements are to be
94971          * appended. If `statements` is `undefined`, a new array is allocated if statements are
94972          * appended.
94973          * @param decl The declaration whose exports are to be recorded.
94974          */
94975         function appendExportsOfBindingElement(statements, decl) {
94976             if (currentModuleInfo.exportEquals) {
94977                 return statements;
94978             }
94979             if (ts.isBindingPattern(decl.name)) {
94980                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
94981                     var element = _a[_i];
94982                     if (!ts.isOmittedExpression(element)) {
94983                         statements = appendExportsOfBindingElement(statements, element);
94984                     }
94985                 }
94986             }
94987             else if (!ts.isGeneratedIdentifier(decl.name)) {
94988                 statements = appendExportsOfDeclaration(statements, decl);
94989             }
94990             return statements;
94991         }
94992         /**
94993          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
94994          * returning the statement list.
94995          *
94996          * @param statements A statement list to which the down-level export statements are to be
94997          * appended. If `statements` is `undefined`, a new array is allocated if statements are
94998          * appended.
94999          * @param decl The declaration whose exports are to be recorded.
95000          */
95001         function appendExportsOfHoistedDeclaration(statements, decl) {
95002             if (currentModuleInfo.exportEquals) {
95003                 return statements;
95004             }
95005             if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
95006                 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createIdentifier("default") : factory.getDeclarationName(decl);
95007                 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl), /*location*/ decl);
95008             }
95009             if (decl.name) {
95010                 statements = appendExportsOfDeclaration(statements, decl);
95011             }
95012             return statements;
95013         }
95014         /**
95015          * Appends the exports of a declaration to a statement list, returning the statement list.
95016          *
95017          * @param statements A statement list to which the down-level export statements are to be
95018          * appended. If `statements` is `undefined`, a new array is allocated if statements are
95019          * appended.
95020          * @param decl The declaration to export.
95021          */
95022         function appendExportsOfDeclaration(statements, decl, liveBinding) {
95023             var name = factory.getDeclarationName(decl);
95024             var exportSpecifiers = currentModuleInfo.exportSpecifiers.get(ts.idText(name));
95025             if (exportSpecifiers) {
95026                 for (var _i = 0, exportSpecifiers_1 = exportSpecifiers; _i < exportSpecifiers_1.length; _i++) {
95027                     var exportSpecifier = exportSpecifiers_1[_i];
95028                     statements = appendExportStatement(statements, exportSpecifier.name, name, /*location*/ exportSpecifier.name, /* allowComments */ undefined, liveBinding);
95029                 }
95030             }
95031             return statements;
95032         }
95033         /**
95034          * Appends the down-level representation of an export to a statement list, returning the
95035          * statement list.
95036          *
95037          * @param statements A statement list to which the down-level export statements are to be
95038          * appended. If `statements` is `undefined`, a new array is allocated if statements are
95039          * appended.
95040          * @param exportName The name of the export.
95041          * @param expression The expression to export.
95042          * @param location The location to use for source maps and comments for the export.
95043          * @param allowComments Whether to allow comments on the export.
95044          */
95045         function appendExportStatement(statements, exportName, expression, location, allowComments, liveBinding) {
95046             statements = ts.append(statements, createExportStatement(exportName, expression, location, allowComments, liveBinding));
95047             return statements;
95048         }
95049         function createUnderscoreUnderscoreESModule() {
95050             var statement;
95051             if (languageVersion === 0 /* ES3 */) {
95052                 statement = factory.createExpressionStatement(createExportExpression(factory.createIdentifier("__esModule"), factory.createTrue()));
95053             }
95054             else {
95055                 statement = factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
95056                 /*typeArguments*/ undefined, [
95057                     factory.createIdentifier("exports"),
95058                     factory.createStringLiteral("__esModule"),
95059                     factory.createObjectLiteralExpression([
95060                         factory.createPropertyAssignment("value", factory.createTrue())
95061                     ])
95062                 ]));
95063             }
95064             ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
95065             return statement;
95066         }
95067         /**
95068          * Creates a call to the current file's export function to export a value.
95069          *
95070          * @param name The bound name of the export.
95071          * @param value The exported value.
95072          * @param location The location to use for source maps and comments for the export.
95073          * @param allowComments An optional value indicating whether to emit comments for the statement.
95074          */
95075         function createExportStatement(name, value, location, allowComments, liveBinding) {
95076             var statement = ts.setTextRange(factory.createExpressionStatement(createExportExpression(name, value, /* location */ undefined, liveBinding)), location);
95077             ts.startOnNewLine(statement);
95078             if (!allowComments) {
95079                 ts.setEmitFlags(statement, 1536 /* NoComments */);
95080             }
95081             return statement;
95082         }
95083         /**
95084          * Creates a call to the current file's export function to export a value.
95085          *
95086          * @param name The bound name of the export.
95087          * @param value The exported value.
95088          * @param location The location to use for source maps and comments for the export.
95089          */
95090         function createExportExpression(name, value, location, liveBinding) {
95091             return ts.setTextRange(liveBinding && languageVersion !== 0 /* ES3 */ ? factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("Object"), "defineProperty"), 
95092             /*typeArguments*/ undefined, [
95093                 factory.createIdentifier("exports"),
95094                 factory.createStringLiteralFromNode(name),
95095                 factory.createObjectLiteralExpression([
95096                     factory.createPropertyAssignment("enumerable", factory.createTrue()),
95097                     factory.createPropertyAssignment("get", factory.createFunctionExpression(
95098                     /*modifiers*/ undefined, 
95099                     /*asteriskToken*/ undefined, 
95100                     /*name*/ undefined, 
95101                     /*typeParameters*/ undefined, 
95102                     /*parameters*/ [], 
95103                     /*type*/ undefined, factory.createBlock([factory.createReturnStatement(value)])))
95104                 ])
95105             ]) : factory.createAssignment(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(name)), value), location);
95106         }
95107         //
95108         // Modifier Visitors
95109         //
95110         /**
95111          * Visit nodes to elide module-specific modifiers.
95112          *
95113          * @param node The node to visit.
95114          */
95115         function modifierVisitor(node) {
95116             // Elide module-specific modifiers.
95117             switch (node.kind) {
95118                 case 92 /* ExportKeyword */:
95119                 case 87 /* DefaultKeyword */:
95120                     return undefined;
95121             }
95122             return node;
95123         }
95124         //
95125         // Emit Notification
95126         //
95127         /**
95128          * Hook for node emit notifications.
95129          *
95130          * @param hint A hint as to the intended usage of the node.
95131          * @param node The node to emit.
95132          * @param emit A callback used to emit the node in the printer.
95133          */
95134         function onEmitNode(hint, node, emitCallback) {
95135             if (node.kind === 297 /* SourceFile */) {
95136                 currentSourceFile = node;
95137                 currentModuleInfo = moduleInfoMap[ts.getOriginalNodeId(currentSourceFile)];
95138                 noSubstitution = [];
95139                 previousOnEmitNode(hint, node, emitCallback);
95140                 currentSourceFile = undefined;
95141                 currentModuleInfo = undefined;
95142                 noSubstitution = undefined;
95143             }
95144             else {
95145                 previousOnEmitNode(hint, node, emitCallback);
95146             }
95147         }
95148         //
95149         // Substitutions
95150         //
95151         /**
95152          * Hooks node substitutions.
95153          *
95154          * @param hint A hint as to the intended usage of the node.
95155          * @param node The node to substitute.
95156          */
95157         function onSubstituteNode(hint, node) {
95158             node = previousOnSubstituteNode(hint, node);
95159             if (node.id && noSubstitution[node.id]) {
95160                 return node;
95161             }
95162             if (hint === 1 /* Expression */) {
95163                 return substituteExpression(node);
95164             }
95165             else if (ts.isShorthandPropertyAssignment(node)) {
95166                 return substituteShorthandPropertyAssignment(node);
95167             }
95168             return node;
95169         }
95170         /**
95171          * Substitution for a ShorthandPropertyAssignment whose declaration name is an imported
95172          * or exported symbol.
95173          *
95174          * @param node The node to substitute.
95175          */
95176         function substituteShorthandPropertyAssignment(node) {
95177             var name = node.name;
95178             var exportedOrImportedName = substituteExpressionIdentifier(name);
95179             if (exportedOrImportedName !== name) {
95180                 // A shorthand property with an assignment initializer is probably part of a
95181                 // destructuring assignment
95182                 if (node.objectAssignmentInitializer) {
95183                     var initializer = factory.createAssignment(exportedOrImportedName, node.objectAssignmentInitializer);
95184                     return ts.setTextRange(factory.createPropertyAssignment(name, initializer), node);
95185                 }
95186                 return ts.setTextRange(factory.createPropertyAssignment(name, exportedOrImportedName), node);
95187             }
95188             return node;
95189         }
95190         /**
95191          * Substitution for an Expression that may contain an imported or exported symbol.
95192          *
95193          * @param node The node to substitute.
95194          */
95195         function substituteExpression(node) {
95196             switch (node.kind) {
95197                 case 78 /* Identifier */:
95198                     return substituteExpressionIdentifier(node);
95199                 case 216 /* BinaryExpression */:
95200                     return substituteBinaryExpression(node);
95201                 case 215 /* PostfixUnaryExpression */:
95202                 case 214 /* PrefixUnaryExpression */:
95203                     return substituteUnaryExpression(node);
95204             }
95205             return node;
95206         }
95207         /**
95208          * Substitution for an Identifier expression that may contain an imported or exported
95209          * symbol.
95210          *
95211          * @param node The node to substitute.
95212          */
95213         function substituteExpressionIdentifier(node) {
95214             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
95215                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
95216                 if (externalHelpersModuleName) {
95217                     return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
95218                 }
95219                 return node;
95220             }
95221             if (!(ts.isGeneratedIdentifier(node) && !(node.autoGenerateFlags & 64 /* AllowNameSubstitution */)) && !ts.isLocalName(node)) {
95222                 var exportContainer = resolver.getReferencedExportContainer(node, ts.isExportName(node));
95223                 if (exportContainer && exportContainer.kind === 297 /* SourceFile */) {
95224                     return ts.setTextRange(factory.createPropertyAccessExpression(factory.createIdentifier("exports"), factory.cloneNode(node)), 
95225                     /*location*/ node);
95226                 }
95227                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
95228                 if (importDeclaration) {
95229                     if (ts.isImportClause(importDeclaration)) {
95230                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), 
95231                         /*location*/ node);
95232                     }
95233                     else if (ts.isImportSpecifier(importDeclaration)) {
95234                         var name = importDeclaration.propertyName || importDeclaration.name;
95235                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(name)), 
95236                         /*location*/ node);
95237                     }
95238                 }
95239             }
95240             return node;
95241         }
95242         /**
95243          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
95244          *
95245          * @param node The node to substitute.
95246          */
95247         function substituteBinaryExpression(node) {
95248             // When we see an assignment expression whose left-hand side is an exported symbol,
95249             // we should ensure all exports of that symbol are updated with the correct value.
95250             //
95251             // - We do not substitute generated identifiers for any reason.
95252             // - We do not substitute identifiers tagged with the LocalName flag.
95253             // - We do not substitute identifiers that were originally the name of an enum or
95254             //   namespace due to how they are transformed in TypeScript.
95255             // - We only substitute identifiers that are exported at the top level.
95256             if (ts.isAssignmentOperator(node.operatorToken.kind)
95257                 && ts.isIdentifier(node.left)
95258                 && !ts.isGeneratedIdentifier(node.left)
95259                 && !ts.isLocalName(node.left)
95260                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
95261                 var exportedNames = getExports(node.left);
95262                 if (exportedNames) {
95263                     // For each additional export of the declaration, apply an export assignment.
95264                     var expression = node;
95265                     for (var _i = 0, exportedNames_2 = exportedNames; _i < exportedNames_2.length; _i++) {
95266                         var exportName = exportedNames_2[_i];
95267                         // Mark the node to prevent triggering this rule again.
95268                         noSubstitution[ts.getNodeId(expression)] = true;
95269                         expression = createExportExpression(exportName, expression, /*location*/ node);
95270                     }
95271                     return expression;
95272                 }
95273             }
95274             return node;
95275         }
95276         /**
95277          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
95278          *
95279          * @param node The node to substitute.
95280          */
95281         function substituteUnaryExpression(node) {
95282             // When we see a prefix or postfix increment expression whose operand is an exported
95283             // symbol, we should ensure all exports of that symbol are updated with the correct
95284             // value.
95285             //
95286             // - We do not substitute generated identifiers for any reason.
95287             // - We do not substitute identifiers tagged with the LocalName flag.
95288             // - We do not substitute identifiers that were originally the name of an enum or
95289             //   namespace due to how they are transformed in TypeScript.
95290             // - We only substitute identifiers that are exported at the top level.
95291             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
95292                 && ts.isIdentifier(node.operand)
95293                 && !ts.isGeneratedIdentifier(node.operand)
95294                 && !ts.isLocalName(node.operand)
95295                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
95296                 var exportedNames = getExports(node.operand);
95297                 if (exportedNames) {
95298                     var expression = node.kind === 215 /* PostfixUnaryExpression */
95299                         ? ts.setTextRange(factory.createBinaryExpression(node.operand, factory.createToken(node.operator === 45 /* PlusPlusToken */ ? 63 /* PlusEqualsToken */ : 64 /* MinusEqualsToken */), factory.createNumericLiteral(1)), 
95300                         /*location*/ node)
95301                         : node;
95302                     for (var _i = 0, exportedNames_3 = exportedNames; _i < exportedNames_3.length; _i++) {
95303                         var exportName = exportedNames_3[_i];
95304                         // Mark the node to prevent triggering this rule again.
95305                         noSubstitution[ts.getNodeId(expression)] = true;
95306                         expression = createExportExpression(exportName, expression);
95307                     }
95308                     return expression;
95309                 }
95310             }
95311             return node;
95312         }
95313         /**
95314          * Gets the additional exports of a name.
95315          *
95316          * @param name The name.
95317          */
95318         function getExports(name) {
95319             if (!ts.isGeneratedIdentifier(name)) {
95320                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
95321                     || resolver.getReferencedValueDeclaration(name);
95322                 if (valueDeclaration) {
95323                     return currentModuleInfo
95324                         && currentModuleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)];
95325                 }
95326             }
95327         }
95328     }
95329     ts.transformModule = transformModule;
95330     // emit helper for dynamic import
95331     var dynamicImportUMDHelper = {
95332         name: "typescript:dynamicimport-sync-require",
95333         scoped: true,
95334         text: "\n            var __syncRequire = typeof module === \"object\" && typeof module.exports === \"object\";"
95335     };
95336 })(ts || (ts = {}));
95337 /*@internal*/
95338 var ts;
95339 (function (ts) {
95340     function transformSystemModule(context) {
95341         var factory = context.factory, startLexicalEnvironment = context.startLexicalEnvironment, endLexicalEnvironment = context.endLexicalEnvironment, hoistVariableDeclaration = context.hoistVariableDeclaration;
95342         var compilerOptions = context.getCompilerOptions();
95343         var resolver = context.getEmitResolver();
95344         var host = context.getEmitHost();
95345         var previousOnSubstituteNode = context.onSubstituteNode;
95346         var previousOnEmitNode = context.onEmitNode;
95347         context.onSubstituteNode = onSubstituteNode;
95348         context.onEmitNode = onEmitNode;
95349         context.enableSubstitution(78 /* Identifier */); // Substitutes expression identifiers for imported symbols.
95350         context.enableSubstitution(289 /* ShorthandPropertyAssignment */); // Substitutes expression identifiers for imported symbols
95351         context.enableSubstitution(216 /* BinaryExpression */); // Substitutes assignments to exported symbols.
95352         context.enableSubstitution(214 /* PrefixUnaryExpression */); // Substitutes updates to exported symbols.
95353         context.enableSubstitution(215 /* PostfixUnaryExpression */); // Substitutes updates to exported symbols.
95354         context.enableSubstitution(226 /* MetaProperty */); // Substitutes 'import.meta'
95355         context.enableEmitNotification(297 /* SourceFile */); // Restore state when substituting nodes in a file.
95356         var moduleInfoMap = []; // The ExternalModuleInfo for each file.
95357         var deferredExports = []; // Exports to defer until an EndOfDeclarationMarker is found.
95358         var exportFunctionsMap = []; // The export function associated with a source file.
95359         var noSubstitutionMap = []; // Set of nodes for which substitution rules should be ignored for each file.
95360         var contextObjectMap = []; // The context object associated with a source file.
95361         var currentSourceFile; // The current file.
95362         var moduleInfo; // ExternalModuleInfo for the current file.
95363         var exportFunction; // The export function for the current file.
95364         var contextObject; // The context object for the current file.
95365         var hoistedStatements;
95366         var enclosingBlockScopedContainer;
95367         var noSubstitution; // Set of nodes for which substitution rules should be ignored.
95368         return ts.chainBundle(context, transformSourceFile);
95369         /**
95370          * Transforms the module aspects of a SourceFile.
95371          *
95372          * @param node The SourceFile node.
95373          */
95374         function transformSourceFile(node) {
95375             if (node.isDeclarationFile || !(ts.isEffectiveExternalModule(node, compilerOptions) || node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
95376                 return node;
95377             }
95378             var id = ts.getOriginalNodeId(node);
95379             currentSourceFile = node;
95380             enclosingBlockScopedContainer = node;
95381             // System modules have the following shape:
95382             //
95383             //     System.register(['dep-1', ... 'dep-n'], function(exports) {/* module body function */})
95384             //
95385             // The parameter 'exports' here is a callback '<T>(name: string, value: T) => T' that
95386             // is used to publish exported values. 'exports' returns its 'value' argument so in
95387             // most cases expressions that mutate exported values can be rewritten as:
95388             //
95389             //     expr -> exports('name', expr)
95390             //
95391             // The only exception in this rule is postfix unary operators,
95392             // see comment to 'substitutePostfixUnaryExpression' for more details
95393             // Collect information about the external module and dependency groups.
95394             moduleInfo = moduleInfoMap[id] = ts.collectExternalModuleInfo(context, node, resolver, compilerOptions);
95395             // Make sure that the name of the 'exports' function does not conflict with
95396             // existing identifiers.
95397             exportFunction = factory.createUniqueName("exports");
95398             exportFunctionsMap[id] = exportFunction;
95399             contextObject = contextObjectMap[id] = factory.createUniqueName("context");
95400             // Add the body of the module.
95401             var dependencyGroups = collectDependencyGroups(moduleInfo.externalImports);
95402             var moduleBodyBlock = createSystemModuleBody(node, dependencyGroups);
95403             var moduleBodyFunction = factory.createFunctionExpression(
95404             /*modifiers*/ undefined, 
95405             /*asteriskToken*/ undefined, 
95406             /*name*/ undefined, 
95407             /*typeParameters*/ undefined, [
95408                 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, exportFunction),
95409                 factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, contextObject)
95410             ], 
95411             /*type*/ undefined, moduleBodyBlock);
95412             // Write the call to `System.register`
95413             // Clear the emit-helpers flag for later passes since we'll have already used it in the module body
95414             // So the helper will be emit at the correct position instead of at the top of the source-file
95415             var moduleName = ts.tryGetModuleNameFromFile(factory, node, host, compilerOptions);
95416             var dependencies = factory.createArrayLiteralExpression(ts.map(dependencyGroups, function (dependencyGroup) { return dependencyGroup.name; }));
95417             var updated = ts.setEmitFlags(factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray([
95418                 factory.createExpressionStatement(factory.createCallExpression(factory.createPropertyAccessExpression(factory.createIdentifier("System"), "register"), 
95419                 /*typeArguments*/ undefined, moduleName
95420                     ? [moduleName, dependencies, moduleBodyFunction]
95421                     : [dependencies, moduleBodyFunction]))
95422             ]), node.statements)), 1024 /* NoTrailingComments */);
95423             if (!ts.outFile(compilerOptions)) {
95424                 ts.moveEmitHelpers(updated, moduleBodyBlock, function (helper) { return !helper.scoped; });
95425             }
95426             if (noSubstitution) {
95427                 noSubstitutionMap[id] = noSubstitution;
95428                 noSubstitution = undefined;
95429             }
95430             currentSourceFile = undefined;
95431             moduleInfo = undefined;
95432             exportFunction = undefined;
95433             contextObject = undefined;
95434             hoistedStatements = undefined;
95435             enclosingBlockScopedContainer = undefined;
95436             return updated;
95437         }
95438         /**
95439          * Collects the dependency groups for this files imports.
95440          *
95441          * @param externalImports The imports for the file.
95442          */
95443         function collectDependencyGroups(externalImports) {
95444             var groupIndices = new ts.Map();
95445             var dependencyGroups = [];
95446             for (var _i = 0, externalImports_1 = externalImports; _i < externalImports_1.length; _i++) {
95447                 var externalImport = externalImports_1[_i];
95448                 var externalModuleName = ts.getExternalModuleNameLiteral(factory, externalImport, currentSourceFile, host, resolver, compilerOptions);
95449                 if (externalModuleName) {
95450                     var text = externalModuleName.text;
95451                     var groupIndex = groupIndices.get(text);
95452                     if (groupIndex !== undefined) {
95453                         // deduplicate/group entries in dependency list by the dependency name
95454                         dependencyGroups[groupIndex].externalImports.push(externalImport);
95455                     }
95456                     else {
95457                         groupIndices.set(text, dependencyGroups.length);
95458                         dependencyGroups.push({
95459                             name: externalModuleName,
95460                             externalImports: [externalImport]
95461                         });
95462                     }
95463                 }
95464             }
95465             return dependencyGroups;
95466         }
95467         /**
95468          * Adds the statements for the module body function for the source file.
95469          *
95470          * @param node The source file for the module.
95471          * @param dependencyGroups The grouped dependencies of the module.
95472          */
95473         function createSystemModuleBody(node, dependencyGroups) {
95474             // Shape of the body in system modules:
95475             //
95476             //  function (exports) {
95477             //      <list of local aliases for imports>
95478             //      <hoisted variable declarations>
95479             //      <hoisted function declarations>
95480             //      return {
95481             //          setters: [
95482             //              <list of setter function for imports>
95483             //          ],
95484             //          execute: function() {
95485             //              <module statements>
95486             //          }
95487             //      }
95488             //      <temp declarations>
95489             //  }
95490             //
95491             // i.e:
95492             //
95493             //   import {x} from 'file1'
95494             //   var y = 1;
95495             //   export function foo() { return y + x(); }
95496             //   console.log(y);
95497             //
95498             // Will be transformed to:
95499             //
95500             //  function(exports) {
95501             //      function foo() { return y + file_1.x(); }
95502             //      exports("foo", foo);
95503             //      var file_1, y;
95504             //      return {
95505             //          setters: [
95506             //              function(v) { file_1 = v }
95507             //          ],
95508             //          execute(): function() {
95509             //              y = 1;
95510             //              console.log(y);
95511             //          }
95512             //      };
95513             //  }
95514             var statements = [];
95515             // We start a new lexical environment in this function body, but *not* in the
95516             // body of the execute function. This allows us to emit temporary declarations
95517             // only in the outer module body and not in the inner one.
95518             startLexicalEnvironment();
95519             // Add any prologue directives.
95520             var ensureUseStrict = ts.getStrictOptionValue(compilerOptions, "alwaysStrict") || (!compilerOptions.noImplicitUseStrict && ts.isExternalModule(currentSourceFile));
95521             var statementOffset = factory.copyPrologue(node.statements, statements, ensureUseStrict, sourceElementVisitor);
95522             // var __moduleName = context_1 && context_1.id;
95523             statements.push(factory.createVariableStatement(
95524             /*modifiers*/ undefined, factory.createVariableDeclarationList([
95525                 factory.createVariableDeclaration("__moduleName", 
95526                 /*exclamationToken*/ undefined, 
95527                 /*type*/ undefined, factory.createLogicalAnd(contextObject, factory.createPropertyAccessExpression(contextObject, "id")))
95528             ])));
95529             // Visit the synthetic external helpers import declaration if present
95530             ts.visitNode(moduleInfo.externalHelpersImportDeclaration, sourceElementVisitor, ts.isStatement);
95531             // Visit the statements of the source file, emitting any transformations into
95532             // the `executeStatements` array. We do this *before* we fill the `setters` array
95533             // as we both emit transformations as well as aggregate some data used when creating
95534             // setters. This allows us to reduce the number of times we need to loop through the
95535             // statements of the source file.
95536             var executeStatements = ts.visitNodes(node.statements, sourceElementVisitor, ts.isStatement, statementOffset);
95537             // Emit early exports for function declarations.
95538             ts.addRange(statements, hoistedStatements);
95539             // We emit hoisted variables early to align roughly with our previous emit output.
95540             // Two key differences in this approach are:
95541             // - Temporary variables will appear at the top rather than at the bottom of the file
95542             ts.insertStatementsAfterStandardPrologue(statements, endLexicalEnvironment());
95543             var exportStarFunction = addExportStarIfNeeded(statements); // TODO: GH#18217
95544             var modifiers = node.transformFlags & 524288 /* ContainsAwait */ ?
95545                 factory.createModifiersFromModifierFlags(256 /* Async */) :
95546                 undefined;
95547             var moduleObject = factory.createObjectLiteralExpression([
95548                 factory.createPropertyAssignment("setters", createSettersArray(exportStarFunction, dependencyGroups)),
95549                 factory.createPropertyAssignment("execute", factory.createFunctionExpression(modifiers, 
95550                 /*asteriskToken*/ undefined, 
95551                 /*name*/ undefined, 
95552                 /*typeParameters*/ undefined, 
95553                 /*parameters*/ [], 
95554                 /*type*/ undefined, factory.createBlock(executeStatements, /*multiLine*/ true)))
95555             ], /*multiLine*/ true);
95556             statements.push(factory.createReturnStatement(moduleObject));
95557             return factory.createBlock(statements, /*multiLine*/ true);
95558         }
95559         /**
95560          * Adds an exportStar function to a statement list if it is needed for the file.
95561          *
95562          * @param statements A statement list.
95563          */
95564         function addExportStarIfNeeded(statements) {
95565             if (!moduleInfo.hasExportStarsToExportValues) {
95566                 return;
95567             }
95568             // when resolving exports local exported entries/indirect exported entries in the module
95569             // should always win over entries with similar names that were added via star exports
95570             // to support this we store names of local/indirect exported entries in a set.
95571             // this set is used to filter names brought by star expors.
95572             // local names set should only be added if we have anything exported
95573             if (!moduleInfo.exportedNames && moduleInfo.exportSpecifiers.size === 0) {
95574                 // no exported declarations (export var ...) or export specifiers (export {x})
95575                 // check if we have any non star export declarations.
95576                 var hasExportDeclarationWithExportClause = false;
95577                 for (var _i = 0, _a = moduleInfo.externalImports; _i < _a.length; _i++) {
95578                     var externalImport = _a[_i];
95579                     if (externalImport.kind === 267 /* ExportDeclaration */ && externalImport.exportClause) {
95580                         hasExportDeclarationWithExportClause = true;
95581                         break;
95582                     }
95583                 }
95584                 if (!hasExportDeclarationWithExportClause) {
95585                     // we still need to emit exportStar helper
95586                     var exportStarFunction_1 = createExportStarFunction(/*localNames*/ undefined);
95587                     statements.push(exportStarFunction_1);
95588                     return exportStarFunction_1.name;
95589                 }
95590             }
95591             var exportedNames = [];
95592             if (moduleInfo.exportedNames) {
95593                 for (var _b = 0, _c = moduleInfo.exportedNames; _b < _c.length; _b++) {
95594                     var exportedLocalName = _c[_b];
95595                     if (exportedLocalName.escapedText === "default") {
95596                         continue;
95597                     }
95598                     // write name of exported declaration, i.e 'export var x...'
95599                     exportedNames.push(factory.createPropertyAssignment(factory.createStringLiteralFromNode(exportedLocalName), factory.createTrue()));
95600                 }
95601             }
95602             var exportedNamesStorageRef = factory.createUniqueName("exportedNames");
95603             statements.push(factory.createVariableStatement(
95604             /*modifiers*/ undefined, factory.createVariableDeclarationList([
95605                 factory.createVariableDeclaration(exportedNamesStorageRef, 
95606                 /*exclamationToken*/ undefined, 
95607                 /*type*/ undefined, factory.createObjectLiteralExpression(exportedNames, /*multiline*/ true))
95608             ])));
95609             var exportStarFunction = createExportStarFunction(exportedNamesStorageRef);
95610             statements.push(exportStarFunction);
95611             return exportStarFunction.name;
95612         }
95613         /**
95614          * Creates an exportStar function for the file, with an optional set of excluded local
95615          * names.
95616          *
95617          * @param localNames An optional reference to an object containing a set of excluded local
95618          * names.
95619          */
95620         function createExportStarFunction(localNames) {
95621             var exportStarFunction = factory.createUniqueName("exportStar");
95622             var m = factory.createIdentifier("m");
95623             var n = factory.createIdentifier("n");
95624             var exports = factory.createIdentifier("exports");
95625             var condition = factory.createStrictInequality(n, factory.createStringLiteral("default"));
95626             if (localNames) {
95627                 condition = factory.createLogicalAnd(condition, factory.createLogicalNot(factory.createCallExpression(factory.createPropertyAccessExpression(localNames, "hasOwnProperty"), 
95628                 /*typeArguments*/ undefined, [n])));
95629             }
95630             return factory.createFunctionDeclaration(
95631             /*decorators*/ undefined, 
95632             /*modifiers*/ undefined, 
95633             /*asteriskToken*/ undefined, exportStarFunction, 
95634             /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, m)], 
95635             /*type*/ undefined, factory.createBlock([
95636                 factory.createVariableStatement(
95637                 /*modifiers*/ undefined, factory.createVariableDeclarationList([
95638                     factory.createVariableDeclaration(exports, 
95639                     /*exclamationToken*/ undefined, 
95640                     /*type*/ undefined, factory.createObjectLiteralExpression([]))
95641                 ])),
95642                 factory.createForInStatement(factory.createVariableDeclarationList([
95643                     factory.createVariableDeclaration(n)
95644                 ]), m, factory.createBlock([
95645                     ts.setEmitFlags(factory.createIfStatement(condition, factory.createExpressionStatement(factory.createAssignment(factory.createElementAccessExpression(exports, n), factory.createElementAccessExpression(m, n)))), 1 /* SingleLine */)
95646                 ])),
95647                 factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
95648                 /*typeArguments*/ undefined, [exports]))
95649             ], /*multiline*/ true));
95650         }
95651         /**
95652          * Creates an array setter callbacks for each dependency group.
95653          *
95654          * @param exportStarFunction A reference to an exportStarFunction for the file.
95655          * @param dependencyGroups An array of grouped dependencies.
95656          */
95657         function createSettersArray(exportStarFunction, dependencyGroups) {
95658             var setters = [];
95659             for (var _i = 0, dependencyGroups_1 = dependencyGroups; _i < dependencyGroups_1.length; _i++) {
95660                 var group_2 = dependencyGroups_1[_i];
95661                 // derive a unique name for parameter from the first named entry in the group
95662                 var localName = ts.forEach(group_2.externalImports, function (i) { return ts.getLocalNameForExternalImport(factory, i, currentSourceFile); });
95663                 var parameterName = localName ? factory.getGeneratedNameForNode(localName) : factory.createUniqueName("");
95664                 var statements = [];
95665                 for (var _a = 0, _b = group_2.externalImports; _a < _b.length; _a++) {
95666                     var entry = _b[_a];
95667                     var importVariableName = ts.getLocalNameForExternalImport(factory, entry, currentSourceFile); // TODO: GH#18217
95668                     switch (entry.kind) {
95669                         case 261 /* ImportDeclaration */:
95670                             if (!entry.importClause) {
95671                                 // 'import "..."' case
95672                                 // module is imported only for side-effects, no emit required
95673                                 break;
95674                             }
95675                         // falls through
95676                         case 260 /* ImportEqualsDeclaration */:
95677                             ts.Debug.assert(importVariableName !== undefined);
95678                             // save import into the local
95679                             statements.push(factory.createExpressionStatement(factory.createAssignment(importVariableName, parameterName)));
95680                             break;
95681                         case 267 /* ExportDeclaration */:
95682                             ts.Debug.assert(importVariableName !== undefined);
95683                             if (entry.exportClause) {
95684                                 if (ts.isNamedExports(entry.exportClause)) {
95685                                     //  export {a, b as c} from 'foo'
95686                                     //
95687                                     // emit as:
95688                                     //
95689                                     //  exports_({
95690                                     //     "a": _["a"],
95691                                     //     "c": _["b"]
95692                                     //  });
95693                                     var properties = [];
95694                                     for (var _c = 0, _d = entry.exportClause.elements; _c < _d.length; _c++) {
95695                                         var e = _d[_c];
95696                                         properties.push(factory.createPropertyAssignment(factory.createStringLiteral(ts.idText(e.name)), factory.createElementAccessExpression(parameterName, factory.createStringLiteral(ts.idText(e.propertyName || e.name)))));
95697                                     }
95698                                     statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
95699                                     /*typeArguments*/ undefined, [factory.createObjectLiteralExpression(properties, /*multiline*/ true)])));
95700                                 }
95701                                 else {
95702                                     statements.push(factory.createExpressionStatement(factory.createCallExpression(exportFunction, 
95703                                     /*typeArguments*/ undefined, [
95704                                         factory.createStringLiteral(ts.idText(entry.exportClause.name)),
95705                                         parameterName
95706                                     ])));
95707                                 }
95708                             }
95709                             else {
95710                                 //  export * from 'foo'
95711                                 //
95712                                 // emit as:
95713                                 //
95714                                 //  exportStar(foo_1_1);
95715                                 statements.push(factory.createExpressionStatement(factory.createCallExpression(exportStarFunction, 
95716                                 /*typeArguments*/ undefined, [parameterName])));
95717                             }
95718                             break;
95719                     }
95720                 }
95721                 setters.push(factory.createFunctionExpression(
95722                 /*modifiers*/ undefined, 
95723                 /*asteriskToken*/ undefined, 
95724                 /*name*/ undefined, 
95725                 /*typeParameters*/ undefined, [factory.createParameterDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*dotDotDotToken*/ undefined, parameterName)], 
95726                 /*type*/ undefined, factory.createBlock(statements, /*multiLine*/ true)));
95727             }
95728             return factory.createArrayLiteralExpression(setters, /*multiLine*/ true);
95729         }
95730         //
95731         // Top-level Source Element Visitors
95732         //
95733         /**
95734          * Visit source elements at the top-level of a module.
95735          *
95736          * @param node The node to visit.
95737          */
95738         function sourceElementVisitor(node) {
95739             switch (node.kind) {
95740                 case 261 /* ImportDeclaration */:
95741                     return visitImportDeclaration(node);
95742                 case 260 /* ImportEqualsDeclaration */:
95743                     return visitImportEqualsDeclaration(node);
95744                 case 267 /* ExportDeclaration */:
95745                     return visitExportDeclaration(node);
95746                 case 266 /* ExportAssignment */:
95747                     return visitExportAssignment(node);
95748                 default:
95749                     return nestedElementVisitor(node);
95750             }
95751         }
95752         /**
95753          * Visits an ImportDeclaration node.
95754          *
95755          * @param node The node to visit.
95756          */
95757         function visitImportDeclaration(node) {
95758             var statements;
95759             if (node.importClause) {
95760                 hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
95761             }
95762             if (hasAssociatedEndOfDeclarationMarker(node)) {
95763                 // Defer exports until we encounter an EndOfDeclarationMarker node
95764                 var id = ts.getOriginalNodeId(node);
95765                 deferredExports[id] = appendExportsOfImportDeclaration(deferredExports[id], node);
95766             }
95767             else {
95768                 statements = appendExportsOfImportDeclaration(statements, node);
95769             }
95770             return ts.singleOrMany(statements);
95771         }
95772         function visitExportDeclaration(node) {
95773             ts.Debug.assertIsDefined(node);
95774             return undefined;
95775         }
95776         /**
95777          * Visits an ImportEqualsDeclaration node.
95778          *
95779          * @param node The node to visit.
95780          */
95781         function visitImportEqualsDeclaration(node) {
95782             ts.Debug.assert(ts.isExternalModuleImportEqualsDeclaration(node), "import= for internal module references should be handled in an earlier transformer.");
95783             var statements;
95784             hoistVariableDeclaration(ts.getLocalNameForExternalImport(factory, node, currentSourceFile)); // TODO: GH#18217
95785             if (hasAssociatedEndOfDeclarationMarker(node)) {
95786                 // Defer exports until we encounter an EndOfDeclarationMarker node
95787                 var id = ts.getOriginalNodeId(node);
95788                 deferredExports[id] = appendExportsOfImportEqualsDeclaration(deferredExports[id], node);
95789             }
95790             else {
95791                 statements = appendExportsOfImportEqualsDeclaration(statements, node);
95792             }
95793             return ts.singleOrMany(statements);
95794         }
95795         /**
95796          * Visits an ExportAssignment node.
95797          *
95798          * @param node The node to visit.
95799          */
95800         function visitExportAssignment(node) {
95801             if (node.isExportEquals) {
95802                 // Elide `export=` as it is illegal in a SystemJS module.
95803                 return undefined;
95804             }
95805             var expression = ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression);
95806             var original = node.original;
95807             if (original && hasAssociatedEndOfDeclarationMarker(original)) {
95808                 // Defer exports until we encounter an EndOfDeclarationMarker node
95809                 var id = ts.getOriginalNodeId(node);
95810                 deferredExports[id] = appendExportStatement(deferredExports[id], factory.createIdentifier("default"), expression, /*allowComments*/ true);
95811             }
95812             else {
95813                 return createExportStatement(factory.createIdentifier("default"), expression, /*allowComments*/ true);
95814             }
95815         }
95816         /**
95817          * Visits a FunctionDeclaration, hoisting it to the outer module body function.
95818          *
95819          * @param node The node to visit.
95820          */
95821         function visitFunctionDeclaration(node) {
95822             if (ts.hasSyntacticModifier(node, 1 /* Export */)) {
95823                 hoistedStatements = ts.append(hoistedStatements, factory.updateFunctionDeclaration(node, node.decorators, ts.visitNodes(node.modifiers, modifierVisitor, ts.isModifier), node.asteriskToken, factory.getDeclarationName(node, /*allowComments*/ true, /*allowSourceMaps*/ true), 
95824                 /*typeParameters*/ undefined, ts.visitNodes(node.parameters, destructuringAndImportCallVisitor, ts.isParameterDeclaration), 
95825                 /*type*/ undefined, ts.visitNode(node.body, destructuringAndImportCallVisitor, ts.isBlock)));
95826             }
95827             else {
95828                 hoistedStatements = ts.append(hoistedStatements, ts.visitEachChild(node, destructuringAndImportCallVisitor, context));
95829             }
95830             if (hasAssociatedEndOfDeclarationMarker(node)) {
95831                 // Defer exports until we encounter an EndOfDeclarationMarker node
95832                 var id = ts.getOriginalNodeId(node);
95833                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
95834             }
95835             else {
95836                 hoistedStatements = appendExportsOfHoistedDeclaration(hoistedStatements, node);
95837             }
95838             return undefined;
95839         }
95840         /**
95841          * Visits a ClassDeclaration, hoisting its name to the outer module body function.
95842          *
95843          * @param node The node to visit.
95844          */
95845         function visitClassDeclaration(node) {
95846             var statements;
95847             // Hoist the name of the class declaration to the outer module body function.
95848             var name = factory.getLocalName(node);
95849             hoistVariableDeclaration(name);
95850             // Rewrite the class declaration into an assignment of a class expression.
95851             statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.createAssignment(name, ts.setTextRange(factory.createClassExpression(ts.visitNodes(node.decorators, destructuringAndImportCallVisitor, ts.isDecorator), 
95852             /*modifiers*/ undefined, node.name, 
95853             /*typeParameters*/ undefined, ts.visitNodes(node.heritageClauses, destructuringAndImportCallVisitor, ts.isHeritageClause), ts.visitNodes(node.members, destructuringAndImportCallVisitor, ts.isClassElement)), node))), node));
95854             if (hasAssociatedEndOfDeclarationMarker(node)) {
95855                 // Defer exports until we encounter an EndOfDeclarationMarker node
95856                 var id = ts.getOriginalNodeId(node);
95857                 deferredExports[id] = appendExportsOfHoistedDeclaration(deferredExports[id], node);
95858             }
95859             else {
95860                 statements = appendExportsOfHoistedDeclaration(statements, node);
95861             }
95862             return ts.singleOrMany(statements);
95863         }
95864         /**
95865          * Visits a variable statement, hoisting declared names to the top-level module body.
95866          * Each declaration is rewritten into an assignment expression.
95867          *
95868          * @param node The node to visit.
95869          */
95870         function visitVariableStatement(node) {
95871             if (!shouldHoistVariableDeclarationList(node.declarationList)) {
95872                 return ts.visitNode(node, destructuringAndImportCallVisitor, ts.isStatement);
95873             }
95874             var expressions;
95875             var isExportedDeclaration = ts.hasSyntacticModifier(node, 1 /* Export */);
95876             var isMarkedDeclaration = hasAssociatedEndOfDeclarationMarker(node);
95877             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
95878                 var variable = _a[_i];
95879                 if (variable.initializer) {
95880                     expressions = ts.append(expressions, transformInitializedVariable(variable, isExportedDeclaration && !isMarkedDeclaration));
95881                 }
95882                 else {
95883                     hoistBindingElement(variable);
95884                 }
95885             }
95886             var statements;
95887             if (expressions) {
95888                 statements = ts.append(statements, ts.setTextRange(factory.createExpressionStatement(factory.inlineExpressions(expressions)), node));
95889             }
95890             if (isMarkedDeclaration) {
95891                 // Defer exports until we encounter an EndOfDeclarationMarker node
95892                 var id = ts.getOriginalNodeId(node);
95893                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node, isExportedDeclaration);
95894             }
95895             else {
95896                 statements = appendExportsOfVariableStatement(statements, node, /*exportSelf*/ false);
95897             }
95898             return ts.singleOrMany(statements);
95899         }
95900         /**
95901          * Hoists the declared names of a VariableDeclaration or BindingElement.
95902          *
95903          * @param node The declaration to hoist.
95904          */
95905         function hoistBindingElement(node) {
95906             if (ts.isBindingPattern(node.name)) {
95907                 for (var _i = 0, _a = node.name.elements; _i < _a.length; _i++) {
95908                     var element = _a[_i];
95909                     if (!ts.isOmittedExpression(element)) {
95910                         hoistBindingElement(element);
95911                     }
95912                 }
95913             }
95914             else {
95915                 hoistVariableDeclaration(factory.cloneNode(node.name));
95916             }
95917         }
95918         /**
95919          * Determines whether a VariableDeclarationList should be hoisted.
95920          *
95921          * @param node The node to test.
95922          */
95923         function shouldHoistVariableDeclarationList(node) {
95924             // hoist only non-block scoped declarations or block scoped declarations parented by source file
95925             return (ts.getEmitFlags(node) & 2097152 /* NoHoisting */) === 0
95926                 && (enclosingBlockScopedContainer.kind === 297 /* SourceFile */
95927                     || (ts.getOriginalNode(node).flags & 3 /* BlockScoped */) === 0);
95928         }
95929         /**
95930          * Transform an initialized variable declaration into an expression.
95931          *
95932          * @param node The node to transform.
95933          * @param isExportedDeclaration A value indicating whether the variable is exported.
95934          */
95935         function transformInitializedVariable(node, isExportedDeclaration) {
95936             var createAssignment = isExportedDeclaration ? createExportedVariableAssignment : createNonExportedVariableAssignment;
95937             return ts.isBindingPattern(node.name)
95938                 ? ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
95939                 /*needsValue*/ false, createAssignment)
95940                 : node.initializer ? createAssignment(node.name, ts.visitNode(node.initializer, destructuringAndImportCallVisitor, ts.isExpression)) : node.name;
95941         }
95942         /**
95943          * Creates an assignment expression for an exported variable declaration.
95944          *
95945          * @param name The name of the variable.
95946          * @param value The value of the variable's initializer.
95947          * @param location The source map location for the assignment.
95948          */
95949         function createExportedVariableAssignment(name, value, location) {
95950             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ true);
95951         }
95952         /**
95953          * Creates an assignment expression for a non-exported variable declaration.
95954          *
95955          * @param name The name of the variable.
95956          * @param value The value of the variable's initializer.
95957          * @param location The source map location for the assignment.
95958          */
95959         function createNonExportedVariableAssignment(name, value, location) {
95960             return createVariableAssignment(name, value, location, /*isExportedDeclaration*/ false);
95961         }
95962         /**
95963          * Creates an assignment expression for a variable declaration.
95964          *
95965          * @param name The name of the variable.
95966          * @param value The value of the variable's initializer.
95967          * @param location The source map location for the assignment.
95968          * @param isExportedDeclaration A value indicating whether the variable is exported.
95969          */
95970         function createVariableAssignment(name, value, location, isExportedDeclaration) {
95971             hoistVariableDeclaration(factory.cloneNode(name));
95972             return isExportedDeclaration
95973                 ? createExportExpression(name, preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location)))
95974                 : preventSubstitution(ts.setTextRange(factory.createAssignment(name, value), location));
95975         }
95976         /**
95977          * Visits a MergeDeclarationMarker used as a placeholder for the beginning of a merged
95978          * and transformed declaration.
95979          *
95980          * @param node The node to visit.
95981          */
95982         function visitMergeDeclarationMarker(node) {
95983             // For an EnumDeclaration or ModuleDeclaration that merges with a preceeding
95984             // declaration we do not emit a leading variable declaration. To preserve the
95985             // begin/end semantics of the declararation and to properly handle exports
95986             // we wrapped the leading variable declaration in a `MergeDeclarationMarker`.
95987             //
95988             // To balance the declaration, we defer the exports of the elided variable
95989             // statement until we visit this declaration's `EndOfDeclarationMarker`.
95990             if (hasAssociatedEndOfDeclarationMarker(node) && node.original.kind === 232 /* VariableStatement */) {
95991                 var id = ts.getOriginalNodeId(node);
95992                 var isExportedDeclaration = ts.hasSyntacticModifier(node.original, 1 /* Export */);
95993                 deferredExports[id] = appendExportsOfVariableStatement(deferredExports[id], node.original, isExportedDeclaration);
95994             }
95995             return node;
95996         }
95997         /**
95998          * Determines whether a node has an associated EndOfDeclarationMarker.
95999          *
96000          * @param node The node to test.
96001          */
96002         function hasAssociatedEndOfDeclarationMarker(node) {
96003             return (ts.getEmitFlags(node) & 4194304 /* HasEndOfDeclarationMarker */) !== 0;
96004         }
96005         /**
96006          * Visits a DeclarationMarker used as a placeholder for the end of a transformed
96007          * declaration.
96008          *
96009          * @param node The node to visit.
96010          */
96011         function visitEndOfDeclarationMarker(node) {
96012             // For some transformations we emit an `EndOfDeclarationMarker` to mark the actual
96013             // end of the transformed declaration. We use this marker to emit any deferred exports
96014             // of the declaration.
96015             var id = ts.getOriginalNodeId(node);
96016             var statements = deferredExports[id];
96017             if (statements) {
96018                 delete deferredExports[id];
96019                 return ts.append(statements, node);
96020             }
96021             else {
96022                 var original = ts.getOriginalNode(node);
96023                 if (ts.isModuleOrEnumDeclaration(original)) {
96024                     return ts.append(appendExportsOfDeclaration(statements, original), node);
96025                 }
96026             }
96027             return node;
96028         }
96029         /**
96030          * Appends the exports of an ImportDeclaration to a statement list, returning the
96031          * statement list.
96032          *
96033          * @param statements A statement list to which the down-level export statements are to be
96034          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96035          * appended.
96036          * @param decl The declaration whose exports are to be recorded.
96037          */
96038         function appendExportsOfImportDeclaration(statements, decl) {
96039             if (moduleInfo.exportEquals) {
96040                 return statements;
96041             }
96042             var importClause = decl.importClause;
96043             if (!importClause) {
96044                 return statements;
96045             }
96046             if (importClause.name) {
96047                 statements = appendExportsOfDeclaration(statements, importClause);
96048             }
96049             var namedBindings = importClause.namedBindings;
96050             if (namedBindings) {
96051                 switch (namedBindings.kind) {
96052                     case 263 /* NamespaceImport */:
96053                         statements = appendExportsOfDeclaration(statements, namedBindings);
96054                         break;
96055                     case 264 /* NamedImports */:
96056                         for (var _i = 0, _a = namedBindings.elements; _i < _a.length; _i++) {
96057                             var importBinding = _a[_i];
96058                             statements = appendExportsOfDeclaration(statements, importBinding);
96059                         }
96060                         break;
96061                 }
96062             }
96063             return statements;
96064         }
96065         /**
96066          * Appends the export of an ImportEqualsDeclaration to a statement list, returning the
96067          * statement list.
96068          *
96069          * @param statements A statement list to which the down-level export statements are to be
96070          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96071          * appended.
96072          * @param decl The declaration whose exports are to be recorded.
96073          */
96074         function appendExportsOfImportEqualsDeclaration(statements, decl) {
96075             if (moduleInfo.exportEquals) {
96076                 return statements;
96077             }
96078             return appendExportsOfDeclaration(statements, decl);
96079         }
96080         /**
96081          * Appends the exports of a VariableStatement to a statement list, returning the statement
96082          * list.
96083          *
96084          * @param statements A statement list to which the down-level export statements are to be
96085          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96086          * appended.
96087          * @param node The VariableStatement whose exports are to be recorded.
96088          * @param exportSelf A value indicating whether to also export each VariableDeclaration of
96089          * `nodes` declaration list.
96090          */
96091         function appendExportsOfVariableStatement(statements, node, exportSelf) {
96092             if (moduleInfo.exportEquals) {
96093                 return statements;
96094             }
96095             for (var _i = 0, _a = node.declarationList.declarations; _i < _a.length; _i++) {
96096                 var decl = _a[_i];
96097                 if (decl.initializer || exportSelf) {
96098                     statements = appendExportsOfBindingElement(statements, decl, exportSelf);
96099                 }
96100             }
96101             return statements;
96102         }
96103         /**
96104          * Appends the exports of a VariableDeclaration or BindingElement to a statement list,
96105          * returning the statement list.
96106          *
96107          * @param statements A statement list to which the down-level export statements are to be
96108          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96109          * appended.
96110          * @param decl The declaration whose exports are to be recorded.
96111          * @param exportSelf A value indicating whether to also export the declaration itself.
96112          */
96113         function appendExportsOfBindingElement(statements, decl, exportSelf) {
96114             if (moduleInfo.exportEquals) {
96115                 return statements;
96116             }
96117             if (ts.isBindingPattern(decl.name)) {
96118                 for (var _i = 0, _a = decl.name.elements; _i < _a.length; _i++) {
96119                     var element = _a[_i];
96120                     if (!ts.isOmittedExpression(element)) {
96121                         statements = appendExportsOfBindingElement(statements, element, exportSelf);
96122                     }
96123                 }
96124             }
96125             else if (!ts.isGeneratedIdentifier(decl.name)) {
96126                 var excludeName = void 0;
96127                 if (exportSelf) {
96128                     statements = appendExportStatement(statements, decl.name, factory.getLocalName(decl));
96129                     excludeName = ts.idText(decl.name);
96130                 }
96131                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
96132             }
96133             return statements;
96134         }
96135         /**
96136          * Appends the exports of a ClassDeclaration or FunctionDeclaration to a statement list,
96137          * returning the statement list.
96138          *
96139          * @param statements A statement list to which the down-level export statements are to be
96140          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96141          * appended.
96142          * @param decl The declaration whose exports are to be recorded.
96143          */
96144         function appendExportsOfHoistedDeclaration(statements, decl) {
96145             if (moduleInfo.exportEquals) {
96146                 return statements;
96147             }
96148             var excludeName;
96149             if (ts.hasSyntacticModifier(decl, 1 /* Export */)) {
96150                 var exportName = ts.hasSyntacticModifier(decl, 512 /* Default */) ? factory.createStringLiteral("default") : decl.name;
96151                 statements = appendExportStatement(statements, exportName, factory.getLocalName(decl));
96152                 excludeName = ts.getTextOfIdentifierOrLiteral(exportName);
96153             }
96154             if (decl.name) {
96155                 statements = appendExportsOfDeclaration(statements, decl, excludeName);
96156             }
96157             return statements;
96158         }
96159         /**
96160          * Appends the exports of a declaration to a statement list, returning the statement list.
96161          *
96162          * @param statements A statement list to which the down-level export statements are to be
96163          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96164          * appended.
96165          * @param decl The declaration to export.
96166          * @param excludeName An optional name to exclude from exports.
96167          */
96168         function appendExportsOfDeclaration(statements, decl, excludeName) {
96169             if (moduleInfo.exportEquals) {
96170                 return statements;
96171             }
96172             var name = factory.getDeclarationName(decl);
96173             var exportSpecifiers = moduleInfo.exportSpecifiers.get(ts.idText(name));
96174             if (exportSpecifiers) {
96175                 for (var _i = 0, exportSpecifiers_2 = exportSpecifiers; _i < exportSpecifiers_2.length; _i++) {
96176                     var exportSpecifier = exportSpecifiers_2[_i];
96177                     if (exportSpecifier.name.escapedText !== excludeName) {
96178                         statements = appendExportStatement(statements, exportSpecifier.name, name);
96179                     }
96180                 }
96181             }
96182             return statements;
96183         }
96184         /**
96185          * Appends the down-level representation of an export to a statement list, returning the
96186          * statement list.
96187          *
96188          * @param statements A statement list to which the down-level export statements are to be
96189          * appended. If `statements` is `undefined`, a new array is allocated if statements are
96190          * appended.
96191          * @param exportName The name of the export.
96192          * @param expression The expression to export.
96193          * @param allowComments Whether to allow comments on the export.
96194          */
96195         function appendExportStatement(statements, exportName, expression, allowComments) {
96196             statements = ts.append(statements, createExportStatement(exportName, expression, allowComments));
96197             return statements;
96198         }
96199         /**
96200          * Creates a call to the current file's export function to export a value.
96201          *
96202          * @param name The bound name of the export.
96203          * @param value The exported value.
96204          * @param allowComments An optional value indicating whether to emit comments for the statement.
96205          */
96206         function createExportStatement(name, value, allowComments) {
96207             var statement = factory.createExpressionStatement(createExportExpression(name, value));
96208             ts.startOnNewLine(statement);
96209             if (!allowComments) {
96210                 ts.setEmitFlags(statement, 1536 /* NoComments */);
96211             }
96212             return statement;
96213         }
96214         /**
96215          * Creates a call to the current file's export function to export a value.
96216          *
96217          * @param name The bound name of the export.
96218          * @param value The exported value.
96219          */
96220         function createExportExpression(name, value) {
96221             var exportName = ts.isIdentifier(name) ? factory.createStringLiteralFromNode(name) : name;
96222             ts.setEmitFlags(value, ts.getEmitFlags(value) | 1536 /* NoComments */);
96223             return ts.setCommentRange(factory.createCallExpression(exportFunction, /*typeArguments*/ undefined, [exportName, value]), value);
96224         }
96225         //
96226         // Top-Level or Nested Source Element Visitors
96227         //
96228         /**
96229          * Visit nested elements at the top-level of a module.
96230          *
96231          * @param node The node to visit.
96232          */
96233         function nestedElementVisitor(node) {
96234             switch (node.kind) {
96235                 case 232 /* VariableStatement */:
96236                     return visitVariableStatement(node);
96237                 case 251 /* FunctionDeclaration */:
96238                     return visitFunctionDeclaration(node);
96239                 case 252 /* ClassDeclaration */:
96240                     return visitClassDeclaration(node);
96241                 case 237 /* ForStatement */:
96242                     return visitForStatement(node);
96243                 case 238 /* ForInStatement */:
96244                     return visitForInStatement(node);
96245                 case 239 /* ForOfStatement */:
96246                     return visitForOfStatement(node);
96247                 case 235 /* DoStatement */:
96248                     return visitDoStatement(node);
96249                 case 236 /* WhileStatement */:
96250                     return visitWhileStatement(node);
96251                 case 245 /* LabeledStatement */:
96252                     return visitLabeledStatement(node);
96253                 case 243 /* WithStatement */:
96254                     return visitWithStatement(node);
96255                 case 244 /* SwitchStatement */:
96256                     return visitSwitchStatement(node);
96257                 case 258 /* CaseBlock */:
96258                     return visitCaseBlock(node);
96259                 case 284 /* CaseClause */:
96260                     return visitCaseClause(node);
96261                 case 285 /* DefaultClause */:
96262                     return visitDefaultClause(node);
96263                 case 247 /* TryStatement */:
96264                     return visitTryStatement(node);
96265                 case 287 /* CatchClause */:
96266                     return visitCatchClause(node);
96267                 case 230 /* Block */:
96268                     return visitBlock(node);
96269                 case 338 /* MergeDeclarationMarker */:
96270                     return visitMergeDeclarationMarker(node);
96271                 case 339 /* EndOfDeclarationMarker */:
96272                     return visitEndOfDeclarationMarker(node);
96273                 default:
96274                     return destructuringAndImportCallVisitor(node);
96275             }
96276         }
96277         /**
96278          * Visits the body of a ForStatement to hoist declarations.
96279          *
96280          * @param node The node to visit.
96281          */
96282         function visitForStatement(node) {
96283             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96284             enclosingBlockScopedContainer = node;
96285             node = factory.updateForStatement(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));
96286             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96287             return node;
96288         }
96289         /**
96290          * Visits the body of a ForInStatement to hoist declarations.
96291          *
96292          * @param node The node to visit.
96293          */
96294         function visitForInStatement(node) {
96295             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96296             enclosingBlockScopedContainer = node;
96297             node = factory.updateForInStatement(node, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96298             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96299             return node;
96300         }
96301         /**
96302          * Visits the body of a ForOfStatement to hoist declarations.
96303          *
96304          * @param node The node to visit.
96305          */
96306         function visitForOfStatement(node) {
96307             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96308             enclosingBlockScopedContainer = node;
96309             node = factory.updateForOfStatement(node, node.awaitModifier, visitForInitializer(node.initializer), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96310             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96311             return node;
96312         }
96313         /**
96314          * Determines whether to hoist the initializer of a ForStatement, ForInStatement, or
96315          * ForOfStatement.
96316          *
96317          * @param node The node to test.
96318          */
96319         function shouldHoistForInitializer(node) {
96320             return ts.isVariableDeclarationList(node)
96321                 && shouldHoistVariableDeclarationList(node);
96322         }
96323         /**
96324          * Visits the initializer of a ForStatement, ForInStatement, or ForOfStatement
96325          *
96326          * @param node The node to visit.
96327          */
96328         function visitForInitializer(node) {
96329             if (shouldHoistForInitializer(node)) {
96330                 var expressions = void 0;
96331                 for (var _i = 0, _a = node.declarations; _i < _a.length; _i++) {
96332                     var variable = _a[_i];
96333                     expressions = ts.append(expressions, transformInitializedVariable(variable, /*isExportedDeclaration*/ false));
96334                     if (!variable.initializer) {
96335                         hoistBindingElement(variable);
96336                     }
96337                 }
96338                 return expressions ? factory.inlineExpressions(expressions) : factory.createOmittedExpression();
96339             }
96340             else {
96341                 return ts.visitEachChild(node, nestedElementVisitor, context);
96342             }
96343         }
96344         /**
96345          * Visits the body of a DoStatement to hoist declarations.
96346          *
96347          * @param node The node to visit.
96348          */
96349         function visitDoStatement(node) {
96350             return factory.updateDoStatement(node, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock), ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression));
96351         }
96352         /**
96353          * Visits the body of a WhileStatement to hoist declarations.
96354          *
96355          * @param node The node to visit.
96356          */
96357         function visitWhileStatement(node) {
96358             return factory.updateWhileStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96359         }
96360         /**
96361          * Visits the body of a LabeledStatement to hoist declarations.
96362          *
96363          * @param node The node to visit.
96364          */
96365         function visitLabeledStatement(node) {
96366             return factory.updateLabeledStatement(node, node.label, ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96367         }
96368         /**
96369          * Visits the body of a WithStatement to hoist declarations.
96370          *
96371          * @param node The node to visit.
96372          */
96373         function visitWithStatement(node) {
96374             return factory.updateWithStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.statement, nestedElementVisitor, ts.isStatement, factory.liftToBlock));
96375         }
96376         /**
96377          * Visits the body of a SwitchStatement to hoist declarations.
96378          *
96379          * @param node The node to visit.
96380          */
96381         function visitSwitchStatement(node) {
96382             return factory.updateSwitchStatement(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNode(node.caseBlock, nestedElementVisitor, ts.isCaseBlock));
96383         }
96384         /**
96385          * Visits the body of a CaseBlock to hoist declarations.
96386          *
96387          * @param node The node to visit.
96388          */
96389         function visitCaseBlock(node) {
96390             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96391             enclosingBlockScopedContainer = node;
96392             node = factory.updateCaseBlock(node, ts.visitNodes(node.clauses, nestedElementVisitor, ts.isCaseOrDefaultClause));
96393             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96394             return node;
96395         }
96396         /**
96397          * Visits the body of a CaseClause to hoist declarations.
96398          *
96399          * @param node The node to visit.
96400          */
96401         function visitCaseClause(node) {
96402             return factory.updateCaseClause(node, ts.visitNode(node.expression, destructuringAndImportCallVisitor, ts.isExpression), ts.visitNodes(node.statements, nestedElementVisitor, ts.isStatement));
96403         }
96404         /**
96405          * Visits the body of a DefaultClause to hoist declarations.
96406          *
96407          * @param node The node to visit.
96408          */
96409         function visitDefaultClause(node) {
96410             return ts.visitEachChild(node, nestedElementVisitor, context);
96411         }
96412         /**
96413          * Visits the body of a TryStatement to hoist declarations.
96414          *
96415          * @param node The node to visit.
96416          */
96417         function visitTryStatement(node) {
96418             return ts.visitEachChild(node, nestedElementVisitor, context);
96419         }
96420         /**
96421          * Visits the body of a CatchClause to hoist declarations.
96422          *
96423          * @param node The node to visit.
96424          */
96425         function visitCatchClause(node) {
96426             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96427             enclosingBlockScopedContainer = node;
96428             node = factory.updateCatchClause(node, node.variableDeclaration, ts.visitNode(node.block, nestedElementVisitor, ts.isBlock));
96429             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96430             return node;
96431         }
96432         /**
96433          * Visits the body of a Block to hoist declarations.
96434          *
96435          * @param node The node to visit.
96436          */
96437         function visitBlock(node) {
96438             var savedEnclosingBlockScopedContainer = enclosingBlockScopedContainer;
96439             enclosingBlockScopedContainer = node;
96440             node = ts.visitEachChild(node, nestedElementVisitor, context);
96441             enclosingBlockScopedContainer = savedEnclosingBlockScopedContainer;
96442             return node;
96443         }
96444         //
96445         // Destructuring Assignment Visitors
96446         //
96447         /**
96448          * Visit nodes to flatten destructuring assignments to exported symbols.
96449          *
96450          * @param node The node to visit.
96451          */
96452         function destructuringAndImportCallVisitor(node) {
96453             if (ts.isDestructuringAssignment(node)) {
96454                 return visitDestructuringAssignment(node);
96455             }
96456             else if (ts.isImportCall(node)) {
96457                 return visitImportCallExpression(node);
96458             }
96459             else if ((node.transformFlags & 1024 /* ContainsDestructuringAssignment */) || (node.transformFlags & 2097152 /* ContainsDynamicImport */)) {
96460                 return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
96461             }
96462             else {
96463                 return node;
96464             }
96465         }
96466         function visitImportCallExpression(node) {
96467             // import("./blah")
96468             // emit as
96469             // System.register([], function (_export, _context) {
96470             //     return {
96471             //         setters: [],
96472             //         execute: () => {
96473             //             _context.import('./blah');
96474             //         }
96475             //     };
96476             // });
96477             return factory.createCallExpression(factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("import")), 
96478             /*typeArguments*/ undefined, ts.some(node.arguments) ? [ts.visitNode(node.arguments[0], destructuringAndImportCallVisitor)] : []);
96479         }
96480         /**
96481          * Visits a DestructuringAssignment to flatten destructuring to exported symbols.
96482          *
96483          * @param node The node to visit.
96484          */
96485         function visitDestructuringAssignment(node) {
96486             if (hasExportedReferenceInDestructuringTarget(node.left)) {
96487                 return ts.flattenDestructuringAssignment(node, destructuringAndImportCallVisitor, context, 0 /* All */, 
96488                 /*needsValue*/ true);
96489             }
96490             return ts.visitEachChild(node, destructuringAndImportCallVisitor, context);
96491         }
96492         /**
96493          * Determines whether the target of a destructuring assigment refers to an exported symbol.
96494          *
96495          * @param node The destructuring target.
96496          */
96497         function hasExportedReferenceInDestructuringTarget(node) {
96498             if (ts.isAssignmentExpression(node, /*excludeCompoundAssignment*/ true)) {
96499                 return hasExportedReferenceInDestructuringTarget(node.left);
96500             }
96501             else if (ts.isSpreadElement(node)) {
96502                 return hasExportedReferenceInDestructuringTarget(node.expression);
96503             }
96504             else if (ts.isObjectLiteralExpression(node)) {
96505                 return ts.some(node.properties, hasExportedReferenceInDestructuringTarget);
96506             }
96507             else if (ts.isArrayLiteralExpression(node)) {
96508                 return ts.some(node.elements, hasExportedReferenceInDestructuringTarget);
96509             }
96510             else if (ts.isShorthandPropertyAssignment(node)) {
96511                 return hasExportedReferenceInDestructuringTarget(node.name);
96512             }
96513             else if (ts.isPropertyAssignment(node)) {
96514                 return hasExportedReferenceInDestructuringTarget(node.initializer);
96515             }
96516             else if (ts.isIdentifier(node)) {
96517                 var container = resolver.getReferencedExportContainer(node);
96518                 return container !== undefined && container.kind === 297 /* SourceFile */;
96519             }
96520             else {
96521                 return false;
96522             }
96523         }
96524         //
96525         // Modifier Visitors
96526         //
96527         /**
96528          * Visit nodes to elide module-specific modifiers.
96529          *
96530          * @param node The node to visit.
96531          */
96532         function modifierVisitor(node) {
96533             switch (node.kind) {
96534                 case 92 /* ExportKeyword */:
96535                 case 87 /* DefaultKeyword */:
96536                     return undefined;
96537             }
96538             return node;
96539         }
96540         //
96541         // Emit Notification
96542         //
96543         /**
96544          * Hook for node emit notifications.
96545          *
96546          * @param hint A hint as to the intended usage of the node.
96547          * @param node The node to emit.
96548          * @param emitCallback A callback used to emit the node in the printer.
96549          */
96550         function onEmitNode(hint, node, emitCallback) {
96551             if (node.kind === 297 /* SourceFile */) {
96552                 var id = ts.getOriginalNodeId(node);
96553                 currentSourceFile = node;
96554                 moduleInfo = moduleInfoMap[id];
96555                 exportFunction = exportFunctionsMap[id];
96556                 noSubstitution = noSubstitutionMap[id];
96557                 contextObject = contextObjectMap[id];
96558                 if (noSubstitution) {
96559                     delete noSubstitutionMap[id];
96560                 }
96561                 previousOnEmitNode(hint, node, emitCallback);
96562                 currentSourceFile = undefined;
96563                 moduleInfo = undefined;
96564                 exportFunction = undefined;
96565                 contextObject = undefined;
96566                 noSubstitution = undefined;
96567             }
96568             else {
96569                 previousOnEmitNode(hint, node, emitCallback);
96570             }
96571         }
96572         //
96573         // Substitutions
96574         //
96575         /**
96576          * Hooks node substitutions.
96577          *
96578          * @param hint A hint as to the intended usage of the node.
96579          * @param node The node to substitute.
96580          */
96581         function onSubstituteNode(hint, node) {
96582             node = previousOnSubstituteNode(hint, node);
96583             if (isSubstitutionPrevented(node)) {
96584                 return node;
96585             }
96586             if (hint === 1 /* Expression */) {
96587                 return substituteExpression(node);
96588             }
96589             else if (hint === 4 /* Unspecified */) {
96590                 return substituteUnspecified(node);
96591             }
96592             return node;
96593         }
96594         /**
96595          * Substitute the node, if necessary.
96596          *
96597          * @param node The node to substitute.
96598          */
96599         function substituteUnspecified(node) {
96600             switch (node.kind) {
96601                 case 289 /* ShorthandPropertyAssignment */:
96602                     return substituteShorthandPropertyAssignment(node);
96603             }
96604             return node;
96605         }
96606         /**
96607          * Substitution for a ShorthandPropertyAssignment whose name that may contain an imported or exported symbol.
96608          *
96609          * @param node The node to substitute.
96610          */
96611         function substituteShorthandPropertyAssignment(node) {
96612             var name = node.name;
96613             if (!ts.isGeneratedIdentifier(name) && !ts.isLocalName(name)) {
96614                 var importDeclaration = resolver.getReferencedImportDeclaration(name);
96615                 if (importDeclaration) {
96616                     if (ts.isImportClause(importDeclaration)) {
96617                         return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default"))), 
96618                         /*location*/ node);
96619                     }
96620                     else if (ts.isImportSpecifier(importDeclaration)) {
96621                         return ts.setTextRange(factory.createPropertyAssignment(factory.cloneNode(name), factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name))), 
96622                         /*location*/ node);
96623                     }
96624                 }
96625             }
96626             return node;
96627         }
96628         /**
96629          * Substitute the expression, if necessary.
96630          *
96631          * @param node The node to substitute.
96632          */
96633         function substituteExpression(node) {
96634             switch (node.kind) {
96635                 case 78 /* Identifier */:
96636                     return substituteExpressionIdentifier(node);
96637                 case 216 /* BinaryExpression */:
96638                     return substituteBinaryExpression(node);
96639                 case 214 /* PrefixUnaryExpression */:
96640                 case 215 /* PostfixUnaryExpression */:
96641                     return substituteUnaryExpression(node);
96642                 case 226 /* MetaProperty */:
96643                     return substituteMetaProperty(node);
96644             }
96645             return node;
96646         }
96647         /**
96648          * Substitution for an Identifier expression that may contain an imported or exported symbol.
96649          *
96650          * @param node The node to substitute.
96651          */
96652         function substituteExpressionIdentifier(node) {
96653             if (ts.getEmitFlags(node) & 4096 /* HelperName */) {
96654                 var externalHelpersModuleName = ts.getExternalHelpersModuleName(currentSourceFile);
96655                 if (externalHelpersModuleName) {
96656                     return factory.createPropertyAccessExpression(externalHelpersModuleName, node);
96657                 }
96658                 return node;
96659             }
96660             // When we see an identifier in an expression position that
96661             // points to an imported symbol, we should substitute a qualified
96662             // reference to the imported symbol if one is needed.
96663             //
96664             // - We do not substitute generated identifiers for any reason.
96665             // - We do not substitute identifiers tagged with the LocalName flag.
96666             if (!ts.isGeneratedIdentifier(node) && !ts.isLocalName(node)) {
96667                 var importDeclaration = resolver.getReferencedImportDeclaration(node);
96668                 if (importDeclaration) {
96669                     if (ts.isImportClause(importDeclaration)) {
96670                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent), factory.createIdentifier("default")), 
96671                         /*location*/ node);
96672                     }
96673                     else if (ts.isImportSpecifier(importDeclaration)) {
96674                         return ts.setTextRange(factory.createPropertyAccessExpression(factory.getGeneratedNameForNode(importDeclaration.parent.parent.parent), factory.cloneNode(importDeclaration.propertyName || importDeclaration.name)), 
96675                         /*location*/ node);
96676                     }
96677                 }
96678             }
96679             return node;
96680         }
96681         /**
96682          * Substitution for a BinaryExpression that may contain an imported or exported symbol.
96683          *
96684          * @param node The node to substitute.
96685          */
96686         function substituteBinaryExpression(node) {
96687             // When we see an assignment expression whose left-hand side is an exported symbol,
96688             // we should ensure all exports of that symbol are updated with the correct value.
96689             //
96690             // - We do not substitute generated identifiers for any reason.
96691             // - We do not substitute identifiers tagged with the LocalName flag.
96692             // - We do not substitute identifiers that were originally the name of an enum or
96693             //   namespace due to how they are transformed in TypeScript.
96694             // - We only substitute identifiers that are exported at the top level.
96695             if (ts.isAssignmentOperator(node.operatorToken.kind)
96696                 && ts.isIdentifier(node.left)
96697                 && !ts.isGeneratedIdentifier(node.left)
96698                 && !ts.isLocalName(node.left)
96699                 && !ts.isDeclarationNameOfEnumOrNamespace(node.left)) {
96700                 var exportedNames = getExports(node.left);
96701                 if (exportedNames) {
96702                     // For each additional export of the declaration, apply an export assignment.
96703                     var expression = node;
96704                     for (var _i = 0, exportedNames_4 = exportedNames; _i < exportedNames_4.length; _i++) {
96705                         var exportName = exportedNames_4[_i];
96706                         expression = createExportExpression(exportName, preventSubstitution(expression));
96707                     }
96708                     return expression;
96709                 }
96710             }
96711             return node;
96712         }
96713         /**
96714          * Substitution for a UnaryExpression that may contain an imported or exported symbol.
96715          *
96716          * @param node The node to substitute.
96717          */
96718         function substituteUnaryExpression(node) {
96719             // When we see a prefix or postfix increment expression whose operand is an exported
96720             // symbol, we should ensure all exports of that symbol are updated with the correct
96721             // value.
96722             //
96723             // - We do not substitute generated identifiers for any reason.
96724             // - We do not substitute identifiers tagged with the LocalName flag.
96725             // - We do not substitute identifiers that were originally the name of an enum or
96726             //   namespace due to how they are transformed in TypeScript.
96727             // - We only substitute identifiers that are exported at the top level.
96728             if ((node.operator === 45 /* PlusPlusToken */ || node.operator === 46 /* MinusMinusToken */)
96729                 && ts.isIdentifier(node.operand)
96730                 && !ts.isGeneratedIdentifier(node.operand)
96731                 && !ts.isLocalName(node.operand)
96732                 && !ts.isDeclarationNameOfEnumOrNamespace(node.operand)) {
96733                 var exportedNames = getExports(node.operand);
96734                 if (exportedNames) {
96735                     var expression = node.kind === 215 /* PostfixUnaryExpression */
96736                         ? ts.setTextRange(factory.createPrefixUnaryExpression(node.operator, node.operand), node)
96737                         : node;
96738                     for (var _i = 0, exportedNames_5 = exportedNames; _i < exportedNames_5.length; _i++) {
96739                         var exportName = exportedNames_5[_i];
96740                         expression = createExportExpression(exportName, preventSubstitution(expression));
96741                     }
96742                     if (node.kind === 215 /* PostfixUnaryExpression */) {
96743                         expression = node.operator === 45 /* PlusPlusToken */
96744                             ? factory.createSubtract(preventSubstitution(expression), factory.createNumericLiteral(1))
96745                             : factory.createAdd(preventSubstitution(expression), factory.createNumericLiteral(1));
96746                     }
96747                     return expression;
96748                 }
96749             }
96750             return node;
96751         }
96752         function substituteMetaProperty(node) {
96753             if (ts.isImportMeta(node)) {
96754                 return factory.createPropertyAccessExpression(contextObject, factory.createIdentifier("meta"));
96755             }
96756             return node;
96757         }
96758         /**
96759          * Gets the exports of a name.
96760          *
96761          * @param name The name.
96762          */
96763         function getExports(name) {
96764             var exportedNames;
96765             if (!ts.isGeneratedIdentifier(name)) {
96766                 var valueDeclaration = resolver.getReferencedImportDeclaration(name)
96767                     || resolver.getReferencedValueDeclaration(name);
96768                 if (valueDeclaration) {
96769                     var exportContainer = resolver.getReferencedExportContainer(name, /*prefixLocals*/ false);
96770                     if (exportContainer && exportContainer.kind === 297 /* SourceFile */) {
96771                         exportedNames = ts.append(exportedNames, factory.getDeclarationName(valueDeclaration));
96772                     }
96773                     exportedNames = ts.addRange(exportedNames, moduleInfo && moduleInfo.exportedBindings[ts.getOriginalNodeId(valueDeclaration)]);
96774                 }
96775             }
96776             return exportedNames;
96777         }
96778         /**
96779          * Prevent substitution of a node for this transformer.
96780          *
96781          * @param node The node which should not be substituted.
96782          */
96783         function preventSubstitution(node) {
96784             if (noSubstitution === undefined)
96785                 noSubstitution = [];
96786             noSubstitution[ts.getNodeId(node)] = true;
96787             return node;
96788         }
96789         /**
96790          * Determines whether a node should not be substituted.
96791          *
96792          * @param node The node to test.
96793          */
96794         function isSubstitutionPrevented(node) {
96795             return noSubstitution && node.id && noSubstitution[node.id];
96796         }
96797     }
96798     ts.transformSystemModule = transformSystemModule;
96799 })(ts || (ts = {}));
96800 /*@internal*/
96801 var ts;
96802 (function (ts) {
96803     function transformECMAScriptModule(context) {
96804         var factory = context.factory, emitHelpers = context.getEmitHelperFactory;
96805         var compilerOptions = context.getCompilerOptions();
96806         var previousOnEmitNode = context.onEmitNode;
96807         var previousOnSubstituteNode = context.onSubstituteNode;
96808         context.onEmitNode = onEmitNode;
96809         context.onSubstituteNode = onSubstituteNode;
96810         context.enableEmitNotification(297 /* SourceFile */);
96811         context.enableSubstitution(78 /* Identifier */);
96812         var helperNameSubstitutions;
96813         return ts.chainBundle(context, transformSourceFile);
96814         function transformSourceFile(node) {
96815             if (node.isDeclarationFile) {
96816                 return node;
96817             }
96818             if (ts.isExternalModule(node) || compilerOptions.isolatedModules) {
96819                 var result = updateExternalModule(node);
96820                 if (!ts.isExternalModule(node) || ts.some(result.statements, ts.isExternalModuleIndicator)) {
96821                     return result;
96822                 }
96823                 return factory.updateSourceFile(result, ts.setTextRange(factory.createNodeArray(__spreadArrays(result.statements, [ts.createEmptyExports(factory)])), result.statements));
96824             }
96825             return node;
96826         }
96827         function updateExternalModule(node) {
96828             var externalHelpersImportDeclaration = ts.createExternalHelpersImportDeclarationIfNeeded(factory, emitHelpers(), node, compilerOptions);
96829             if (externalHelpersImportDeclaration) {
96830                 var statements = [];
96831                 var statementOffset = factory.copyPrologue(node.statements, statements);
96832                 ts.append(statements, externalHelpersImportDeclaration);
96833                 ts.addRange(statements, ts.visitNodes(node.statements, visitor, ts.isStatement, statementOffset));
96834                 return factory.updateSourceFile(node, ts.setTextRange(factory.createNodeArray(statements), node.statements));
96835             }
96836             else {
96837                 return ts.visitEachChild(node, visitor, context);
96838             }
96839         }
96840         function visitor(node) {
96841             switch (node.kind) {
96842                 case 260 /* ImportEqualsDeclaration */:
96843                     // Elide `import=` as it is not legal with --module ES6
96844                     return undefined;
96845                 case 266 /* ExportAssignment */:
96846                     return visitExportAssignment(node);
96847                 case 267 /* ExportDeclaration */:
96848                     var exportDecl = node;
96849                     return visitExportDeclaration(exportDecl);
96850             }
96851             return node;
96852         }
96853         function visitExportAssignment(node) {
96854             // Elide `export=` as it is not legal with --module ES6
96855             return node.isExportEquals ? undefined : node;
96856         }
96857         function visitExportDeclaration(node) {
96858             // `export * as ns` only needs to be transformed in ES2015
96859             if (compilerOptions.module !== undefined && compilerOptions.module > ts.ModuleKind.ES2015) {
96860                 return node;
96861             }
96862             // Either ill-formed or don't need to be tranformed.
96863             if (!node.exportClause || !ts.isNamespaceExport(node.exportClause) || !node.moduleSpecifier) {
96864                 return node;
96865             }
96866             var oldIdentifier = node.exportClause.name;
96867             var synthName = factory.getGeneratedNameForNode(oldIdentifier);
96868             var importDecl = factory.createImportDeclaration(
96869             /*decorators*/ undefined, 
96870             /*modifiers*/ undefined, factory.createImportClause(
96871             /*isTypeOnly*/ false, 
96872             /*name*/ undefined, factory.createNamespaceImport(synthName)), node.moduleSpecifier);
96873             ts.setOriginalNode(importDecl, node.exportClause);
96874             var exportDecl = ts.isExportNamespaceAsDefaultDeclaration(node) ? factory.createExportDefault(synthName) : factory.createExportDeclaration(
96875             /*decorators*/ undefined, 
96876             /*modifiers*/ undefined, 
96877             /*isTypeOnly*/ false, factory.createNamedExports([factory.createExportSpecifier(synthName, oldIdentifier)]));
96878             ts.setOriginalNode(exportDecl, node);
96879             return [importDecl, exportDecl];
96880         }
96881         //
96882         // Emit Notification
96883         //
96884         /**
96885          * Hook for node emit.
96886          *
96887          * @param hint A hint as to the intended usage of the node.
96888          * @param node The node to emit.
96889          * @param emit A callback used to emit the node in the printer.
96890          */
96891         function onEmitNode(hint, node, emitCallback) {
96892             if (ts.isSourceFile(node)) {
96893                 if ((ts.isExternalModule(node) || compilerOptions.isolatedModules) && compilerOptions.importHelpers) {
96894                     helperNameSubstitutions = new ts.Map();
96895                 }
96896                 previousOnEmitNode(hint, node, emitCallback);
96897                 helperNameSubstitutions = undefined;
96898             }
96899             else {
96900                 previousOnEmitNode(hint, node, emitCallback);
96901             }
96902         }
96903         //
96904         // Substitutions
96905         //
96906         /**
96907          * Hooks node substitutions.
96908          *
96909          * @param hint A hint as to the intended usage of the node.
96910          * @param node The node to substitute.
96911          */
96912         function onSubstituteNode(hint, node) {
96913             node = previousOnSubstituteNode(hint, node);
96914             if (helperNameSubstitutions && ts.isIdentifier(node) && ts.getEmitFlags(node) & 4096 /* HelperName */) {
96915                 return substituteHelperName(node);
96916             }
96917             return node;
96918         }
96919         function substituteHelperName(node) {
96920             var name = ts.idText(node);
96921             var substitution = helperNameSubstitutions.get(name);
96922             if (!substitution) {
96923                 helperNameSubstitutions.set(name, substitution = factory.createUniqueName(name, 16 /* Optimistic */ | 32 /* FileLevel */));
96924             }
96925             return substitution;
96926         }
96927     }
96928     ts.transformECMAScriptModule = transformECMAScriptModule;
96929 })(ts || (ts = {}));
96930 /* @internal */
96931 var ts;
96932 (function (ts) {
96933     function canProduceDiagnostics(node) {
96934         return ts.isVariableDeclaration(node) ||
96935             ts.isPropertyDeclaration(node) ||
96936             ts.isPropertySignature(node) ||
96937             ts.isBindingElement(node) ||
96938             ts.isSetAccessor(node) ||
96939             ts.isGetAccessor(node) ||
96940             ts.isConstructSignatureDeclaration(node) ||
96941             ts.isCallSignatureDeclaration(node) ||
96942             ts.isMethodDeclaration(node) ||
96943             ts.isMethodSignature(node) ||
96944             ts.isFunctionDeclaration(node) ||
96945             ts.isParameter(node) ||
96946             ts.isTypeParameterDeclaration(node) ||
96947             ts.isExpressionWithTypeArguments(node) ||
96948             ts.isImportEqualsDeclaration(node) ||
96949             ts.isTypeAliasDeclaration(node) ||
96950             ts.isConstructorDeclaration(node) ||
96951             ts.isIndexSignatureDeclaration(node) ||
96952             ts.isPropertyAccessExpression(node);
96953     }
96954     ts.canProduceDiagnostics = canProduceDiagnostics;
96955     function createGetSymbolAccessibilityDiagnosticForNodeName(node) {
96956         if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
96957             return getAccessorNameVisibilityError;
96958         }
96959         else if (ts.isMethodSignature(node) || ts.isMethodDeclaration(node)) {
96960             return getMethodNameVisibilityError;
96961         }
96962         else {
96963             return createGetSymbolAccessibilityDiagnosticForNode(node);
96964         }
96965         function getAccessorNameVisibilityError(symbolAccessibilityResult) {
96966             var diagnosticMessage = getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
96967             return diagnosticMessage !== undefined ? {
96968                 diagnosticMessage: diagnosticMessage,
96969                 errorNode: node,
96970                 typeName: node.name
96971             } : undefined;
96972         }
96973         function getAccessorNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
96974             if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
96975                 return symbolAccessibilityResult.errorModuleName ?
96976                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
96977                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
96978                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
96979                     ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
96980             }
96981             else if (node.parent.kind === 252 /* ClassDeclaration */) {
96982                 return symbolAccessibilityResult.errorModuleName ?
96983                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
96984                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
96985                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
96986                     ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
96987             }
96988             else {
96989                 return symbolAccessibilityResult.errorModuleName ?
96990                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
96991                     ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
96992             }
96993         }
96994         function getMethodNameVisibilityError(symbolAccessibilityResult) {
96995             var diagnosticMessage = getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult);
96996             return diagnosticMessage !== undefined ? {
96997                 diagnosticMessage: diagnosticMessage,
96998                 errorNode: node,
96999                 typeName: node.name
97000             } : undefined;
97001         }
97002         function getMethodNameVisibilityDiagnosticMessage(symbolAccessibilityResult) {
97003             if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97004                 return symbolAccessibilityResult.errorModuleName ?
97005                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97006                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97007                         ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
97008                     ts.Diagnostics.Public_static_method_0_of_exported_class_has_or_is_using_private_name_1;
97009             }
97010             else if (node.parent.kind === 252 /* ClassDeclaration */) {
97011                 return symbolAccessibilityResult.errorModuleName ?
97012                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97013                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97014                         ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
97015                     ts.Diagnostics.Public_method_0_of_exported_class_has_or_is_using_private_name_1;
97016             }
97017             else {
97018                 return symbolAccessibilityResult.errorModuleName ?
97019                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97020                     ts.Diagnostics.Method_0_of_exported_interface_has_or_is_using_private_name_1;
97021             }
97022         }
97023     }
97024     ts.createGetSymbolAccessibilityDiagnosticForNodeName = createGetSymbolAccessibilityDiagnosticForNodeName;
97025     function createGetSymbolAccessibilityDiagnosticForNode(node) {
97026         if (ts.isVariableDeclaration(node) || ts.isPropertyDeclaration(node) || ts.isPropertySignature(node) || ts.isPropertyAccessExpression(node) || ts.isBindingElement(node) || ts.isConstructorDeclaration(node)) {
97027             return getVariableDeclarationTypeVisibilityError;
97028         }
97029         else if (ts.isSetAccessor(node) || ts.isGetAccessor(node)) {
97030             return getAccessorDeclarationTypeVisibilityError;
97031         }
97032         else if (ts.isConstructSignatureDeclaration(node) || ts.isCallSignatureDeclaration(node) || ts.isMethodDeclaration(node) || ts.isMethodSignature(node) || ts.isFunctionDeclaration(node) || ts.isIndexSignatureDeclaration(node)) {
97033             return getReturnTypeVisibilityError;
97034         }
97035         else if (ts.isParameter(node)) {
97036             if (ts.isParameterPropertyDeclaration(node, node.parent) && ts.hasSyntacticModifier(node.parent, 8 /* Private */)) {
97037                 return getVariableDeclarationTypeVisibilityError;
97038             }
97039             return getParameterDeclarationTypeVisibilityError;
97040         }
97041         else if (ts.isTypeParameterDeclaration(node)) {
97042             return getTypeParameterConstraintVisibilityError;
97043         }
97044         else if (ts.isExpressionWithTypeArguments(node)) {
97045             return getHeritageClauseVisibilityError;
97046         }
97047         else if (ts.isImportEqualsDeclaration(node)) {
97048             return getImportEntityNameVisibilityError;
97049         }
97050         else if (ts.isTypeAliasDeclaration(node)) {
97051             return getTypeAliasDeclarationVisibilityError;
97052         }
97053         else {
97054             return ts.Debug.assertNever(node, "Attempted to set a declaration diagnostic context for unhandled node kind: " + ts.SyntaxKind[node.kind]);
97055         }
97056         function getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
97057             if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) {
97058                 return symbolAccessibilityResult.errorModuleName ?
97059                     symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97060                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97061                         ts.Diagnostics.Exported_variable_0_has_or_is_using_name_1_from_private_module_2 :
97062                     ts.Diagnostics.Exported_variable_0_has_or_is_using_private_name_1;
97063             }
97064             // This check is to ensure we don't report error on constructor parameter property as that error would be reported during parameter emit
97065             // The only exception here is if the constructor was marked as private. we are not emitting the constructor parameters at all.
97066             else if (node.kind === 163 /* PropertyDeclaration */ || node.kind === 201 /* PropertyAccessExpression */ || node.kind === 162 /* PropertySignature */ ||
97067                 (node.kind === 160 /* Parameter */ && ts.hasSyntacticModifier(node.parent, 8 /* Private */))) {
97068                 // TODO(jfreeman): Deal with computed properties in error reporting.
97069                 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97070                     return symbolAccessibilityResult.errorModuleName ?
97071                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97072                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97073                             ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
97074                         ts.Diagnostics.Public_static_property_0_of_exported_class_has_or_is_using_private_name_1;
97075                 }
97076                 else if (node.parent.kind === 252 /* ClassDeclaration */ || node.kind === 160 /* Parameter */) {
97077                     return symbolAccessibilityResult.errorModuleName ?
97078                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97079                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97080                             ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_name_1_from_private_module_2 :
97081                         ts.Diagnostics.Public_property_0_of_exported_class_has_or_is_using_private_name_1;
97082                 }
97083                 else {
97084                     // Interfaces cannot have types that cannot be named
97085                     return symbolAccessibilityResult.errorModuleName ?
97086                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97087                         ts.Diagnostics.Property_0_of_exported_interface_has_or_is_using_private_name_1;
97088                 }
97089             }
97090         }
97091         function getVariableDeclarationTypeVisibilityError(symbolAccessibilityResult) {
97092             var diagnosticMessage = getVariableDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
97093             return diagnosticMessage !== undefined ? {
97094                 diagnosticMessage: diagnosticMessage,
97095                 errorNode: node,
97096                 typeName: node.name
97097             } : undefined;
97098         }
97099         function getAccessorDeclarationTypeVisibilityError(symbolAccessibilityResult) {
97100             var diagnosticMessage;
97101             if (node.kind === 168 /* SetAccessor */) {
97102                 // Getters can infer the return type from the returned expression, but setters cannot, so the
97103                 // "_from_external_module_1_but_cannot_be_named" case cannot occur.
97104                 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97105                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97106                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97107                         ts.Diagnostics.Parameter_type_of_public_static_setter_0_from_exported_class_has_or_is_using_private_name_1;
97108                 }
97109                 else {
97110                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97111                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97112                         ts.Diagnostics.Parameter_type_of_public_setter_0_from_exported_class_has_or_is_using_private_name_1;
97113                 }
97114             }
97115             else {
97116                 if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97117                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97118                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97119                             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 :
97120                             ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97121                         ts.Diagnostics.Return_type_of_public_static_getter_0_from_exported_class_has_or_is_using_private_name_1;
97122                 }
97123                 else {
97124                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97125                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97126                             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 :
97127                             ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97128                         ts.Diagnostics.Return_type_of_public_getter_0_from_exported_class_has_or_is_using_private_name_1;
97129                 }
97130             }
97131             return {
97132                 diagnosticMessage: diagnosticMessage,
97133                 errorNode: node.name,
97134                 typeName: node.name
97135             };
97136         }
97137         function getReturnTypeVisibilityError(symbolAccessibilityResult) {
97138             var diagnosticMessage;
97139             switch (node.kind) {
97140                 case 170 /* ConstructSignature */:
97141                     // Interfaces cannot have return types that cannot be named
97142                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97143                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
97144                         ts.Diagnostics.Return_type_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_0;
97145                     break;
97146                 case 169 /* CallSignature */:
97147                     // Interfaces cannot have return types that cannot be named
97148                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97149                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
97150                         ts.Diagnostics.Return_type_of_call_signature_from_exported_interface_has_or_is_using_private_name_0;
97151                     break;
97152                 case 171 /* IndexSignature */:
97153                     // Interfaces cannot have return types that cannot be named
97154                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97155                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
97156                         ts.Diagnostics.Return_type_of_index_signature_from_exported_interface_has_or_is_using_private_name_0;
97157                     break;
97158                 case 165 /* MethodDeclaration */:
97159                 case 164 /* MethodSignature */:
97160                     if (ts.hasSyntacticModifier(node, 32 /* Static */)) {
97161                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97162                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97163                                 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 :
97164                                 ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
97165                             ts.Diagnostics.Return_type_of_public_static_method_from_exported_class_has_or_is_using_private_name_0;
97166                     }
97167                     else if (node.parent.kind === 252 /* ClassDeclaration */) {
97168                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97169                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97170                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
97171                                 ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_name_0_from_private_module_1 :
97172                             ts.Diagnostics.Return_type_of_public_method_from_exported_class_has_or_is_using_private_name_0;
97173                     }
97174                     else {
97175                         // Interfaces cannot have return types that cannot be named
97176                         diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97177                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_name_0_from_private_module_1 :
97178                             ts.Diagnostics.Return_type_of_method_from_exported_interface_has_or_is_using_private_name_0;
97179                     }
97180                     break;
97181                 case 251 /* FunctionDeclaration */:
97182                     diagnosticMessage = symbolAccessibilityResult.errorModuleName ?
97183                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97184                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_external_module_1_but_cannot_be_named :
97185                             ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_name_0_from_private_module_1 :
97186                         ts.Diagnostics.Return_type_of_exported_function_has_or_is_using_private_name_0;
97187                     break;
97188                 default:
97189                     return ts.Debug.fail("This is unknown kind for signature: " + node.kind);
97190             }
97191             return {
97192                 diagnosticMessage: diagnosticMessage,
97193                 errorNode: node.name || node
97194             };
97195         }
97196         function getParameterDeclarationTypeVisibilityError(symbolAccessibilityResult) {
97197             var diagnosticMessage = getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult);
97198             return diagnosticMessage !== undefined ? {
97199                 diagnosticMessage: diagnosticMessage,
97200                 errorNode: node,
97201                 typeName: node.name
97202             } : undefined;
97203         }
97204         function getParameterDeclarationTypeVisibilityDiagnosticMessage(symbolAccessibilityResult) {
97205             switch (node.parent.kind) {
97206                 case 166 /* Constructor */:
97207                     return symbolAccessibilityResult.errorModuleName ?
97208                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97209                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97210                             ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97211                         ts.Diagnostics.Parameter_0_of_constructor_from_exported_class_has_or_is_using_private_name_1;
97212                 case 170 /* ConstructSignature */:
97213                 case 175 /* ConstructorType */:
97214                     // Interfaces cannot have parameter types that cannot be named
97215                     return symbolAccessibilityResult.errorModuleName ?
97216                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97217                         ts.Diagnostics.Parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
97218                 case 169 /* CallSignature */:
97219                     // Interfaces cannot have parameter types that cannot be named
97220                     return symbolAccessibilityResult.errorModuleName ?
97221                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97222                         ts.Diagnostics.Parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
97223                 case 171 /* IndexSignature */:
97224                     // Interfaces cannot have parameter types that cannot be named
97225                     return symbolAccessibilityResult.errorModuleName ?
97226                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97227                         ts.Diagnostics.Parameter_0_of_index_signature_from_exported_interface_has_or_is_using_private_name_1;
97228                 case 165 /* MethodDeclaration */:
97229                 case 164 /* MethodSignature */:
97230                     if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) {
97231                         return symbolAccessibilityResult.errorModuleName ?
97232                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97233                                 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 :
97234                                 ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97235                             ts.Diagnostics.Parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
97236                     }
97237                     else if (node.parent.parent.kind === 252 /* ClassDeclaration */) {
97238                         return symbolAccessibilityResult.errorModuleName ?
97239                             symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97240                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97241                                 ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_name_1_from_private_module_2 :
97242                             ts.Diagnostics.Parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
97243                     }
97244                     else {
97245                         // Interfaces cannot have parameter types that cannot be named
97246                         return symbolAccessibilityResult.errorModuleName ?
97247                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_name_1_from_private_module_2 :
97248                             ts.Diagnostics.Parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
97249                     }
97250                 case 251 /* FunctionDeclaration */:
97251                 case 174 /* FunctionType */:
97252                     return symbolAccessibilityResult.errorModuleName ?
97253                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97254                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97255                             ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_name_1_from_private_module_2 :
97256                         ts.Diagnostics.Parameter_0_of_exported_function_has_or_is_using_private_name_1;
97257                 case 168 /* SetAccessor */:
97258                 case 167 /* GetAccessor */:
97259                     return symbolAccessibilityResult.errorModuleName ?
97260                         symbolAccessibilityResult.accessibility === 2 /* CannotBeNamed */ ?
97261                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_external_module_2_but_cannot_be_named :
97262                             ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_name_1_from_private_module_2 :
97263                         ts.Diagnostics.Parameter_0_of_accessor_has_or_is_using_private_name_1;
97264                 default:
97265                     return ts.Debug.fail("Unknown parent for parameter: " + ts.SyntaxKind[node.parent.kind]);
97266             }
97267         }
97268         function getTypeParameterConstraintVisibilityError() {
97269             // Type parameter constraints are named by user so we should always be able to name it
97270             var diagnosticMessage;
97271             switch (node.parent.kind) {
97272                 case 252 /* ClassDeclaration */:
97273                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_class_has_or_is_using_private_name_1;
97274                     break;
97275                 case 253 /* InterfaceDeclaration */:
97276                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_interface_has_or_is_using_private_name_1;
97277                     break;
97278                 case 190 /* MappedType */:
97279                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_mapped_object_type_is_using_private_name_1;
97280                     break;
97281                 case 175 /* ConstructorType */:
97282                 case 170 /* ConstructSignature */:
97283                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_constructor_signature_from_exported_interface_has_or_is_using_private_name_1;
97284                     break;
97285                 case 169 /* CallSignature */:
97286                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_call_signature_from_exported_interface_has_or_is_using_private_name_1;
97287                     break;
97288                 case 165 /* MethodDeclaration */:
97289                 case 164 /* MethodSignature */:
97290                     if (ts.hasSyntacticModifier(node.parent, 32 /* Static */)) {
97291                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_static_method_from_exported_class_has_or_is_using_private_name_1;
97292                     }
97293                     else if (node.parent.parent.kind === 252 /* ClassDeclaration */) {
97294                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_public_method_from_exported_class_has_or_is_using_private_name_1;
97295                     }
97296                     else {
97297                         diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_method_from_exported_interface_has_or_is_using_private_name_1;
97298                     }
97299                     break;
97300                 case 174 /* FunctionType */:
97301                 case 251 /* FunctionDeclaration */:
97302                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_function_has_or_is_using_private_name_1;
97303                     break;
97304                 case 254 /* TypeAliasDeclaration */:
97305                     diagnosticMessage = ts.Diagnostics.Type_parameter_0_of_exported_type_alias_has_or_is_using_private_name_1;
97306                     break;
97307                 default:
97308                     return ts.Debug.fail("This is unknown parent for type parameter: " + node.parent.kind);
97309             }
97310             return {
97311                 diagnosticMessage: diagnosticMessage,
97312                 errorNode: node,
97313                 typeName: node.name
97314             };
97315         }
97316         function getHeritageClauseVisibilityError() {
97317             var diagnosticMessage;
97318             // Heritage clause is written by user so it can always be named
97319             if (ts.isClassDeclaration(node.parent.parent)) {
97320                 // Class or Interface implemented/extended is inaccessible
97321                 diagnosticMessage = ts.isHeritageClause(node.parent) && node.parent.token === 116 /* ImplementsKeyword */ ?
97322                     ts.Diagnostics.Implements_clause_of_exported_class_0_has_or_is_using_private_name_1 :
97323                     node.parent.parent.name ? ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1 :
97324                         ts.Diagnostics.extends_clause_of_exported_class_has_or_is_using_private_name_0;
97325             }
97326             else {
97327                 // interface is inaccessible
97328                 diagnosticMessage = ts.Diagnostics.extends_clause_of_exported_interface_0_has_or_is_using_private_name_1;
97329             }
97330             return {
97331                 diagnosticMessage: diagnosticMessage,
97332                 errorNode: node,
97333                 typeName: ts.getNameOfDeclaration(node.parent.parent)
97334             };
97335         }
97336         function getImportEntityNameVisibilityError() {
97337             return {
97338                 diagnosticMessage: ts.Diagnostics.Import_declaration_0_is_using_private_name_1,
97339                 errorNode: node,
97340                 typeName: node.name
97341             };
97342         }
97343         function getTypeAliasDeclarationVisibilityError() {
97344             return {
97345                 diagnosticMessage: ts.Diagnostics.Exported_type_alias_0_has_or_is_using_private_name_1,
97346                 errorNode: node.type,
97347                 typeName: node.name
97348             };
97349         }
97350     }
97351     ts.createGetSymbolAccessibilityDiagnosticForNode = createGetSymbolAccessibilityDiagnosticForNode;
97352 })(ts || (ts = {}));
97353 /*@internal*/
97354 var ts;
97355 (function (ts) {
97356     function getDeclarationDiagnostics(host, resolver, file) {
97357         var compilerOptions = host.getCompilerOptions();
97358         var result = ts.transformNodes(resolver, host, ts.factory, compilerOptions, file ? [file] : ts.filter(host.getSourceFiles(), ts.isSourceFileNotJson), [transformDeclarations], /*allowDtsFiles*/ false);
97359         return result.diagnostics;
97360     }
97361     ts.getDeclarationDiagnostics = getDeclarationDiagnostics;
97362     function hasInternalAnnotation(range, currentSourceFile) {
97363         var comment = currentSourceFile.text.substring(range.pos, range.end);
97364         return ts.stringContains(comment, "@internal");
97365     }
97366     function isInternalDeclaration(node, currentSourceFile) {
97367         var parseTreeNode = ts.getParseTreeNode(node);
97368         if (parseTreeNode && parseTreeNode.kind === 160 /* Parameter */) {
97369             var paramIdx = parseTreeNode.parent.parameters.indexOf(parseTreeNode);
97370             var previousSibling = paramIdx > 0 ? parseTreeNode.parent.parameters[paramIdx - 1] : undefined;
97371             var text = currentSourceFile.text;
97372             var commentRanges = previousSibling
97373                 ? ts.concatenate(
97374                 // to handle
97375                 // ... parameters, /* @internal */
97376                 // public param: string
97377                 ts.getTrailingCommentRanges(text, ts.skipTrivia(text, previousSibling.end + 1, /* stopAfterLineBreak */ false, /* stopAtComments */ true)), ts.getLeadingCommentRanges(text, node.pos))
97378                 : ts.getTrailingCommentRanges(text, ts.skipTrivia(text, node.pos, /* stopAfterLineBreak */ false, /* stopAtComments */ true));
97379             return commentRanges && commentRanges.length && hasInternalAnnotation(ts.last(commentRanges), currentSourceFile);
97380         }
97381         var leadingCommentRanges = parseTreeNode && ts.getLeadingCommentRangesOfNode(parseTreeNode, currentSourceFile);
97382         return !!ts.forEach(leadingCommentRanges, function (range) {
97383             return hasInternalAnnotation(range, currentSourceFile);
97384         });
97385     }
97386     ts.isInternalDeclaration = isInternalDeclaration;
97387     var declarationEmitNodeBuilderFlags = 1024 /* MultilineObjectLiterals */ |
97388         2048 /* WriteClassExpressionAsTypeLiteral */ |
97389         4096 /* UseTypeOfFunction */ |
97390         8 /* UseStructuralFallback */ |
97391         524288 /* AllowEmptyTuple */ |
97392         4 /* GenerateNamesForShadowedTypeParams */ |
97393         1 /* NoTruncation */;
97394     /**
97395      * Transforms a ts file into a .d.ts file
97396      * This process requires type information, which is retrieved through the emit resolver. Because of this,
97397      * in many places this transformer assumes it will be operating on parse tree nodes directly.
97398      * This means that _no transforms should be allowed to occur before this one_.
97399      */
97400     function transformDeclarations(context) {
97401         var throwDiagnostic = function () { return ts.Debug.fail("Diagnostic emitted without context"); };
97402         var getSymbolAccessibilityDiagnostic = throwDiagnostic;
97403         var needsDeclare = true;
97404         var isBundledEmit = false;
97405         var resultHasExternalModuleIndicator = false;
97406         var needsScopeFixMarker = false;
97407         var resultHasScopeMarker = false;
97408         var enclosingDeclaration;
97409         var necessaryTypeReferences;
97410         var lateMarkedStatements;
97411         var lateStatementReplacementMap;
97412         var suppressNewDiagnosticContexts;
97413         var exportedModulesFromDeclarationEmit;
97414         var factory = context.factory;
97415         var host = context.getEmitHost();
97416         var symbolTracker = {
97417             trackSymbol: trackSymbol,
97418             reportInaccessibleThisError: reportInaccessibleThisError,
97419             reportInaccessibleUniqueSymbolError: reportInaccessibleUniqueSymbolError,
97420             reportCyclicStructureError: reportCyclicStructureError,
97421             reportPrivateInBaseOfClassExpression: reportPrivateInBaseOfClassExpression,
97422             reportLikelyUnsafeImportRequiredError: reportLikelyUnsafeImportRequiredError,
97423             reportTruncationError: reportTruncationError,
97424             moduleResolverHost: host,
97425             trackReferencedAmbientModule: trackReferencedAmbientModule,
97426             trackExternalModuleSymbolOfImportTypeNode: trackExternalModuleSymbolOfImportTypeNode,
97427             reportNonlocalAugmentation: reportNonlocalAugmentation
97428         };
97429         var errorNameNode;
97430         var currentSourceFile;
97431         var refs;
97432         var libs;
97433         var emittedImports; // must be declared in container so it can be `undefined` while transformer's first pass
97434         var resolver = context.getEmitResolver();
97435         var options = context.getCompilerOptions();
97436         var noResolve = options.noResolve, stripInternal = options.stripInternal;
97437         return transformRoot;
97438         function recordTypeReferenceDirectivesIfNecessary(typeReferenceDirectives) {
97439             if (!typeReferenceDirectives) {
97440                 return;
97441             }
97442             necessaryTypeReferences = necessaryTypeReferences || new ts.Set();
97443             for (var _i = 0, typeReferenceDirectives_2 = typeReferenceDirectives; _i < typeReferenceDirectives_2.length; _i++) {
97444                 var ref = typeReferenceDirectives_2[_i];
97445                 necessaryTypeReferences.add(ref);
97446             }
97447         }
97448         function trackReferencedAmbientModule(node, symbol) {
97449             // If it is visible via `// <reference types="..."/>`, then we should just use that
97450             var directives = resolver.getTypeReferenceDirectivesForSymbol(symbol, 67108863 /* All */);
97451             if (ts.length(directives)) {
97452                 return recordTypeReferenceDirectivesIfNecessary(directives);
97453             }
97454             // Otherwise we should emit a path-based reference
97455             var container = ts.getSourceFileOfNode(node);
97456             refs.set(ts.getOriginalNodeId(container), container);
97457         }
97458         function handleSymbolAccessibilityError(symbolAccessibilityResult) {
97459             if (symbolAccessibilityResult.accessibility === 0 /* Accessible */) {
97460                 // Add aliases back onto the possible imports list if they're not there so we can try them again with updated visibility info
97461                 if (symbolAccessibilityResult && symbolAccessibilityResult.aliasesToMakeVisible) {
97462                     if (!lateMarkedStatements) {
97463                         lateMarkedStatements = symbolAccessibilityResult.aliasesToMakeVisible;
97464                     }
97465                     else {
97466                         for (var _i = 0, _a = symbolAccessibilityResult.aliasesToMakeVisible; _i < _a.length; _i++) {
97467                             var ref = _a[_i];
97468                             ts.pushIfUnique(lateMarkedStatements, ref);
97469                         }
97470                     }
97471                 }
97472                 // TODO: Do all these accessibility checks inside/after the first pass in the checker when declarations are enabled, if possible
97473             }
97474             else {
97475                 // Report error
97476                 var errorInfo = getSymbolAccessibilityDiagnostic(symbolAccessibilityResult);
97477                 if (errorInfo) {
97478                     if (errorInfo.typeName) {
97479                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, ts.getTextOfNode(errorInfo.typeName), symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
97480                     }
97481                     else {
97482                         context.addDiagnostic(ts.createDiagnosticForNode(symbolAccessibilityResult.errorNode || errorInfo.errorNode, errorInfo.diagnosticMessage, symbolAccessibilityResult.errorSymbolName, symbolAccessibilityResult.errorModuleName));
97483                     }
97484                 }
97485             }
97486         }
97487         function trackExternalModuleSymbolOfImportTypeNode(symbol) {
97488             if (!isBundledEmit) {
97489                 (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
97490             }
97491         }
97492         function trackSymbol(symbol, enclosingDeclaration, meaning) {
97493             if (symbol.flags & 262144 /* TypeParameter */)
97494                 return;
97495             handleSymbolAccessibilityError(resolver.isSymbolAccessible(symbol, enclosingDeclaration, meaning, /*shouldComputeAliasesToMakeVisible*/ true));
97496             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForSymbol(symbol, meaning));
97497         }
97498         function reportPrivateInBaseOfClassExpression(propertyName) {
97499             if (errorNameNode) {
97500                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.Property_0_of_exported_class_expression_may_not_be_private_or_protected, propertyName));
97501             }
97502         }
97503         function reportInaccessibleUniqueSymbolError() {
97504             if (errorNameNode) {
97505                 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"));
97506             }
97507         }
97508         function reportCyclicStructureError() {
97509             if (errorNameNode) {
97510                 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)));
97511             }
97512         }
97513         function reportInaccessibleThisError() {
97514             if (errorNameNode) {
97515                 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"));
97516             }
97517         }
97518         function reportLikelyUnsafeImportRequiredError(specifier) {
97519             if (errorNameNode) {
97520                 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));
97521             }
97522         }
97523         function reportTruncationError() {
97524             if (errorNameNode) {
97525                 context.addDiagnostic(ts.createDiagnosticForNode(errorNameNode, ts.Diagnostics.The_inferred_type_of_this_node_exceeds_the_maximum_length_the_compiler_will_serialize_An_explicit_type_annotation_is_needed));
97526             }
97527         }
97528         function reportNonlocalAugmentation(containingFile, parentSymbol, symbol) {
97529             var primaryDeclaration = ts.find(parentSymbol.declarations, function (d) { return ts.getSourceFileOfNode(d) === containingFile; });
97530             var augmentingDeclarations = ts.filter(symbol.declarations, function (d) { return ts.getSourceFileOfNode(d) !== containingFile; });
97531             for (var _i = 0, augmentingDeclarations_1 = augmentingDeclarations; _i < augmentingDeclarations_1.length; _i++) {
97532                 var augmentations = augmentingDeclarations_1[_i];
97533                 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)));
97534             }
97535         }
97536         function transformDeclarationsForJS(sourceFile, bundled) {
97537             var oldDiag = getSymbolAccessibilityDiagnostic;
97538             getSymbolAccessibilityDiagnostic = function (s) { return ({
97539                 diagnosticMessage: s.errorModuleName
97540                     ? ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_from_module_1_An_explicit_type_annotation_may_unblock_declaration_emit
97541                     : ts.Diagnostics.Declaration_emit_for_this_file_requires_using_private_name_0_An_explicit_type_annotation_may_unblock_declaration_emit,
97542                 errorNode: s.errorNode || sourceFile
97543             }); };
97544             var result = resolver.getDeclarationStatementsForSourceFile(sourceFile, declarationEmitNodeBuilderFlags, symbolTracker, bundled);
97545             getSymbolAccessibilityDiagnostic = oldDiag;
97546             return result;
97547         }
97548         function transformRoot(node) {
97549             if (node.kind === 297 /* SourceFile */ && node.isDeclarationFile) {
97550                 return node;
97551             }
97552             if (node.kind === 298 /* Bundle */) {
97553                 isBundledEmit = true;
97554                 refs = new ts.Map();
97555                 libs = new ts.Map();
97556                 var hasNoDefaultLib_1 = false;
97557                 var bundle = factory.createBundle(ts.map(node.sourceFiles, function (sourceFile) {
97558                     if (sourceFile.isDeclarationFile)
97559                         return undefined; // Omit declaration files from bundle results, too // TODO: GH#18217
97560                     hasNoDefaultLib_1 = hasNoDefaultLib_1 || sourceFile.hasNoDefaultLib;
97561                     currentSourceFile = sourceFile;
97562                     enclosingDeclaration = sourceFile;
97563                     lateMarkedStatements = undefined;
97564                     suppressNewDiagnosticContexts = false;
97565                     lateStatementReplacementMap = new ts.Map();
97566                     getSymbolAccessibilityDiagnostic = throwDiagnostic;
97567                     needsScopeFixMarker = false;
97568                     resultHasScopeMarker = false;
97569                     collectReferences(sourceFile, refs);
97570                     collectLibs(sourceFile, libs);
97571                     if (ts.isExternalOrCommonJsModule(sourceFile) || ts.isJsonSourceFile(sourceFile)) {
97572                         resultHasExternalModuleIndicator = false; // unused in external module bundle emit (all external modules are within module blocks, therefore are known to be modules)
97573                         needsDeclare = false;
97574                         var statements = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile, /*bundled*/ true)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
97575                         var newFile = factory.updateSourceFile(sourceFile, [factory.createModuleDeclaration([], [factory.createModifier(133 /* DeclareKeyword */)], factory.createStringLiteral(ts.getResolvedExternalModuleName(context.getEmitHost(), sourceFile)), factory.createModuleBlock(ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), sourceFile.statements)))], /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
97576                         return newFile;
97577                     }
97578                     needsDeclare = true;
97579                     var updated = ts.isSourceFileJS(sourceFile) ? factory.createNodeArray(transformDeclarationsForJS(sourceFile)) : ts.visitNodes(sourceFile.statements, visitDeclarationStatements);
97580                     return factory.updateSourceFile(sourceFile, transformAndReplaceLatePaintedStatements(updated), /*isDeclarationFile*/ true, /*referencedFiles*/ [], /*typeReferences*/ [], /*hasNoDefaultLib*/ false, /*libReferences*/ []);
97581                 }), ts.mapDefined(node.prepends, function (prepend) {
97582                     if (prepend.kind === 300 /* InputFiles */) {
97583                         var sourceFile = ts.createUnparsedSourceFile(prepend, "dts", stripInternal);
97584                         hasNoDefaultLib_1 = hasNoDefaultLib_1 || !!sourceFile.hasNoDefaultLib;
97585                         collectReferences(sourceFile, refs);
97586                         recordTypeReferenceDirectivesIfNecessary(sourceFile.typeReferenceDirectives);
97587                         collectLibs(sourceFile, libs);
97588                         return sourceFile;
97589                     }
97590                     return prepend;
97591                 }));
97592                 bundle.syntheticFileReferences = [];
97593                 bundle.syntheticTypeReferences = getFileReferencesForUsedTypeReferences();
97594                 bundle.syntheticLibReferences = getLibReferences();
97595                 bundle.hasNoDefaultLib = hasNoDefaultLib_1;
97596                 var outputFilePath_1 = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
97597                 var referenceVisitor_1 = mapReferencesIntoArray(bundle.syntheticFileReferences, outputFilePath_1);
97598                 refs.forEach(referenceVisitor_1);
97599                 return bundle;
97600             }
97601             // Single source file
97602             needsDeclare = true;
97603             needsScopeFixMarker = false;
97604             resultHasScopeMarker = false;
97605             enclosingDeclaration = node;
97606             currentSourceFile = node;
97607             getSymbolAccessibilityDiagnostic = throwDiagnostic;
97608             isBundledEmit = false;
97609             resultHasExternalModuleIndicator = false;
97610             suppressNewDiagnosticContexts = false;
97611             lateMarkedStatements = undefined;
97612             lateStatementReplacementMap = new ts.Map();
97613             necessaryTypeReferences = undefined;
97614             refs = collectReferences(currentSourceFile, new ts.Map());
97615             libs = collectLibs(currentSourceFile, new ts.Map());
97616             var references = [];
97617             var outputFilePath = ts.getDirectoryPath(ts.normalizeSlashes(ts.getOutputPathsFor(node, host, /*forceDtsPaths*/ true).declarationFilePath));
97618             var referenceVisitor = mapReferencesIntoArray(references, outputFilePath);
97619             var combinedStatements;
97620             if (ts.isSourceFileJS(currentSourceFile)) {
97621                 combinedStatements = factory.createNodeArray(transformDeclarationsForJS(node));
97622                 refs.forEach(referenceVisitor);
97623                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
97624             }
97625             else {
97626                 var statements = ts.visitNodes(node.statements, visitDeclarationStatements);
97627                 combinedStatements = ts.setTextRange(factory.createNodeArray(transformAndReplaceLatePaintedStatements(statements)), node.statements);
97628                 refs.forEach(referenceVisitor);
97629                 emittedImports = ts.filter(combinedStatements, ts.isAnyImportSyntax);
97630                 if (ts.isExternalModule(node) && (!resultHasExternalModuleIndicator || (needsScopeFixMarker && !resultHasScopeMarker))) {
97631                     combinedStatements = ts.setTextRange(factory.createNodeArray(__spreadArrays(combinedStatements, [ts.createEmptyExports(factory)])), combinedStatements);
97632                 }
97633             }
97634             var updated = factory.updateSourceFile(node, combinedStatements, /*isDeclarationFile*/ true, references, getFileReferencesForUsedTypeReferences(), node.hasNoDefaultLib, getLibReferences());
97635             updated.exportedModulesFromDeclarationEmit = exportedModulesFromDeclarationEmit;
97636             return updated;
97637             function getLibReferences() {
97638                 return ts.map(ts.arrayFrom(libs.keys()), function (lib) { return ({ fileName: lib, pos: -1, end: -1 }); });
97639             }
97640             function getFileReferencesForUsedTypeReferences() {
97641                 return necessaryTypeReferences ? ts.mapDefined(ts.arrayFrom(necessaryTypeReferences.keys()), getFileReferenceForTypeName) : [];
97642             }
97643             function getFileReferenceForTypeName(typeName) {
97644                 // Elide type references for which we have imports
97645                 if (emittedImports) {
97646                     for (var _i = 0, emittedImports_1 = emittedImports; _i < emittedImports_1.length; _i++) {
97647                         var importStatement = emittedImports_1[_i];
97648                         if (ts.isImportEqualsDeclaration(importStatement) && ts.isExternalModuleReference(importStatement.moduleReference)) {
97649                             var expr = importStatement.moduleReference.expression;
97650                             if (ts.isStringLiteralLike(expr) && expr.text === typeName) {
97651                                 return undefined;
97652                             }
97653                         }
97654                         else if (ts.isImportDeclaration(importStatement) && ts.isStringLiteral(importStatement.moduleSpecifier) && importStatement.moduleSpecifier.text === typeName) {
97655                             return undefined;
97656                         }
97657                     }
97658                 }
97659                 return { fileName: typeName, pos: -1, end: -1 };
97660             }
97661             function mapReferencesIntoArray(references, outputFilePath) {
97662                 return function (file) {
97663                     var declFileName;
97664                     if (file.isDeclarationFile) { // Neither decl files or js should have their refs changed
97665                         declFileName = file.fileName;
97666                     }
97667                     else {
97668                         if (isBundledEmit && ts.contains(node.sourceFiles, file))
97669                             return; // Omit references to files which are being merged
97670                         var paths = ts.getOutputPathsFor(file, host, /*forceDtsPaths*/ true);
97671                         declFileName = paths.declarationFilePath || paths.jsFilePath || file.fileName;
97672                     }
97673                     if (declFileName) {
97674                         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, 
97675                         /*preferences*/ undefined);
97676                         if (!ts.pathIsRelative(specifier)) {
97677                             // If some compiler option/symlink/whatever allows access to the file containing the ambient module declaration
97678                             // via a non-relative name, emit a type reference directive to that non-relative name, rather than
97679                             // a relative path to the declaration file
97680                             recordTypeReferenceDirectivesIfNecessary([specifier]);
97681                             return;
97682                         }
97683                         var fileName = ts.getRelativePathToDirectoryOrUrl(outputFilePath, declFileName, host.getCurrentDirectory(), host.getCanonicalFileName, 
97684                         /*isAbsolutePathAnUrl*/ false);
97685                         if (ts.startsWith(fileName, "./") && ts.hasExtension(fileName)) {
97686                             fileName = fileName.substring(2);
97687                         }
97688                         // omit references to files from node_modules (npm may disambiguate module
97689                         // references when installing this package, making the path is unreliable).
97690                         if (ts.startsWith(fileName, "node_modules/") || ts.pathContainsNodeModules(fileName)) {
97691                             return;
97692                         }
97693                         references.push({ pos: -1, end: -1, fileName: fileName });
97694                     }
97695                 };
97696             }
97697         }
97698         function collectReferences(sourceFile, ret) {
97699             if (noResolve || (!ts.isUnparsedSource(sourceFile) && ts.isSourceFileJS(sourceFile)))
97700                 return ret;
97701             ts.forEach(sourceFile.referencedFiles, function (f) {
97702                 var elem = host.getSourceFileFromReference(sourceFile, f);
97703                 if (elem) {
97704                     ret.set(ts.getOriginalNodeId(elem), elem);
97705                 }
97706             });
97707             return ret;
97708         }
97709         function collectLibs(sourceFile, ret) {
97710             ts.forEach(sourceFile.libReferenceDirectives, function (ref) {
97711                 var lib = host.getLibFileFromReference(ref);
97712                 if (lib) {
97713                     ret.set(ts.toFileNameLowerCase(ref.fileName), true);
97714                 }
97715             });
97716             return ret;
97717         }
97718         function filterBindingPatternInitializers(name) {
97719             if (name.kind === 78 /* Identifier */) {
97720                 return name;
97721             }
97722             else {
97723                 if (name.kind === 197 /* ArrayBindingPattern */) {
97724                     return factory.updateArrayBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
97725                 }
97726                 else {
97727                     return factory.updateObjectBindingPattern(name, ts.visitNodes(name.elements, visitBindingElement));
97728                 }
97729             }
97730             function visitBindingElement(elem) {
97731                 if (elem.kind === 222 /* OmittedExpression */) {
97732                     return elem;
97733                 }
97734                 return factory.updateBindingElement(elem, elem.dotDotDotToken, elem.propertyName, filterBindingPatternInitializers(elem.name), shouldPrintWithInitializer(elem) ? elem.initializer : undefined);
97735             }
97736         }
97737         function ensureParameter(p, modifierMask, type) {
97738             var oldDiag;
97739             if (!suppressNewDiagnosticContexts) {
97740                 oldDiag = getSymbolAccessibilityDiagnostic;
97741                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p);
97742             }
97743             var newParam = factory.updateParameterDeclaration(p, 
97744             /*decorators*/ undefined, maskModifiers(p, modifierMask), p.dotDotDotToken, filterBindingPatternInitializers(p.name), resolver.isOptionalParameter(p) ? (p.questionToken || factory.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
97745             ensureNoInitializer(p));
97746             if (!suppressNewDiagnosticContexts) {
97747                 getSymbolAccessibilityDiagnostic = oldDiag;
97748             }
97749             return newParam;
97750         }
97751         function shouldPrintWithInitializer(node) {
97752             return canHaveLiteralInitializer(node) && resolver.isLiteralConstDeclaration(ts.getParseTreeNode(node)); // TODO: Make safe
97753         }
97754         function ensureNoInitializer(node) {
97755             if (shouldPrintWithInitializer(node)) {
97756                 return resolver.createLiteralConstValue(ts.getParseTreeNode(node), symbolTracker); // TODO: Make safe
97757             }
97758             return undefined;
97759         }
97760         function ensureType(node, type, ignorePrivate) {
97761             if (!ignorePrivate && ts.hasEffectiveModifier(node, 8 /* Private */)) {
97762                 // Private nodes emit no types (except private parameter properties, whose parameter types are actually visible)
97763                 return;
97764             }
97765             if (shouldPrintWithInitializer(node)) {
97766                 // Literal const declarations will have an initializer ensured rather than a type
97767                 return;
97768             }
97769             var shouldUseResolverType = node.kind === 160 /* Parameter */ &&
97770                 (resolver.isRequiredInitializedParameter(node) ||
97771                     resolver.isOptionalUninitializedParameterProperty(node));
97772             if (type && !shouldUseResolverType) {
97773                 return ts.visitNode(type, visitDeclarationSubtree);
97774             }
97775             if (!ts.getParseTreeNode(node)) {
97776                 return type ? ts.visitNode(type, visitDeclarationSubtree) : factory.createKeywordTypeNode(128 /* AnyKeyword */);
97777             }
97778             if (node.kind === 168 /* SetAccessor */) {
97779                 // 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
97780                 // (The inferred type here will be void, but the old declaration emitter printed `any`, so this replicates that)
97781                 return factory.createKeywordTypeNode(128 /* AnyKeyword */);
97782             }
97783             errorNameNode = node.name;
97784             var oldDiag;
97785             if (!suppressNewDiagnosticContexts) {
97786                 oldDiag = getSymbolAccessibilityDiagnostic;
97787                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(node);
97788             }
97789             if (node.kind === 249 /* VariableDeclaration */ || node.kind === 198 /* BindingElement */) {
97790                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
97791             }
97792             if (node.kind === 160 /* Parameter */
97793                 || node.kind === 163 /* PropertyDeclaration */
97794                 || node.kind === 162 /* PropertySignature */) {
97795                 if (!node.initializer)
97796                     return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType));
97797                 return cleanup(resolver.createTypeOfDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker, shouldUseResolverType) || resolver.createTypeOfExpression(node.initializer, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
97798             }
97799             return cleanup(resolver.createReturnTypeOfSignatureDeclaration(node, enclosingDeclaration, declarationEmitNodeBuilderFlags, symbolTracker));
97800             function cleanup(returnValue) {
97801                 errorNameNode = undefined;
97802                 if (!suppressNewDiagnosticContexts) {
97803                     getSymbolAccessibilityDiagnostic = oldDiag;
97804                 }
97805                 return returnValue || factory.createKeywordTypeNode(128 /* AnyKeyword */);
97806             }
97807         }
97808         function isDeclarationAndNotVisible(node) {
97809             node = ts.getParseTreeNode(node);
97810             switch (node.kind) {
97811                 case 251 /* FunctionDeclaration */:
97812                 case 256 /* ModuleDeclaration */:
97813                 case 253 /* InterfaceDeclaration */:
97814                 case 252 /* ClassDeclaration */:
97815                 case 254 /* TypeAliasDeclaration */:
97816                 case 255 /* EnumDeclaration */:
97817                     return !resolver.isDeclarationVisible(node);
97818                 // The following should be doing their own visibility checks based on filtering their members
97819                 case 249 /* VariableDeclaration */:
97820                     return !getBindingNameVisible(node);
97821                 case 260 /* ImportEqualsDeclaration */:
97822                 case 261 /* ImportDeclaration */:
97823                 case 267 /* ExportDeclaration */:
97824                 case 266 /* ExportAssignment */:
97825                     return false;
97826             }
97827             return false;
97828         }
97829         function getBindingNameVisible(elem) {
97830             if (ts.isOmittedExpression(elem)) {
97831                 return false;
97832             }
97833             if (ts.isBindingPattern(elem.name)) {
97834                 // If any child binding pattern element has been marked visible (usually by collect linked aliases), then this is visible
97835                 return ts.some(elem.name.elements, getBindingNameVisible);
97836             }
97837             else {
97838                 return resolver.isDeclarationVisible(elem);
97839             }
97840         }
97841         function updateParamsList(node, params, modifierMask) {
97842             if (ts.hasEffectiveModifier(node, 8 /* Private */)) {
97843                 return undefined; // TODO: GH#18217
97844             }
97845             var newParams = ts.map(params, function (p) { return ensureParameter(p, modifierMask); });
97846             if (!newParams) {
97847                 return undefined; // TODO: GH#18217
97848             }
97849             return factory.createNodeArray(newParams, params.hasTrailingComma);
97850         }
97851         function updateAccessorParamsList(input, isPrivate) {
97852             var newParams;
97853             if (!isPrivate) {
97854                 var thisParameter = ts.getThisParameter(input);
97855                 if (thisParameter) {
97856                     newParams = [ensureParameter(thisParameter)];
97857                 }
97858             }
97859             if (ts.isSetAccessorDeclaration(input)) {
97860                 var newValueParameter = void 0;
97861                 if (!isPrivate) {
97862                     var valueParameter = ts.getSetAccessorValueParameter(input);
97863                     if (valueParameter) {
97864                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
97865                         newValueParameter = ensureParameter(valueParameter, /*modifierMask*/ undefined, accessorType);
97866                     }
97867                 }
97868                 if (!newValueParameter) {
97869                     newValueParameter = factory.createParameterDeclaration(
97870                     /*decorators*/ undefined, 
97871                     /*modifiers*/ undefined, 
97872                     /*dotDotDotToken*/ undefined, "value");
97873                 }
97874                 newParams = ts.append(newParams, newValueParameter);
97875             }
97876             return factory.createNodeArray(newParams || ts.emptyArray);
97877         }
97878         function ensureTypeParams(node, params) {
97879             return ts.hasEffectiveModifier(node, 8 /* Private */) ? undefined : ts.visitNodes(params, visitDeclarationSubtree);
97880         }
97881         function isEnclosingDeclaration(node) {
97882             return ts.isSourceFile(node)
97883                 || ts.isTypeAliasDeclaration(node)
97884                 || ts.isModuleDeclaration(node)
97885                 || ts.isClassDeclaration(node)
97886                 || ts.isInterfaceDeclaration(node)
97887                 || ts.isFunctionLike(node)
97888                 || ts.isIndexSignatureDeclaration(node)
97889                 || ts.isMappedTypeNode(node);
97890         }
97891         function checkEntityNameVisibility(entityName, enclosingDeclaration) {
97892             var visibilityResult = resolver.isEntityNameVisible(entityName, enclosingDeclaration);
97893             handleSymbolAccessibilityError(visibilityResult);
97894             recordTypeReferenceDirectivesIfNecessary(resolver.getTypeReferenceDirectivesForEntityName(entityName));
97895         }
97896         function preserveJsDoc(updated, original) {
97897             if (ts.hasJSDocNodes(updated) && ts.hasJSDocNodes(original)) {
97898                 updated.jsDoc = original.jsDoc;
97899             }
97900             return ts.setCommentRange(updated, ts.getCommentRange(original));
97901         }
97902         function rewriteModuleSpecifier(parent, input) {
97903             if (!input)
97904                 return undefined; // TODO: GH#18217
97905             resultHasExternalModuleIndicator = resultHasExternalModuleIndicator || (parent.kind !== 256 /* ModuleDeclaration */ && parent.kind !== 195 /* ImportType */);
97906             if (ts.isStringLiteralLike(input)) {
97907                 if (isBundledEmit) {
97908                     var newName = ts.getExternalModuleNameFromDeclaration(context.getEmitHost(), resolver, parent);
97909                     if (newName) {
97910                         return factory.createStringLiteral(newName);
97911                     }
97912                 }
97913                 else {
97914                     var symbol = resolver.getSymbolOfExternalModuleSpecifier(input);
97915                     if (symbol) {
97916                         (exportedModulesFromDeclarationEmit || (exportedModulesFromDeclarationEmit = [])).push(symbol);
97917                     }
97918                 }
97919             }
97920             return input;
97921         }
97922         function transformImportEqualsDeclaration(decl) {
97923             if (!resolver.isDeclarationVisible(decl))
97924                 return;
97925             if (decl.moduleReference.kind === 272 /* ExternalModuleReference */) {
97926                 // Rewrite external module names if necessary
97927                 var specifier = ts.getExternalModuleImportEqualsDeclarationExpression(decl);
97928                 return factory.updateImportEqualsDeclaration(decl, 
97929                 /*decorators*/ undefined, decl.modifiers, decl.name, factory.updateExternalModuleReference(decl.moduleReference, rewriteModuleSpecifier(decl, specifier)));
97930             }
97931             else {
97932                 var oldDiag = getSymbolAccessibilityDiagnostic;
97933                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(decl);
97934                 checkEntityNameVisibility(decl.moduleReference, enclosingDeclaration);
97935                 getSymbolAccessibilityDiagnostic = oldDiag;
97936                 return decl;
97937             }
97938         }
97939         function transformImportDeclaration(decl) {
97940             if (!decl.importClause) {
97941                 // import "mod" - possibly needed for side effects? (global interface patches, module augmentations, etc)
97942                 return factory.updateImportDeclaration(decl, 
97943                 /*decorators*/ undefined, decl.modifiers, decl.importClause, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
97944             }
97945             // The `importClause` visibility corresponds to the default's visibility.
97946             var visibleDefaultBinding = decl.importClause && decl.importClause.name && resolver.isDeclarationVisible(decl.importClause) ? decl.importClause.name : undefined;
97947             if (!decl.importClause.namedBindings) {
97948                 // No named bindings (either namespace or list), meaning the import is just default or should be elided
97949                 return visibleDefaultBinding && factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, 
97950                 /*namedBindings*/ undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
97951             }
97952             if (decl.importClause.namedBindings.kind === 263 /* NamespaceImport */) {
97953                 // Namespace import (optionally with visible default)
97954                 var namedBindings = resolver.isDeclarationVisible(decl.importClause.namedBindings) ? decl.importClause.namedBindings : /*namedBindings*/ undefined;
97955                 return visibleDefaultBinding || namedBindings ? factory.updateImportDeclaration(decl, /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, namedBindings), rewriteModuleSpecifier(decl, decl.moduleSpecifier)) : undefined;
97956             }
97957             // Named imports (optionally with visible default)
97958             var bindingList = ts.mapDefined(decl.importClause.namedBindings.elements, function (b) { return resolver.isDeclarationVisible(b) ? b : undefined; });
97959             if ((bindingList && bindingList.length) || visibleDefaultBinding) {
97960                 return factory.updateImportDeclaration(decl, 
97961                 /*decorators*/ undefined, decl.modifiers, factory.updateImportClause(decl.importClause, decl.importClause.isTypeOnly, visibleDefaultBinding, bindingList && bindingList.length ? factory.updateNamedImports(decl.importClause.namedBindings, bindingList) : undefined), rewriteModuleSpecifier(decl, decl.moduleSpecifier));
97962             }
97963             // Augmentation of export depends on import
97964             if (resolver.isImportRequiredByAugmentation(decl)) {
97965                 return factory.updateImportDeclaration(decl, 
97966                 /*decorators*/ undefined, decl.modifiers, 
97967                 /*importClause*/ undefined, rewriteModuleSpecifier(decl, decl.moduleSpecifier));
97968             }
97969             // Nothing visible
97970         }
97971         function transformAndReplaceLatePaintedStatements(statements) {
97972             // This is a `while` loop because `handleSymbolAccessibilityError` can see additional import aliases marked as visible during
97973             // error handling which must now be included in the output and themselves checked for errors.
97974             // For example:
97975             // ```
97976             // module A {
97977             //   export module Q {}
97978             //   import B = Q;
97979             //   import C = B;
97980             //   export import D = C;
97981             // }
97982             // ```
97983             // 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
97984             // 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
97985             // dependent imports and allowing a valid declaration file output. Today, this dependent alias marking only happens for internal import aliases.
97986             while (ts.length(lateMarkedStatements)) {
97987                 var i = lateMarkedStatements.shift();
97988                 if (!ts.isLateVisibilityPaintedStatement(i)) {
97989                     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));
97990                 }
97991                 var priorNeedsDeclare = needsDeclare;
97992                 needsDeclare = i.parent && ts.isSourceFile(i.parent) && !(ts.isExternalModule(i.parent) && isBundledEmit);
97993                 var result = transformTopLevelDeclaration(i);
97994                 needsDeclare = priorNeedsDeclare;
97995                 lateStatementReplacementMap.set(ts.getOriginalNodeId(i), result);
97996             }
97997             // And lastly, we need to get the final form of all those indetermine import declarations from before and add them to the output list
97998             // (and remove them from the set to examine for outter declarations)
97999             return ts.visitNodes(statements, visitLateVisibilityMarkedStatements);
98000             function visitLateVisibilityMarkedStatements(statement) {
98001                 if (ts.isLateVisibilityPaintedStatement(statement)) {
98002                     var key = ts.getOriginalNodeId(statement);
98003                     if (lateStatementReplacementMap.has(key)) {
98004                         var result = lateStatementReplacementMap.get(key);
98005                         lateStatementReplacementMap.delete(key);
98006                         if (result) {
98007                             if (ts.isArray(result) ? ts.some(result, ts.needsScopeMarker) : ts.needsScopeMarker(result)) {
98008                                 // Top-level declarations in .d.ts files are always considered exported even without a modifier unless there's an export assignment or specifier
98009                                 needsScopeFixMarker = true;
98010                             }
98011                             if (ts.isSourceFile(statement.parent) && (ts.isArray(result) ? ts.some(result, ts.isExternalModuleIndicator) : ts.isExternalModuleIndicator(result))) {
98012                                 resultHasExternalModuleIndicator = true;
98013                             }
98014                         }
98015                         return result;
98016                     }
98017                 }
98018                 return statement;
98019             }
98020         }
98021         function visitDeclarationSubtree(input) {
98022             if (shouldStripInternal(input))
98023                 return;
98024             if (ts.isDeclaration(input)) {
98025                 if (isDeclarationAndNotVisible(input))
98026                     return;
98027                 if (ts.hasDynamicName(input) && !resolver.isLateBound(ts.getParseTreeNode(input))) {
98028                     return;
98029                 }
98030             }
98031             // Elide implementation signatures from overload sets
98032             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
98033                 return;
98034             // Elide semicolon class statements
98035             if (ts.isSemicolonClassElement(input))
98036                 return;
98037             var previousEnclosingDeclaration;
98038             if (isEnclosingDeclaration(input)) {
98039                 previousEnclosingDeclaration = enclosingDeclaration;
98040                 enclosingDeclaration = input;
98041             }
98042             var oldDiag = getSymbolAccessibilityDiagnostic;
98043             // Setup diagnostic-related flags before first potential `cleanup` call, otherwise
98044             // We'd see a TDZ violation at runtime
98045             var canProduceDiagnostic = ts.canProduceDiagnostics(input);
98046             var oldWithinObjectLiteralType = suppressNewDiagnosticContexts;
98047             var shouldEnterSuppressNewDiagnosticsContextContext = ((input.kind === 177 /* TypeLiteral */ || input.kind === 190 /* MappedType */) && input.parent.kind !== 254 /* TypeAliasDeclaration */);
98048             // Emit methods which are private as properties with no type information
98049             if (ts.isMethodDeclaration(input) || ts.isMethodSignature(input)) {
98050                 if (ts.hasEffectiveModifier(input, 8 /* Private */)) {
98051                     if (input.symbol && input.symbol.declarations && input.symbol.declarations[0] !== input)
98052                         return; // Elide all but the first overload
98053                     return cleanup(factory.createPropertyDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, /*questionToken*/ undefined, /*type*/ undefined, /*initializer*/ undefined));
98054                 }
98055             }
98056             if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
98057                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
98058             }
98059             if (ts.isTypeQueryNode(input)) {
98060                 checkEntityNameVisibility(input.exprName, enclosingDeclaration);
98061             }
98062             if (shouldEnterSuppressNewDiagnosticsContextContext) {
98063                 // 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.
98064                 suppressNewDiagnosticContexts = true;
98065             }
98066             if (isProcessedComponent(input)) {
98067                 switch (input.kind) {
98068                     case 223 /* ExpressionWithTypeArguments */: {
98069                         if ((ts.isEntityName(input.expression) || ts.isEntityNameExpression(input.expression))) {
98070                             checkEntityNameVisibility(input.expression, enclosingDeclaration);
98071                         }
98072                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
98073                         return cleanup(factory.updateExpressionWithTypeArguments(node, node.expression, node.typeArguments));
98074                     }
98075                     case 173 /* TypeReference */: {
98076                         checkEntityNameVisibility(input.typeName, enclosingDeclaration);
98077                         var node = ts.visitEachChild(input, visitDeclarationSubtree, context);
98078                         return cleanup(factory.updateTypeReferenceNode(node, node.typeName, node.typeArguments));
98079                     }
98080                     case 170 /* ConstructSignature */:
98081                         return cleanup(factory.updateConstructSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
98082                     case 166 /* Constructor */: {
98083                         // A constructor declaration may not have a type annotation
98084                         var ctor = factory.createConstructorDeclaration(
98085                         /*decorators*/ undefined, 
98086                         /*modifiers*/ ensureModifiers(input), updateParamsList(input, input.parameters, 0 /* None */), 
98087                         /*body*/ undefined);
98088                         return cleanup(ctor);
98089                     }
98090                     case 165 /* MethodDeclaration */: {
98091                         if (ts.isPrivateIdentifier(input.name)) {
98092                             return cleanup(/*returnValue*/ undefined);
98093                         }
98094                         var sig = factory.createMethodDeclaration(
98095                         /*decorators*/ undefined, ensureModifiers(input), 
98096                         /*asteriskToken*/ undefined, input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
98097                         /*body*/ undefined);
98098                         return cleanup(sig);
98099                     }
98100                     case 167 /* GetAccessor */: {
98101                         if (ts.isPrivateIdentifier(input.name)) {
98102                             return cleanup(/*returnValue*/ undefined);
98103                         }
98104                         var accessorType = getTypeAnnotationFromAllAccessorDeclarations(input, resolver.getAllAccessorDeclarations(input));
98105                         return cleanup(factory.updateGetAccessorDeclaration(input, 
98106                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), ensureType(input, accessorType), 
98107                         /*body*/ undefined));
98108                     }
98109                     case 168 /* SetAccessor */: {
98110                         if (ts.isPrivateIdentifier(input.name)) {
98111                             return cleanup(/*returnValue*/ undefined);
98112                         }
98113                         return cleanup(factory.updateSetAccessorDeclaration(input, 
98114                         /*decorators*/ undefined, ensureModifiers(input), input.name, updateAccessorParamsList(input, ts.hasEffectiveModifier(input, 8 /* Private */)), 
98115                         /*body*/ undefined));
98116                     }
98117                     case 163 /* PropertyDeclaration */:
98118                         if (ts.isPrivateIdentifier(input.name)) {
98119                             return cleanup(/*returnValue*/ undefined);
98120                         }
98121                         return cleanup(factory.updatePropertyDeclaration(input, 
98122                         /*decorators*/ undefined, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type), ensureNoInitializer(input)));
98123                     case 162 /* PropertySignature */:
98124                         if (ts.isPrivateIdentifier(input.name)) {
98125                             return cleanup(/*returnValue*/ undefined);
98126                         }
98127                         return cleanup(factory.updatePropertySignature(input, ensureModifiers(input), input.name, input.questionToken, ensureType(input, input.type)));
98128                     case 164 /* MethodSignature */: {
98129                         if (ts.isPrivateIdentifier(input.name)) {
98130                             return cleanup(/*returnValue*/ undefined);
98131                         }
98132                         return cleanup(factory.updateMethodSignature(input, ensureModifiers(input), input.name, input.questionToken, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
98133                     }
98134                     case 169 /* CallSignature */: {
98135                         return cleanup(factory.updateCallSignature(input, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type)));
98136                     }
98137                     case 171 /* IndexSignature */: {
98138                         return cleanup(factory.updateIndexSignature(input, 
98139                         /*decorators*/ undefined, ensureModifiers(input), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree) || factory.createKeywordTypeNode(128 /* AnyKeyword */)));
98140                     }
98141                     case 249 /* VariableDeclaration */: {
98142                         if (ts.isBindingPattern(input.name)) {
98143                             return recreateBindingPattern(input.name);
98144                         }
98145                         shouldEnterSuppressNewDiagnosticsContextContext = true;
98146                         suppressNewDiagnosticContexts = true; // Variable declaration types also suppress new diagnostic contexts, provided the contexts wouldn't be made for binding pattern types
98147                         return cleanup(factory.updateVariableDeclaration(input, input.name, /*exclamationToken*/ undefined, ensureType(input, input.type), ensureNoInitializer(input)));
98148                     }
98149                     case 159 /* TypeParameter */: {
98150                         if (isPrivateMethodTypeParameter(input) && (input.default || input.constraint)) {
98151                             return cleanup(factory.updateTypeParameterDeclaration(input, input.name, /*constraint*/ undefined, /*defaultType*/ undefined));
98152                         }
98153                         return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
98154                     }
98155                     case 184 /* ConditionalType */: {
98156                         // We have to process conditional types in a special way because for visibility purposes we need to push a new enclosingDeclaration
98157                         // just for the `infer` types in the true branch. It's an implicit declaration scope that only applies to _part_ of the type.
98158                         var checkType = ts.visitNode(input.checkType, visitDeclarationSubtree);
98159                         var extendsType = ts.visitNode(input.extendsType, visitDeclarationSubtree);
98160                         var oldEnclosingDecl = enclosingDeclaration;
98161                         enclosingDeclaration = input.trueType;
98162                         var trueType = ts.visitNode(input.trueType, visitDeclarationSubtree);
98163                         enclosingDeclaration = oldEnclosingDecl;
98164                         var falseType = ts.visitNode(input.falseType, visitDeclarationSubtree);
98165                         return cleanup(factory.updateConditionalTypeNode(input, checkType, extendsType, trueType, falseType));
98166                     }
98167                     case 174 /* FunctionType */: {
98168                         return cleanup(factory.updateFunctionTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
98169                     }
98170                     case 175 /* ConstructorType */: {
98171                         return cleanup(factory.updateConstructorTypeNode(input, ts.visitNodes(input.typeParameters, visitDeclarationSubtree), updateParamsList(input, input.parameters), ts.visitNode(input.type, visitDeclarationSubtree)));
98172                     }
98173                     case 195 /* ImportType */: {
98174                         if (!ts.isLiteralImportTypeNode(input))
98175                             return cleanup(input);
98176                         return cleanup(factory.updateImportTypeNode(input, factory.updateLiteralTypeNode(input.argument, rewriteModuleSpecifier(input, input.argument.literal)), input.qualifier, ts.visitNodes(input.typeArguments, visitDeclarationSubtree, ts.isTypeNode), input.isTypeOf));
98177                     }
98178                     default: ts.Debug.assertNever(input, "Attempted to process unhandled node kind: " + ts.SyntaxKind[input.kind]);
98179                 }
98180             }
98181             if (ts.isTupleTypeNode(input) && (ts.getLineAndCharacterOfPosition(currentSourceFile, input.pos).line === ts.getLineAndCharacterOfPosition(currentSourceFile, input.end).line)) {
98182                 ts.setEmitFlags(input, 1 /* SingleLine */);
98183             }
98184             return cleanup(ts.visitEachChild(input, visitDeclarationSubtree, context));
98185             function cleanup(returnValue) {
98186                 if (returnValue && canProduceDiagnostic && ts.hasDynamicName(input)) {
98187                     checkName(input);
98188                 }
98189                 if (isEnclosingDeclaration(input)) {
98190                     enclosingDeclaration = previousEnclosingDeclaration;
98191                 }
98192                 if (canProduceDiagnostic && !suppressNewDiagnosticContexts) {
98193                     getSymbolAccessibilityDiagnostic = oldDiag;
98194                 }
98195                 if (shouldEnterSuppressNewDiagnosticsContextContext) {
98196                     suppressNewDiagnosticContexts = oldWithinObjectLiteralType;
98197                 }
98198                 if (returnValue === input) {
98199                     return returnValue;
98200                 }
98201                 return returnValue && ts.setOriginalNode(preserveJsDoc(returnValue, input), input);
98202             }
98203         }
98204         function isPrivateMethodTypeParameter(node) {
98205             return node.parent.kind === 165 /* MethodDeclaration */ && ts.hasEffectiveModifier(node.parent, 8 /* Private */);
98206         }
98207         function visitDeclarationStatements(input) {
98208             if (!isPreservedDeclarationStatement(input)) {
98209                 // return undefined for unmatched kinds to omit them from the tree
98210                 return;
98211             }
98212             if (shouldStripInternal(input))
98213                 return;
98214             switch (input.kind) {
98215                 case 267 /* ExportDeclaration */: {
98216                     if (ts.isSourceFile(input.parent)) {
98217                         resultHasExternalModuleIndicator = true;
98218                     }
98219                     resultHasScopeMarker = true;
98220                     // Always visible if the parent node isn't dropped for being not visible
98221                     // Rewrite external module names if necessary
98222                     return factory.updateExportDeclaration(input, 
98223                     /*decorators*/ undefined, input.modifiers, input.isTypeOnly, input.exportClause, rewriteModuleSpecifier(input, input.moduleSpecifier));
98224                 }
98225                 case 266 /* ExportAssignment */: {
98226                     // Always visible if the parent node isn't dropped for being not visible
98227                     if (ts.isSourceFile(input.parent)) {
98228                         resultHasExternalModuleIndicator = true;
98229                     }
98230                     resultHasScopeMarker = true;
98231                     if (input.expression.kind === 78 /* Identifier */) {
98232                         return input;
98233                     }
98234                     else {
98235                         var newId = factory.createUniqueName("_default", 16 /* Optimistic */);
98236                         getSymbolAccessibilityDiagnostic = function () { return ({
98237                             diagnosticMessage: ts.Diagnostics.Default_export_of_the_module_has_or_is_using_private_name_0,
98238                             errorNode: input
98239                         }); };
98240                         var varDecl = factory.createVariableDeclaration(newId, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(input.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
98241                         var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
98242                         return [statement, factory.updateExportAssignment(input, input.decorators, input.modifiers, newId)];
98243                     }
98244                 }
98245             }
98246             var result = transformTopLevelDeclaration(input);
98247             // Don't actually transform yet; just leave as original node - will be elided/swapped by late pass
98248             lateStatementReplacementMap.set(ts.getOriginalNodeId(input), result);
98249             return input;
98250         }
98251         function stripExportModifiers(statement) {
98252             if (ts.isImportEqualsDeclaration(statement) || ts.hasEffectiveModifier(statement, 512 /* Default */) || !ts.canHaveModifiers(statement)) {
98253                 // `export import` statements should remain as-is, as imports are _not_ implicitly exported in an ambient namespace
98254                 // Likewise, `export default` classes and the like and just be `default`, so we preserve their `export` modifiers, too
98255                 return statement;
98256             }
98257             var modifiers = factory.createModifiersFromModifierFlags(ts.getEffectiveModifierFlags(statement) & (11263 /* All */ ^ 1 /* Export */));
98258             return factory.updateModifiers(statement, modifiers);
98259         }
98260         function transformTopLevelDeclaration(input) {
98261             if (shouldStripInternal(input))
98262                 return;
98263             switch (input.kind) {
98264                 case 260 /* ImportEqualsDeclaration */: {
98265                     return transformImportEqualsDeclaration(input);
98266                 }
98267                 case 261 /* ImportDeclaration */: {
98268                     return transformImportDeclaration(input);
98269                 }
98270             }
98271             if (ts.isDeclaration(input) && isDeclarationAndNotVisible(input))
98272                 return;
98273             // Elide implementation signatures from overload sets
98274             if (ts.isFunctionLike(input) && resolver.isImplementationOfOverload(input))
98275                 return;
98276             var previousEnclosingDeclaration;
98277             if (isEnclosingDeclaration(input)) {
98278                 previousEnclosingDeclaration = enclosingDeclaration;
98279                 enclosingDeclaration = input;
98280             }
98281             var canProdiceDiagnostic = ts.canProduceDiagnostics(input);
98282             var oldDiag = getSymbolAccessibilityDiagnostic;
98283             if (canProdiceDiagnostic) {
98284                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(input);
98285             }
98286             var previousNeedsDeclare = needsDeclare;
98287             switch (input.kind) {
98288                 case 254 /* TypeAliasDeclaration */: // Type aliases get `declare`d if need be (for legacy support), but that's all
98289                     return cleanup(factory.updateTypeAliasDeclaration(input, 
98290                     /*decorators*/ undefined, ensureModifiers(input), input.name, ts.visitNodes(input.typeParameters, visitDeclarationSubtree, ts.isTypeParameterDeclaration), ts.visitNode(input.type, visitDeclarationSubtree, ts.isTypeNode)));
98291                 case 253 /* InterfaceDeclaration */: {
98292                     return cleanup(factory.updateInterfaceDeclaration(input, 
98293                     /*decorators*/ undefined, ensureModifiers(input), input.name, ensureTypeParams(input, input.typeParameters), transformHeritageClauses(input.heritageClauses), ts.visitNodes(input.members, visitDeclarationSubtree)));
98294                 }
98295                 case 251 /* FunctionDeclaration */: {
98296                     // Generators lose their generator-ness, excepting their return type
98297                     var clean = cleanup(factory.updateFunctionDeclaration(input, 
98298                     /*decorators*/ undefined, ensureModifiers(input), 
98299                     /*asteriskToken*/ undefined, input.name, ensureTypeParams(input, input.typeParameters), updateParamsList(input, input.parameters), ensureType(input, input.type), 
98300                     /*body*/ undefined));
98301                     if (clean && resolver.isExpandoFunctionDeclaration(input)) {
98302                         var props = resolver.getPropertiesOfContainerFunction(input);
98303                         // Use parseNodeFactory so it is usable as an enclosing declaration
98304                         var fakespace_1 = ts.parseNodeFactory.createModuleDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, clean.name || factory.createIdentifier("_default"), factory.createModuleBlock([]), 16 /* Namespace */);
98305                         ts.setParent(fakespace_1, enclosingDeclaration);
98306                         fakespace_1.locals = ts.createSymbolTable(props);
98307                         fakespace_1.symbol = props[0].parent;
98308                         var exportMappings_1 = [];
98309                         var declarations = ts.mapDefined(props, function (p) {
98310                             if (!ts.isPropertyAccessExpression(p.valueDeclaration)) {
98311                                 return undefined; // TODO GH#33569: Handle element access expressions that created late bound names (rather than silently omitting them)
98312                             }
98313                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(p.valueDeclaration);
98314                             var type = resolver.createTypeOfDeclaration(p.valueDeclaration, fakespace_1, declarationEmitNodeBuilderFlags, symbolTracker);
98315                             getSymbolAccessibilityDiagnostic = oldDiag;
98316                             var nameStr = ts.unescapeLeadingUnderscores(p.escapedName);
98317                             var isNonContextualKeywordName = ts.isStringANonContextualKeyword(nameStr);
98318                             var name = isNonContextualKeywordName ? factory.getGeneratedNameForNode(p.valueDeclaration) : factory.createIdentifier(nameStr);
98319                             if (isNonContextualKeywordName) {
98320                                 exportMappings_1.push([name, nameStr]);
98321                             }
98322                             var varDecl = factory.createVariableDeclaration(name, /*exclamationToken*/ undefined, type, /*initializer*/ undefined);
98323                             return factory.createVariableStatement(isNonContextualKeywordName ? undefined : [factory.createToken(92 /* ExportKeyword */)], factory.createVariableDeclarationList([varDecl]));
98324                         });
98325                         if (!exportMappings_1.length) {
98326                             declarations = ts.mapDefined(declarations, function (declaration) { return factory.updateModifiers(declaration, 0 /* None */); });
98327                         }
98328                         else {
98329                             declarations.push(factory.createExportDeclaration(
98330                             /*decorators*/ undefined, 
98331                             /*modifiers*/ undefined, 
98332                             /*isTypeOnly*/ false, factory.createNamedExports(ts.map(exportMappings_1, function (_a) {
98333                                 var gen = _a[0], exp = _a[1];
98334                                 return factory.createExportSpecifier(gen, exp);
98335                             }))));
98336                         }
98337                         var namespaceDecl = factory.createModuleDeclaration(/*decorators*/ undefined, ensureModifiers(input), input.name, factory.createModuleBlock(declarations), 16 /* Namespace */);
98338                         if (!ts.hasEffectiveModifier(clean, 512 /* Default */)) {
98339                             return [clean, namespaceDecl];
98340                         }
98341                         var modifiers = factory.createModifiersFromModifierFlags((ts.getEffectiveModifierFlags(clean) & ~513 /* ExportDefault */) | 2 /* Ambient */);
98342                         var cleanDeclaration = factory.updateFunctionDeclaration(clean, 
98343                         /*decorators*/ undefined, modifiers, 
98344                         /*asteriskToken*/ undefined, clean.name, clean.typeParameters, clean.parameters, clean.type, 
98345                         /*body*/ undefined);
98346                         var namespaceDeclaration = factory.updateModuleDeclaration(namespaceDecl, 
98347                         /*decorators*/ undefined, modifiers, namespaceDecl.name, namespaceDecl.body);
98348                         var exportDefaultDeclaration = factory.createExportAssignment(
98349                         /*decorators*/ undefined, 
98350                         /*modifiers*/ undefined, 
98351                         /*isExportEquals*/ false, namespaceDecl.name);
98352                         if (ts.isSourceFile(input.parent)) {
98353                             resultHasExternalModuleIndicator = true;
98354                         }
98355                         resultHasScopeMarker = true;
98356                         return [cleanDeclaration, namespaceDeclaration, exportDefaultDeclaration];
98357                     }
98358                     else {
98359                         return clean;
98360                     }
98361                 }
98362                 case 256 /* ModuleDeclaration */: {
98363                     needsDeclare = false;
98364                     var inner = input.body;
98365                     if (inner && inner.kind === 257 /* ModuleBlock */) {
98366                         var oldNeedsScopeFix = needsScopeFixMarker;
98367                         var oldHasScopeFix = resultHasScopeMarker;
98368                         resultHasScopeMarker = false;
98369                         needsScopeFixMarker = false;
98370                         var statements = ts.visitNodes(inner.statements, visitDeclarationStatements);
98371                         var lateStatements = transformAndReplaceLatePaintedStatements(statements);
98372                         if (input.flags & 8388608 /* Ambient */) {
98373                             needsScopeFixMarker = false; // If it was `declare`'d everything is implicitly exported already, ignore late printed "privates"
98374                         }
98375                         // With the final list of statements, there are 3 possibilities:
98376                         // 1. There's an export assignment or export declaration in the namespace - do nothing
98377                         // 2. Everything is exported and there are no export assignments or export declarations - strip all export modifiers
98378                         // 3. Some things are exported, some are not, and there's no marker - add an empty marker
98379                         if (!ts.isGlobalScopeAugmentation(input) && !hasScopeMarker(lateStatements) && !resultHasScopeMarker) {
98380                             if (needsScopeFixMarker) {
98381                                 lateStatements = factory.createNodeArray(__spreadArrays(lateStatements, [ts.createEmptyExports(factory)]));
98382                             }
98383                             else {
98384                                 lateStatements = ts.visitNodes(lateStatements, stripExportModifiers);
98385                             }
98386                         }
98387                         var body = factory.updateModuleBlock(inner, lateStatements);
98388                         needsDeclare = previousNeedsDeclare;
98389                         needsScopeFixMarker = oldNeedsScopeFix;
98390                         resultHasScopeMarker = oldHasScopeFix;
98391                         var mods = ensureModifiers(input);
98392                         return cleanup(factory.updateModuleDeclaration(input, 
98393                         /*decorators*/ undefined, mods, ts.isExternalModuleAugmentation(input) ? rewriteModuleSpecifier(input, input.name) : input.name, body));
98394                     }
98395                     else {
98396                         needsDeclare = previousNeedsDeclare;
98397                         var mods = ensureModifiers(input);
98398                         needsDeclare = false;
98399                         ts.visitNode(inner, visitDeclarationStatements);
98400                         // eagerly transform nested namespaces (the nesting doesn't need any elision or painting done)
98401                         var id = ts.getOriginalNodeId(inner); // TODO: GH#18217
98402                         var body = lateStatementReplacementMap.get(id);
98403                         lateStatementReplacementMap.delete(id);
98404                         return cleanup(factory.updateModuleDeclaration(input, 
98405                         /*decorators*/ undefined, mods, input.name, body));
98406                     }
98407                 }
98408                 case 252 /* ClassDeclaration */: {
98409                     var modifiers = factory.createNodeArray(ensureModifiers(input));
98410                     var typeParameters = ensureTypeParams(input, input.typeParameters);
98411                     var ctor = ts.getFirstConstructorWithBody(input);
98412                     var parameterProperties = void 0;
98413                     if (ctor) {
98414                         var oldDiag_1 = getSymbolAccessibilityDiagnostic;
98415                         parameterProperties = ts.compact(ts.flatMap(ctor.parameters, function (param) {
98416                             if (!ts.hasSyntacticModifier(param, 92 /* ParameterPropertyModifier */) || shouldStripInternal(param))
98417                                 return;
98418                             getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(param);
98419                             if (param.name.kind === 78 /* Identifier */) {
98420                                 return preserveJsDoc(factory.createPropertyDeclaration(
98421                                 /*decorators*/ undefined, ensureModifiers(param), param.name, param.questionToken, ensureType(param, param.type), ensureNoInitializer(param)), param);
98422                             }
98423                             else {
98424                                 // Pattern - this is currently an error, but we emit declarations for it somewhat correctly
98425                                 return walkBindingPattern(param.name);
98426                             }
98427                             function walkBindingPattern(pattern) {
98428                                 var elems;
98429                                 for (var _i = 0, _a = pattern.elements; _i < _a.length; _i++) {
98430                                     var elem = _a[_i];
98431                                     if (ts.isOmittedExpression(elem))
98432                                         continue;
98433                                     if (ts.isBindingPattern(elem.name)) {
98434                                         elems = ts.concatenate(elems, walkBindingPattern(elem.name));
98435                                     }
98436                                     elems = elems || [];
98437                                     elems.push(factory.createPropertyDeclaration(
98438                                     /*decorators*/ undefined, ensureModifiers(param), elem.name, 
98439                                     /*questionToken*/ undefined, ensureType(elem, /*type*/ undefined), 
98440                                     /*initializer*/ undefined));
98441                                 }
98442                                 return elems;
98443                             }
98444                         }));
98445                         getSymbolAccessibilityDiagnostic = oldDiag_1;
98446                     }
98447                     var hasPrivateIdentifier = ts.some(input.members, function (member) { return !!member.name && ts.isPrivateIdentifier(member.name); });
98448                     var privateIdentifier = hasPrivateIdentifier ? [
98449                         factory.createPropertyDeclaration(
98450                         /*decorators*/ undefined, 
98451                         /*modifiers*/ undefined, factory.createPrivateIdentifier("#private"), 
98452                         /*questionToken*/ undefined, 
98453                         /*type*/ undefined, 
98454                         /*initializer*/ undefined)
98455                     ] : undefined;
98456                     var memberNodes = ts.concatenate(ts.concatenate(privateIdentifier, parameterProperties), ts.visitNodes(input.members, visitDeclarationSubtree));
98457                     var members = factory.createNodeArray(memberNodes);
98458                     var extendsClause_1 = ts.getEffectiveBaseTypeNode(input);
98459                     if (extendsClause_1 && !ts.isEntityNameExpression(extendsClause_1.expression) && extendsClause_1.expression.kind !== 103 /* NullKeyword */) {
98460                         // We must add a temporary declaration for the extends clause expression
98461                         var oldId = input.name ? ts.unescapeLeadingUnderscores(input.name.escapedText) : "default";
98462                         var newId_1 = factory.createUniqueName(oldId + "_base", 16 /* Optimistic */);
98463                         getSymbolAccessibilityDiagnostic = function () { return ({
98464                             diagnosticMessage: ts.Diagnostics.extends_clause_of_exported_class_0_has_or_is_using_private_name_1,
98465                             errorNode: extendsClause_1,
98466                             typeName: input.name
98467                         }); };
98468                         var varDecl = factory.createVariableDeclaration(newId_1, /*exclamationToken*/ undefined, resolver.createTypeOfExpression(extendsClause_1.expression, input, declarationEmitNodeBuilderFlags, symbolTracker), /*initializer*/ undefined);
98469                         var statement = factory.createVariableStatement(needsDeclare ? [factory.createModifier(133 /* DeclareKeyword */)] : [], factory.createVariableDeclarationList([varDecl], 2 /* Const */));
98470                         var heritageClauses = factory.createNodeArray(ts.map(input.heritageClauses, function (clause) {
98471                             if (clause.token === 93 /* ExtendsKeyword */) {
98472                                 var oldDiag_2 = getSymbolAccessibilityDiagnostic;
98473                                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(clause.types[0]);
98474                                 var newClause = factory.updateHeritageClause(clause, ts.map(clause.types, function (t) { return factory.updateExpressionWithTypeArguments(t, newId_1, ts.visitNodes(t.typeArguments, visitDeclarationSubtree)); }));
98475                                 getSymbolAccessibilityDiagnostic = oldDiag_2;
98476                                 return newClause;
98477                             }
98478                             return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) { return ts.isEntityNameExpression(t.expression) || t.expression.kind === 103 /* NullKeyword */; })), visitDeclarationSubtree));
98479                         }));
98480                         return [statement, cleanup(factory.updateClassDeclaration(input, 
98481                             /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members))]; // TODO: GH#18217
98482                     }
98483                     else {
98484                         var heritageClauses = transformHeritageClauses(input.heritageClauses);
98485                         return cleanup(factory.updateClassDeclaration(input, 
98486                         /*decorators*/ undefined, modifiers, input.name, typeParameters, heritageClauses, members));
98487                     }
98488                 }
98489                 case 232 /* VariableStatement */: {
98490                     return cleanup(transformVariableStatement(input));
98491                 }
98492                 case 255 /* EnumDeclaration */: {
98493                     return cleanup(factory.updateEnumDeclaration(input, /*decorators*/ undefined, factory.createNodeArray(ensureModifiers(input)), input.name, factory.createNodeArray(ts.mapDefined(input.members, function (m) {
98494                         if (shouldStripInternal(m))
98495                             return;
98496                         // Rewrite enum values to their constants, if available
98497                         var constValue = resolver.getConstantValue(m);
98498                         return preserveJsDoc(factory.updateEnumMember(m, m.name, constValue !== undefined ? typeof constValue === "string" ? factory.createStringLiteral(constValue) : factory.createNumericLiteral(constValue) : undefined), m);
98499                     }))));
98500                 }
98501             }
98502             // Anything left unhandled is an error, so this should be unreachable
98503             return ts.Debug.assertNever(input, "Unhandled top-level node in declaration emit: " + ts.SyntaxKind[input.kind]);
98504             function cleanup(node) {
98505                 if (isEnclosingDeclaration(input)) {
98506                     enclosingDeclaration = previousEnclosingDeclaration;
98507                 }
98508                 if (canProdiceDiagnostic) {
98509                     getSymbolAccessibilityDiagnostic = oldDiag;
98510                 }
98511                 if (input.kind === 256 /* ModuleDeclaration */) {
98512                     needsDeclare = previousNeedsDeclare;
98513                 }
98514                 if (node === input) {
98515                     return node;
98516                 }
98517                 return node && ts.setOriginalNode(preserveJsDoc(node, input), input);
98518             }
98519         }
98520         function transformVariableStatement(input) {
98521             if (!ts.forEach(input.declarationList.declarations, getBindingNameVisible))
98522                 return;
98523             var nodes = ts.visitNodes(input.declarationList.declarations, visitDeclarationSubtree);
98524             if (!ts.length(nodes))
98525                 return;
98526             return factory.updateVariableStatement(input, factory.createNodeArray(ensureModifiers(input)), factory.updateVariableDeclarationList(input.declarationList, nodes));
98527         }
98528         function recreateBindingPattern(d) {
98529             return ts.flatten(ts.mapDefined(d.elements, function (e) { return recreateBindingElement(e); }));
98530         }
98531         function recreateBindingElement(e) {
98532             if (e.kind === 222 /* OmittedExpression */) {
98533                 return;
98534             }
98535             if (e.name) {
98536                 if (!getBindingNameVisible(e))
98537                     return;
98538                 if (ts.isBindingPattern(e.name)) {
98539                     return recreateBindingPattern(e.name);
98540                 }
98541                 else {
98542                     return factory.createVariableDeclaration(e.name, /*exclamationToken*/ undefined, ensureType(e, /*type*/ undefined), /*initializer*/ undefined);
98543                 }
98544             }
98545         }
98546         function checkName(node) {
98547             var oldDiag;
98548             if (!suppressNewDiagnosticContexts) {
98549                 oldDiag = getSymbolAccessibilityDiagnostic;
98550                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNodeName(node);
98551             }
98552             errorNameNode = node.name;
98553             ts.Debug.assert(resolver.isLateBound(ts.getParseTreeNode(node))); // Should only be called with dynamic names
98554             var decl = node;
98555             var entityName = decl.name.expression;
98556             checkEntityNameVisibility(entityName, enclosingDeclaration);
98557             if (!suppressNewDiagnosticContexts) {
98558                 getSymbolAccessibilityDiagnostic = oldDiag;
98559             }
98560             errorNameNode = undefined;
98561         }
98562         function shouldStripInternal(node) {
98563             return !!stripInternal && !!node && isInternalDeclaration(node, currentSourceFile);
98564         }
98565         function isScopeMarker(node) {
98566             return ts.isExportAssignment(node) || ts.isExportDeclaration(node);
98567         }
98568         function hasScopeMarker(statements) {
98569             return ts.some(statements, isScopeMarker);
98570         }
98571         function ensureModifiers(node) {
98572             var currentFlags = ts.getEffectiveModifierFlags(node);
98573             var newFlags = ensureModifierFlags(node);
98574             if (currentFlags === newFlags) {
98575                 return node.modifiers;
98576             }
98577             return factory.createModifiersFromModifierFlags(newFlags);
98578         }
98579         function ensureModifierFlags(node) {
98580             var mask = 11263 /* All */ ^ (4 /* Public */ | 256 /* Async */); // No async modifiers in declaration files
98581             var additions = (needsDeclare && !isAlwaysType(node)) ? 2 /* Ambient */ : 0 /* None */;
98582             var parentIsFile = node.parent.kind === 297 /* SourceFile */;
98583             if (!parentIsFile || (isBundledEmit && parentIsFile && ts.isExternalModule(node.parent))) {
98584                 mask ^= 2 /* Ambient */;
98585                 additions = 0 /* None */;
98586             }
98587             return maskModifierFlags(node, mask, additions);
98588         }
98589         function getTypeAnnotationFromAllAccessorDeclarations(node, accessors) {
98590             var accessorType = getTypeAnnotationFromAccessor(node);
98591             if (!accessorType && node !== accessors.firstAccessor) {
98592                 accessorType = getTypeAnnotationFromAccessor(accessors.firstAccessor);
98593                 // 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
98594                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.firstAccessor);
98595             }
98596             if (!accessorType && accessors.secondAccessor && node !== accessors.secondAccessor) {
98597                 accessorType = getTypeAnnotationFromAccessor(accessors.secondAccessor);
98598                 // 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
98599                 getSymbolAccessibilityDiagnostic = ts.createGetSymbolAccessibilityDiagnosticForNode(accessors.secondAccessor);
98600             }
98601             return accessorType;
98602         }
98603         function transformHeritageClauses(nodes) {
98604             return factory.createNodeArray(ts.filter(ts.map(nodes, function (clause) { return factory.updateHeritageClause(clause, ts.visitNodes(factory.createNodeArray(ts.filter(clause.types, function (t) {
98605                 return ts.isEntityNameExpression(t.expression) || (clause.token === 93 /* ExtendsKeyword */ && t.expression.kind === 103 /* NullKeyword */);
98606             })), visitDeclarationSubtree)); }), function (clause) { return clause.types && !!clause.types.length; }));
98607         }
98608     }
98609     ts.transformDeclarations = transformDeclarations;
98610     function isAlwaysType(node) {
98611         if (node.kind === 253 /* InterfaceDeclaration */) {
98612             return true;
98613         }
98614         return false;
98615     }
98616     // Elide "public" modifier, as it is the default
98617     function maskModifiers(node, modifierMask, modifierAdditions) {
98618         return ts.factory.createModifiersFromModifierFlags(maskModifierFlags(node, modifierMask, modifierAdditions));
98619     }
98620     function maskModifierFlags(node, modifierMask, modifierAdditions) {
98621         if (modifierMask === void 0) { modifierMask = 11263 /* All */ ^ 4 /* Public */; }
98622         if (modifierAdditions === void 0) { modifierAdditions = 0 /* None */; }
98623         var flags = (ts.getEffectiveModifierFlags(node) & modifierMask) | modifierAdditions;
98624         if (flags & 512 /* Default */ && !(flags & 1 /* Export */)) {
98625             // A non-exported default is a nonsequitor - we usually try to remove all export modifiers
98626             // from statements in ambient declarations; but a default export must retain its export modifier to be syntactically valid
98627             flags ^= 1 /* Export */;
98628         }
98629         if (flags & 512 /* Default */ && flags & 2 /* Ambient */) {
98630             flags ^= 2 /* Ambient */; // `declare` is never required alongside `default` (and would be an error if printed)
98631         }
98632         return flags;
98633     }
98634     function getTypeAnnotationFromAccessor(accessor) {
98635         if (accessor) {
98636             return accessor.kind === 167 /* GetAccessor */
98637                 ? accessor.type // Getter - return type
98638                 : accessor.parameters.length > 0
98639                     ? accessor.parameters[0].type // Setter parameter type
98640                     : undefined;
98641         }
98642     }
98643     function canHaveLiteralInitializer(node) {
98644         switch (node.kind) {
98645             case 163 /* PropertyDeclaration */:
98646             case 162 /* PropertySignature */:
98647                 return !ts.hasEffectiveModifier(node, 8 /* Private */);
98648             case 160 /* Parameter */:
98649             case 249 /* VariableDeclaration */:
98650                 return true;
98651         }
98652         return false;
98653     }
98654     function isPreservedDeclarationStatement(node) {
98655         switch (node.kind) {
98656             case 251 /* FunctionDeclaration */:
98657             case 256 /* ModuleDeclaration */:
98658             case 260 /* ImportEqualsDeclaration */:
98659             case 253 /* InterfaceDeclaration */:
98660             case 252 /* ClassDeclaration */:
98661             case 254 /* TypeAliasDeclaration */:
98662             case 255 /* EnumDeclaration */:
98663             case 232 /* VariableStatement */:
98664             case 261 /* ImportDeclaration */:
98665             case 267 /* ExportDeclaration */:
98666             case 266 /* ExportAssignment */:
98667                 return true;
98668         }
98669         return false;
98670     }
98671     function isProcessedComponent(node) {
98672         switch (node.kind) {
98673             case 170 /* ConstructSignature */:
98674             case 166 /* Constructor */:
98675             case 165 /* MethodDeclaration */:
98676             case 167 /* GetAccessor */:
98677             case 168 /* SetAccessor */:
98678             case 163 /* PropertyDeclaration */:
98679             case 162 /* PropertySignature */:
98680             case 164 /* MethodSignature */:
98681             case 169 /* CallSignature */:
98682             case 171 /* IndexSignature */:
98683             case 249 /* VariableDeclaration */:
98684             case 159 /* TypeParameter */:
98685             case 223 /* ExpressionWithTypeArguments */:
98686             case 173 /* TypeReference */:
98687             case 184 /* ConditionalType */:
98688             case 174 /* FunctionType */:
98689             case 175 /* ConstructorType */:
98690             case 195 /* ImportType */:
98691                 return true;
98692         }
98693         return false;
98694     }
98695 })(ts || (ts = {}));
98696 /* @internal */
98697 var ts;
98698 (function (ts) {
98699     function getModuleTransformer(moduleKind) {
98700         switch (moduleKind) {
98701             case ts.ModuleKind.ESNext:
98702             case ts.ModuleKind.ES2020:
98703             case ts.ModuleKind.ES2015:
98704                 return ts.transformECMAScriptModule;
98705             case ts.ModuleKind.System:
98706                 return ts.transformSystemModule;
98707             default:
98708                 return ts.transformModule;
98709         }
98710     }
98711     var TransformationState;
98712     (function (TransformationState) {
98713         TransformationState[TransformationState["Uninitialized"] = 0] = "Uninitialized";
98714         TransformationState[TransformationState["Initialized"] = 1] = "Initialized";
98715         TransformationState[TransformationState["Completed"] = 2] = "Completed";
98716         TransformationState[TransformationState["Disposed"] = 3] = "Disposed";
98717     })(TransformationState || (TransformationState = {}));
98718     var SyntaxKindFeatureFlags;
98719     (function (SyntaxKindFeatureFlags) {
98720         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["Substitution"] = 1] = "Substitution";
98721         SyntaxKindFeatureFlags[SyntaxKindFeatureFlags["EmitNotifications"] = 2] = "EmitNotifications";
98722     })(SyntaxKindFeatureFlags || (SyntaxKindFeatureFlags = {}));
98723     ts.noTransformers = { scriptTransformers: ts.emptyArray, declarationTransformers: ts.emptyArray };
98724     function getTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
98725         return {
98726             scriptTransformers: getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles),
98727             declarationTransformers: getDeclarationTransformers(customTransformers),
98728         };
98729     }
98730     ts.getTransformers = getTransformers;
98731     function getScriptTransformers(compilerOptions, customTransformers, emitOnlyDtsFiles) {
98732         if (emitOnlyDtsFiles)
98733             return ts.emptyArray;
98734         var languageVersion = ts.getEmitScriptTarget(compilerOptions);
98735         var moduleKind = ts.getEmitModuleKind(compilerOptions);
98736         var transformers = [];
98737         ts.addRange(transformers, customTransformers && ts.map(customTransformers.before, wrapScriptTransformerFactory));
98738         transformers.push(ts.transformTypeScript);
98739         transformers.push(ts.transformClassFields);
98740         if (ts.getJSXTransformEnabled(compilerOptions)) {
98741             transformers.push(ts.transformJsx);
98742         }
98743         if (languageVersion < 99 /* ESNext */) {
98744             transformers.push(ts.transformESNext);
98745         }
98746         if (languageVersion < 7 /* ES2020 */) {
98747             transformers.push(ts.transformES2020);
98748         }
98749         if (languageVersion < 6 /* ES2019 */) {
98750             transformers.push(ts.transformES2019);
98751         }
98752         if (languageVersion < 5 /* ES2018 */) {
98753             transformers.push(ts.transformES2018);
98754         }
98755         if (languageVersion < 4 /* ES2017 */) {
98756             transformers.push(ts.transformES2017);
98757         }
98758         if (languageVersion < 3 /* ES2016 */) {
98759             transformers.push(ts.transformES2016);
98760         }
98761         if (languageVersion < 2 /* ES2015 */) {
98762             transformers.push(ts.transformES2015);
98763             transformers.push(ts.transformGenerators);
98764         }
98765         transformers.push(getModuleTransformer(moduleKind));
98766         // The ES5 transformer is last so that it can substitute expressions like `exports.default`
98767         // for ES3.
98768         if (languageVersion < 1 /* ES5 */) {
98769             transformers.push(ts.transformES5);
98770         }
98771         ts.addRange(transformers, customTransformers && ts.map(customTransformers.after, wrapScriptTransformerFactory));
98772         return transformers;
98773     }
98774     function getDeclarationTransformers(customTransformers) {
98775         var transformers = [];
98776         transformers.push(ts.transformDeclarations);
98777         ts.addRange(transformers, customTransformers && ts.map(customTransformers.afterDeclarations, wrapDeclarationTransformerFactory));
98778         return transformers;
98779     }
98780     /**
98781      * Wrap a custom script or declaration transformer object in a `Transformer` callback with fallback support for transforming bundles.
98782      */
98783     function wrapCustomTransformer(transformer) {
98784         return function (node) { return ts.isBundle(node) ? transformer.transformBundle(node) : transformer.transformSourceFile(node); };
98785     }
98786     /**
98787      * Wrap a transformer factory that may return a custom script or declaration transformer object.
98788      */
98789     function wrapCustomTransformerFactory(transformer, handleDefault) {
98790         return function (context) {
98791             var customTransformer = transformer(context);
98792             return typeof customTransformer === "function"
98793                 ? handleDefault(context, customTransformer)
98794                 : wrapCustomTransformer(customTransformer);
98795         };
98796     }
98797     function wrapScriptTransformerFactory(transformer) {
98798         return wrapCustomTransformerFactory(transformer, ts.chainBundle);
98799     }
98800     function wrapDeclarationTransformerFactory(transformer) {
98801         return wrapCustomTransformerFactory(transformer, function (_, node) { return node; });
98802     }
98803     function noEmitSubstitution(_hint, node) {
98804         return node;
98805     }
98806     ts.noEmitSubstitution = noEmitSubstitution;
98807     function noEmitNotification(hint, node, callback) {
98808         callback(hint, node);
98809     }
98810     ts.noEmitNotification = noEmitNotification;
98811     /**
98812      * Transforms an array of SourceFiles by passing them through each transformer.
98813      *
98814      * @param resolver The emit resolver provided by the checker.
98815      * @param host The emit host object used to interact with the file system.
98816      * @param options Compiler options to surface in the `TransformationContext`.
98817      * @param nodes An array of nodes to transform.
98818      * @param transforms An array of `TransformerFactory` callbacks.
98819      * @param allowDtsFiles A value indicating whether to allow the transformation of .d.ts files.
98820      */
98821     function transformNodes(resolver, host, factory, options, nodes, transformers, allowDtsFiles) {
98822         var enabledSyntaxKindFeatures = new Array(341 /* Count */);
98823         var lexicalEnvironmentVariableDeclarations;
98824         var lexicalEnvironmentFunctionDeclarations;
98825         var lexicalEnvironmentStatements;
98826         var lexicalEnvironmentFlags = 0 /* None */;
98827         var lexicalEnvironmentVariableDeclarationsStack = [];
98828         var lexicalEnvironmentFunctionDeclarationsStack = [];
98829         var lexicalEnvironmentStatementsStack = [];
98830         var lexicalEnvironmentFlagsStack = [];
98831         var lexicalEnvironmentStackOffset = 0;
98832         var lexicalEnvironmentSuspended = false;
98833         var emitHelpers;
98834         var onSubstituteNode = noEmitSubstitution;
98835         var onEmitNode = noEmitNotification;
98836         var state = 0 /* Uninitialized */;
98837         var diagnostics = [];
98838         // The transformation context is provided to each transformer as part of transformer
98839         // initialization.
98840         var context = {
98841             factory: factory,
98842             getCompilerOptions: function () { return options; },
98843             getEmitResolver: function () { return resolver; },
98844             getEmitHost: function () { return host; },
98845             getEmitHelperFactory: ts.memoize(function () { return ts.createEmitHelperFactory(context); }),
98846             startLexicalEnvironment: startLexicalEnvironment,
98847             suspendLexicalEnvironment: suspendLexicalEnvironment,
98848             resumeLexicalEnvironment: resumeLexicalEnvironment,
98849             endLexicalEnvironment: endLexicalEnvironment,
98850             setLexicalEnvironmentFlags: setLexicalEnvironmentFlags,
98851             getLexicalEnvironmentFlags: getLexicalEnvironmentFlags,
98852             hoistVariableDeclaration: hoistVariableDeclaration,
98853             hoistFunctionDeclaration: hoistFunctionDeclaration,
98854             addInitializationStatement: addInitializationStatement,
98855             requestEmitHelper: requestEmitHelper,
98856             readEmitHelpers: readEmitHelpers,
98857             enableSubstitution: enableSubstitution,
98858             enableEmitNotification: enableEmitNotification,
98859             isSubstitutionEnabled: isSubstitutionEnabled,
98860             isEmitNotificationEnabled: isEmitNotificationEnabled,
98861             get onSubstituteNode() { return onSubstituteNode; },
98862             set onSubstituteNode(value) {
98863                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
98864                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
98865                 onSubstituteNode = value;
98866             },
98867             get onEmitNode() { return onEmitNode; },
98868             set onEmitNode(value) {
98869                 ts.Debug.assert(state < 1 /* Initialized */, "Cannot modify transformation hooks after initialization has completed.");
98870                 ts.Debug.assert(value !== undefined, "Value must not be 'undefined'");
98871                 onEmitNode = value;
98872             },
98873             addDiagnostic: function (diag) {
98874                 diagnostics.push(diag);
98875             }
98876         };
98877         // Ensure the parse tree is clean before applying transformations
98878         for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
98879             var node = nodes_2[_i];
98880             ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
98881         }
98882         ts.performance.mark("beforeTransform");
98883         // Chain together and initialize each transformer.
98884         var transformersWithContext = transformers.map(function (t) { return t(context); });
98885         var transformation = function (node) {
98886             for (var _i = 0, transformersWithContext_1 = transformersWithContext; _i < transformersWithContext_1.length; _i++) {
98887                 var transform = transformersWithContext_1[_i];
98888                 node = transform(node);
98889             }
98890             return node;
98891         };
98892         // prevent modification of transformation hooks.
98893         state = 1 /* Initialized */;
98894         // Transform each node.
98895         var transformed = [];
98896         for (var _a = 0, nodes_3 = nodes; _a < nodes_3.length; _a++) {
98897             var node = nodes_3[_a];
98898             ts.tracing.push("emit" /* Emit */, "transformNodes", node.kind === 297 /* SourceFile */ ? { path: node.path } : { kind: node.kind, pos: node.pos, end: node.end });
98899             transformed.push((allowDtsFiles ? transformation : transformRoot)(node));
98900             ts.tracing.pop();
98901         }
98902         // prevent modification of the lexical environment.
98903         state = 2 /* Completed */;
98904         ts.performance.mark("afterTransform");
98905         ts.performance.measure("transformTime", "beforeTransform", "afterTransform");
98906         return {
98907             transformed: transformed,
98908             substituteNode: substituteNode,
98909             emitNodeWithNotification: emitNodeWithNotification,
98910             isEmitNotificationEnabled: isEmitNotificationEnabled,
98911             dispose: dispose,
98912             diagnostics: diagnostics
98913         };
98914         function transformRoot(node) {
98915             return node && (!ts.isSourceFile(node) || !node.isDeclarationFile) ? transformation(node) : node;
98916         }
98917         /**
98918          * Enables expression substitutions in the pretty printer for the provided SyntaxKind.
98919          */
98920         function enableSubstitution(kind) {
98921             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
98922             enabledSyntaxKindFeatures[kind] |= 1 /* Substitution */;
98923         }
98924         /**
98925          * Determines whether expression substitutions are enabled for the provided node.
98926          */
98927         function isSubstitutionEnabled(node) {
98928             return (enabledSyntaxKindFeatures[node.kind] & 1 /* Substitution */) !== 0
98929                 && (ts.getEmitFlags(node) & 4 /* NoSubstitution */) === 0;
98930         }
98931         /**
98932          * Emits a node with possible substitution.
98933          *
98934          * @param hint A hint as to the intended usage of the node.
98935          * @param node The node to emit.
98936          * @param emitCallback The callback used to emit the node or its substitute.
98937          */
98938         function substituteNode(hint, node) {
98939             ts.Debug.assert(state < 3 /* Disposed */, "Cannot substitute a node after the result is disposed.");
98940             return node && isSubstitutionEnabled(node) && onSubstituteNode(hint, node) || node;
98941         }
98942         /**
98943          * Enables before/after emit notifications in the pretty printer for the provided SyntaxKind.
98944          */
98945         function enableEmitNotification(kind) {
98946             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
98947             enabledSyntaxKindFeatures[kind] |= 2 /* EmitNotifications */;
98948         }
98949         /**
98950          * Determines whether before/after emit notifications should be raised in the pretty
98951          * printer when it emits a node.
98952          */
98953         function isEmitNotificationEnabled(node) {
98954             return (enabledSyntaxKindFeatures[node.kind] & 2 /* EmitNotifications */) !== 0
98955                 || (ts.getEmitFlags(node) & 2 /* AdviseOnEmitNode */) !== 0;
98956         }
98957         /**
98958          * Emits a node with possible emit notification.
98959          *
98960          * @param hint A hint as to the intended usage of the node.
98961          * @param node The node to emit.
98962          * @param emitCallback The callback used to emit the node.
98963          */
98964         function emitNodeWithNotification(hint, node, emitCallback) {
98965             ts.Debug.assert(state < 3 /* Disposed */, "Cannot invoke TransformationResult callbacks after the result is disposed.");
98966             if (node) {
98967                 // TODO: Remove check and unconditionally use onEmitNode when API is breakingly changed
98968                 // (see https://github.com/microsoft/TypeScript/pull/36248/files/5062623f39120171b98870c71344b3242eb03d23#r369766739)
98969                 if (isEmitNotificationEnabled(node)) {
98970                     onEmitNode(hint, node, emitCallback);
98971                 }
98972                 else {
98973                     emitCallback(hint, node);
98974                 }
98975             }
98976         }
98977         /**
98978          * Records a hoisted variable declaration for the provided name within a lexical environment.
98979          */
98980         function hoistVariableDeclaration(name) {
98981             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
98982             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
98983             var decl = ts.setEmitFlags(factory.createVariableDeclaration(name), 64 /* NoNestedSourceMaps */);
98984             if (!lexicalEnvironmentVariableDeclarations) {
98985                 lexicalEnvironmentVariableDeclarations = [decl];
98986             }
98987             else {
98988                 lexicalEnvironmentVariableDeclarations.push(decl);
98989             }
98990             if (lexicalEnvironmentFlags & 1 /* InParameters */) {
98991                 lexicalEnvironmentFlags |= 2 /* VariablesHoistedInParameters */;
98992             }
98993         }
98994         /**
98995          * Records a hoisted function declaration within a lexical environment.
98996          */
98997         function hoistFunctionDeclaration(func) {
98998             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
98999             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99000             ts.setEmitFlags(func, 1048576 /* CustomPrologue */);
99001             if (!lexicalEnvironmentFunctionDeclarations) {
99002                 lexicalEnvironmentFunctionDeclarations = [func];
99003             }
99004             else {
99005                 lexicalEnvironmentFunctionDeclarations.push(func);
99006             }
99007         }
99008         /**
99009          * Adds an initialization statement to the top of the lexical environment.
99010          */
99011         function addInitializationStatement(node) {
99012             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99013             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99014             ts.setEmitFlags(node, 1048576 /* CustomPrologue */);
99015             if (!lexicalEnvironmentStatements) {
99016                 lexicalEnvironmentStatements = [node];
99017             }
99018             else {
99019                 lexicalEnvironmentStatements.push(node);
99020             }
99021         }
99022         /**
99023          * Starts a new lexical environment. Any existing hoisted variable or function declarations
99024          * are pushed onto a stack, and the related storage variables are reset.
99025          */
99026         function startLexicalEnvironment() {
99027             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99028             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99029             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
99030             // Save the current lexical environment. Rather than resizing the array we adjust the
99031             // stack size variable. This allows us to reuse existing array slots we've
99032             // already allocated between transformations to avoid allocation and GC overhead during
99033             // transformation.
99034             lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentVariableDeclarations;
99035             lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFunctionDeclarations;
99036             lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentStatements;
99037             lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset] = lexicalEnvironmentFlags;
99038             lexicalEnvironmentStackOffset++;
99039             lexicalEnvironmentVariableDeclarations = undefined;
99040             lexicalEnvironmentFunctionDeclarations = undefined;
99041             lexicalEnvironmentStatements = undefined;
99042             lexicalEnvironmentFlags = 0 /* None */;
99043         }
99044         /** Suspends the current lexical environment, usually after visiting a parameter list. */
99045         function suspendLexicalEnvironment() {
99046             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99047             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99048             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is already suspended.");
99049             lexicalEnvironmentSuspended = true;
99050         }
99051         /** Resumes a suspended lexical environment, usually before visiting a function body. */
99052         function resumeLexicalEnvironment() {
99053             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99054             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99055             ts.Debug.assert(lexicalEnvironmentSuspended, "Lexical environment is not suspended.");
99056             lexicalEnvironmentSuspended = false;
99057         }
99058         /**
99059          * Ends a lexical environment. The previous set of hoisted declarations are restored and
99060          * any hoisted declarations added in this environment are returned.
99061          */
99062         function endLexicalEnvironment() {
99063             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the lexical environment during initialization.");
99064             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the lexical environment after transformation has completed.");
99065             ts.Debug.assert(!lexicalEnvironmentSuspended, "Lexical environment is suspended.");
99066             var statements;
99067             if (lexicalEnvironmentVariableDeclarations ||
99068                 lexicalEnvironmentFunctionDeclarations ||
99069                 lexicalEnvironmentStatements) {
99070                 if (lexicalEnvironmentFunctionDeclarations) {
99071                     statements = __spreadArrays(lexicalEnvironmentFunctionDeclarations);
99072                 }
99073                 if (lexicalEnvironmentVariableDeclarations) {
99074                     var statement = factory.createVariableStatement(
99075                     /*modifiers*/ undefined, factory.createVariableDeclarationList(lexicalEnvironmentVariableDeclarations));
99076                     ts.setEmitFlags(statement, 1048576 /* CustomPrologue */);
99077                     if (!statements) {
99078                         statements = [statement];
99079                     }
99080                     else {
99081                         statements.push(statement);
99082                     }
99083                 }
99084                 if (lexicalEnvironmentStatements) {
99085                     if (!statements) {
99086                         statements = __spreadArrays(lexicalEnvironmentStatements);
99087                     }
99088                     else {
99089                         statements = __spreadArrays(statements, lexicalEnvironmentStatements);
99090                     }
99091                 }
99092             }
99093             // Restore the previous lexical environment.
99094             lexicalEnvironmentStackOffset--;
99095             lexicalEnvironmentVariableDeclarations = lexicalEnvironmentVariableDeclarationsStack[lexicalEnvironmentStackOffset];
99096             lexicalEnvironmentFunctionDeclarations = lexicalEnvironmentFunctionDeclarationsStack[lexicalEnvironmentStackOffset];
99097             lexicalEnvironmentStatements = lexicalEnvironmentStatementsStack[lexicalEnvironmentStackOffset];
99098             lexicalEnvironmentFlags = lexicalEnvironmentFlagsStack[lexicalEnvironmentStackOffset];
99099             if (lexicalEnvironmentStackOffset === 0) {
99100                 lexicalEnvironmentVariableDeclarationsStack = [];
99101                 lexicalEnvironmentFunctionDeclarationsStack = [];
99102                 lexicalEnvironmentStatementsStack = [];
99103                 lexicalEnvironmentFlagsStack = [];
99104             }
99105             return statements;
99106         }
99107         function setLexicalEnvironmentFlags(flags, value) {
99108             lexicalEnvironmentFlags = value ?
99109                 lexicalEnvironmentFlags | flags :
99110                 lexicalEnvironmentFlags & ~flags;
99111         }
99112         function getLexicalEnvironmentFlags() {
99113             return lexicalEnvironmentFlags;
99114         }
99115         function requestEmitHelper(helper) {
99116             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
99117             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
99118             ts.Debug.assert(!helper.scoped, "Cannot request a scoped emit helper.");
99119             if (helper.dependencies) {
99120                 for (var _i = 0, _a = helper.dependencies; _i < _a.length; _i++) {
99121                     var h = _a[_i];
99122                     requestEmitHelper(h);
99123                 }
99124             }
99125             emitHelpers = ts.append(emitHelpers, helper);
99126         }
99127         function readEmitHelpers() {
99128             ts.Debug.assert(state > 0 /* Uninitialized */, "Cannot modify the transformation context during initialization.");
99129             ts.Debug.assert(state < 2 /* Completed */, "Cannot modify the transformation context after transformation has completed.");
99130             var helpers = emitHelpers;
99131             emitHelpers = undefined;
99132             return helpers;
99133         }
99134         function dispose() {
99135             if (state < 3 /* Disposed */) {
99136                 // Clean up emit nodes on parse tree
99137                 for (var _i = 0, nodes_4 = nodes; _i < nodes_4.length; _i++) {
99138                     var node = nodes_4[_i];
99139                     ts.disposeEmitNodes(ts.getSourceFileOfNode(ts.getParseTreeNode(node)));
99140                 }
99141                 // Release references to external entries for GC purposes.
99142                 lexicalEnvironmentVariableDeclarations = undefined;
99143                 lexicalEnvironmentVariableDeclarationsStack = undefined;
99144                 lexicalEnvironmentFunctionDeclarations = undefined;
99145                 lexicalEnvironmentFunctionDeclarationsStack = undefined;
99146                 onSubstituteNode = undefined;
99147                 onEmitNode = undefined;
99148                 emitHelpers = undefined;
99149                 // Prevent further use of the transformation result.
99150                 state = 3 /* Disposed */;
99151             }
99152         }
99153     }
99154     ts.transformNodes = transformNodes;
99155     ts.nullTransformationContext = {
99156         get factory() { return ts.factory; },
99157         enableEmitNotification: ts.noop,
99158         enableSubstitution: ts.noop,
99159         endLexicalEnvironment: ts.returnUndefined,
99160         getCompilerOptions: function () { return ({}); },
99161         getEmitHost: ts.notImplemented,
99162         getEmitResolver: ts.notImplemented,
99163         getEmitHelperFactory: ts.notImplemented,
99164         setLexicalEnvironmentFlags: ts.noop,
99165         getLexicalEnvironmentFlags: function () { return 0; },
99166         hoistFunctionDeclaration: ts.noop,
99167         hoistVariableDeclaration: ts.noop,
99168         addInitializationStatement: ts.noop,
99169         isEmitNotificationEnabled: ts.notImplemented,
99170         isSubstitutionEnabled: ts.notImplemented,
99171         onEmitNode: ts.noop,
99172         onSubstituteNode: ts.notImplemented,
99173         readEmitHelpers: ts.notImplemented,
99174         requestEmitHelper: ts.noop,
99175         resumeLexicalEnvironment: ts.noop,
99176         startLexicalEnvironment: ts.noop,
99177         suspendLexicalEnvironment: ts.noop,
99178         addDiagnostic: ts.noop,
99179     };
99180 })(ts || (ts = {}));
99181 var ts;
99182 (function (ts) {
99183     var brackets = createBracketsMap();
99184     var syntheticParent = { pos: -1, end: -1 };
99185     /*@internal*/
99186     function isBuildInfoFile(file) {
99187         return ts.fileExtensionIs(file, ".tsbuildinfo" /* TsBuildInfo */);
99188     }
99189     ts.isBuildInfoFile = isBuildInfoFile;
99190     /*@internal*/
99191     /**
99192      * Iterates over the source files that are expected to have an emit output.
99193      *
99194      * @param host An EmitHost.
99195      * @param action The action to execute.
99196      * @param sourceFilesOrTargetSourceFile
99197      *   If an array, the full list of source files to emit.
99198      *   Else, calls `getSourceFilesToEmit` with the (optional) target source file to determine the list of source files to emit.
99199      */
99200     function forEachEmittedFile(host, action, sourceFilesOrTargetSourceFile, forceDtsEmit, onlyBuildInfo, includeBuildInfo) {
99201         if (forceDtsEmit === void 0) { forceDtsEmit = false; }
99202         var sourceFiles = ts.isArray(sourceFilesOrTargetSourceFile) ? sourceFilesOrTargetSourceFile : ts.getSourceFilesToEmit(host, sourceFilesOrTargetSourceFile, forceDtsEmit);
99203         var options = host.getCompilerOptions();
99204         if (ts.outFile(options)) {
99205             var prepends = host.getPrependNodes();
99206             if (sourceFiles.length || prepends.length) {
99207                 var bundle = ts.factory.createBundle(sourceFiles, prepends);
99208                 var result = action(getOutputPathsFor(bundle, host, forceDtsEmit), bundle);
99209                 if (result) {
99210                     return result;
99211                 }
99212             }
99213         }
99214         else {
99215             if (!onlyBuildInfo) {
99216                 for (var _a = 0, sourceFiles_1 = sourceFiles; _a < sourceFiles_1.length; _a++) {
99217                     var sourceFile = sourceFiles_1[_a];
99218                     var result = action(getOutputPathsFor(sourceFile, host, forceDtsEmit), sourceFile);
99219                     if (result) {
99220                         return result;
99221                     }
99222                 }
99223             }
99224             if (includeBuildInfo) {
99225                 var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
99226                 if (buildInfoPath)
99227                     return action({ buildInfoPath: buildInfoPath }, /*sourceFileOrBundle*/ undefined);
99228             }
99229         }
99230     }
99231     ts.forEachEmittedFile = forEachEmittedFile;
99232     function getTsBuildInfoEmitOutputFilePath(options) {
99233         var configFile = options.configFilePath;
99234         if (!ts.isIncrementalCompilation(options))
99235             return undefined;
99236         if (options.tsBuildInfoFile)
99237             return options.tsBuildInfoFile;
99238         var outPath = ts.outFile(options);
99239         var buildInfoExtensionLess;
99240         if (outPath) {
99241             buildInfoExtensionLess = ts.removeFileExtension(outPath);
99242         }
99243         else {
99244             if (!configFile)
99245                 return undefined;
99246             var configFileExtensionLess = ts.removeFileExtension(configFile);
99247             buildInfoExtensionLess = options.outDir ?
99248                 options.rootDir ?
99249                     ts.resolvePath(options.outDir, ts.getRelativePathFromDirectory(options.rootDir, configFileExtensionLess, /*ignoreCase*/ true)) :
99250                     ts.combinePaths(options.outDir, ts.getBaseFileName(configFileExtensionLess)) :
99251                 configFileExtensionLess;
99252         }
99253         return buildInfoExtensionLess + ".tsbuildinfo" /* TsBuildInfo */;
99254     }
99255     ts.getTsBuildInfoEmitOutputFilePath = getTsBuildInfoEmitOutputFilePath;
99256     /*@internal*/
99257     function getOutputPathsForBundle(options, forceDtsPaths) {
99258         var outPath = ts.outFile(options);
99259         var jsFilePath = options.emitDeclarationOnly ? undefined : outPath;
99260         var sourceMapFilePath = jsFilePath && getSourceMapFilePath(jsFilePath, options);
99261         var declarationFilePath = (forceDtsPaths || ts.getEmitDeclarations(options)) ? ts.removeFileExtension(outPath) + ".d.ts" /* Dts */ : undefined;
99262         var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
99263         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(options);
99264         return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: buildInfoPath };
99265     }
99266     ts.getOutputPathsForBundle = getOutputPathsForBundle;
99267     /*@internal*/
99268     function getOutputPathsFor(sourceFile, host, forceDtsPaths) {
99269         var options = host.getCompilerOptions();
99270         if (sourceFile.kind === 298 /* Bundle */) {
99271             return getOutputPathsForBundle(options, forceDtsPaths);
99272         }
99273         else {
99274             var ownOutputFilePath = ts.getOwnEmitOutputFilePath(sourceFile.fileName, host, getOutputExtension(sourceFile, options));
99275             var isJsonFile = ts.isJsonSourceFile(sourceFile);
99276             // If json file emits to the same location skip writing it, if emitDeclarationOnly skip writing it
99277             var isJsonEmittedToSameLocation = isJsonFile &&
99278                 ts.comparePaths(sourceFile.fileName, ownOutputFilePath, host.getCurrentDirectory(), !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
99279             var jsFilePath = options.emitDeclarationOnly || isJsonEmittedToSameLocation ? undefined : ownOutputFilePath;
99280             var sourceMapFilePath = !jsFilePath || ts.isJsonSourceFile(sourceFile) ? undefined : getSourceMapFilePath(jsFilePath, options);
99281             var declarationFilePath = (forceDtsPaths || (ts.getEmitDeclarations(options) && !isJsonFile)) ? ts.getDeclarationEmitOutputFilePath(sourceFile.fileName, host) : undefined;
99282             var declarationMapPath = declarationFilePath && ts.getAreDeclarationMapsEnabled(options) ? declarationFilePath + ".map" : undefined;
99283             return { jsFilePath: jsFilePath, sourceMapFilePath: sourceMapFilePath, declarationFilePath: declarationFilePath, declarationMapPath: declarationMapPath, buildInfoPath: undefined };
99284         }
99285     }
99286     ts.getOutputPathsFor = getOutputPathsFor;
99287     function getSourceMapFilePath(jsFilePath, options) {
99288         return (options.sourceMap && !options.inlineSourceMap) ? jsFilePath + ".map" : undefined;
99289     }
99290     // JavaScript files are always LanguageVariant.JSX, as JSX syntax is allowed in .js files also.
99291     // So for JavaScript files, '.jsx' is only emitted if the input was '.jsx', and JsxEmit.Preserve.
99292     // For TypeScript, the only time to emit with a '.jsx' extension, is on JSX input, and JsxEmit.Preserve
99293     /* @internal */
99294     function getOutputExtension(sourceFile, options) {
99295         if (ts.isJsonSourceFile(sourceFile)) {
99296             return ".json" /* Json */;
99297         }
99298         if (options.jsx === 1 /* Preserve */) {
99299             if (ts.isSourceFileJS(sourceFile)) {
99300                 if (ts.fileExtensionIs(sourceFile.fileName, ".jsx" /* Jsx */)) {
99301                     return ".jsx" /* Jsx */;
99302                 }
99303             }
99304             else if (sourceFile.languageVariant === 1 /* JSX */) {
99305                 // TypeScript source file preserving JSX syntax
99306                 return ".jsx" /* Jsx */;
99307             }
99308         }
99309         return ".js" /* Js */;
99310     }
99311     ts.getOutputExtension = getOutputExtension;
99312     function rootDirOfOptions(configFile) {
99313         return configFile.options.rootDir || ts.getDirectoryPath(ts.Debug.checkDefined(configFile.options.configFilePath));
99314     }
99315     function getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, outputDir) {
99316         return outputDir ?
99317             ts.resolvePath(outputDir, ts.getRelativePathFromDirectory(rootDirOfOptions(configFile), inputFileName, ignoreCase)) :
99318             inputFileName;
99319     }
99320     /* @internal */
99321     function getOutputDeclarationFileName(inputFileName, configFile, ignoreCase) {
99322         ts.Debug.assert(!ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(inputFileName, ".json" /* Json */));
99323         return ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.declarationDir || configFile.options.outDir), ".d.ts" /* Dts */);
99324     }
99325     ts.getOutputDeclarationFileName = getOutputDeclarationFileName;
99326     function getOutputJSFileName(inputFileName, configFile, ignoreCase) {
99327         if (configFile.options.emitDeclarationOnly)
99328             return undefined;
99329         var isJsonFile = ts.fileExtensionIs(inputFileName, ".json" /* Json */);
99330         var outputFileName = ts.changeExtension(getOutputPathWithoutChangingExt(inputFileName, configFile, ignoreCase, configFile.options.outDir), isJsonFile ?
99331             ".json" /* Json */ :
99332             ts.fileExtensionIs(inputFileName, ".tsx" /* Tsx */) && configFile.options.jsx === 1 /* Preserve */ ?
99333                 ".jsx" /* Jsx */ :
99334                 ".js" /* Js */);
99335         return !isJsonFile || ts.comparePaths(inputFileName, outputFileName, ts.Debug.checkDefined(configFile.options.configFilePath), ignoreCase) !== 0 /* EqualTo */ ?
99336             outputFileName :
99337             undefined;
99338     }
99339     function createAddOutput() {
99340         var outputs;
99341         return { addOutput: addOutput, getOutputs: getOutputs };
99342         function addOutput(path) {
99343             if (path) {
99344                 (outputs || (outputs = [])).push(path);
99345             }
99346         }
99347         function getOutputs() {
99348             return outputs || ts.emptyArray;
99349         }
99350     }
99351     function getSingleOutputFileNames(configFile, addOutput) {
99352         var _a = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
99353         addOutput(jsFilePath);
99354         addOutput(sourceMapFilePath);
99355         addOutput(declarationFilePath);
99356         addOutput(declarationMapPath);
99357         addOutput(buildInfoPath);
99358     }
99359     function getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput) {
99360         if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
99361             return;
99362         var js = getOutputJSFileName(inputFileName, configFile, ignoreCase);
99363         addOutput(js);
99364         if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
99365             return;
99366         if (js && configFile.options.sourceMap) {
99367             addOutput(js + ".map");
99368         }
99369         if (ts.getEmitDeclarations(configFile.options)) {
99370             var dts = getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
99371             addOutput(dts);
99372             if (configFile.options.declarationMap) {
99373                 addOutput(dts + ".map");
99374             }
99375         }
99376     }
99377     /*@internal*/
99378     function getAllProjectOutputs(configFile, ignoreCase) {
99379         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
99380         if (ts.outFile(configFile.options)) {
99381             getSingleOutputFileNames(configFile, addOutput);
99382         }
99383         else {
99384             for (var _b = 0, _c = configFile.fileNames; _b < _c.length; _b++) {
99385                 var inputFileName = _c[_b];
99386                 getOwnOutputFileNames(configFile, inputFileName, ignoreCase, addOutput);
99387             }
99388             addOutput(getTsBuildInfoEmitOutputFilePath(configFile.options));
99389         }
99390         return getOutputs();
99391     }
99392     ts.getAllProjectOutputs = getAllProjectOutputs;
99393     function getOutputFileNames(commandLine, inputFileName, ignoreCase) {
99394         inputFileName = ts.normalizePath(inputFileName);
99395         ts.Debug.assert(ts.contains(commandLine.fileNames, inputFileName), "Expected fileName to be present in command line");
99396         var _a = createAddOutput(), addOutput = _a.addOutput, getOutputs = _a.getOutputs;
99397         if (ts.outFile(commandLine.options)) {
99398             getSingleOutputFileNames(commandLine, addOutput);
99399         }
99400         else {
99401             getOwnOutputFileNames(commandLine, inputFileName, ignoreCase, addOutput);
99402         }
99403         return getOutputs();
99404     }
99405     ts.getOutputFileNames = getOutputFileNames;
99406     /*@internal*/
99407     function getFirstProjectOutput(configFile, ignoreCase) {
99408         if (ts.outFile(configFile.options)) {
99409             var jsFilePath = getOutputPathsForBundle(configFile.options, /*forceDtsPaths*/ false).jsFilePath;
99410             return ts.Debug.checkDefined(jsFilePath, "project " + configFile.options.configFilePath + " expected to have at least one output");
99411         }
99412         for (var _a = 0, _b = configFile.fileNames; _a < _b.length; _a++) {
99413             var inputFileName = _b[_a];
99414             if (ts.fileExtensionIs(inputFileName, ".d.ts" /* Dts */))
99415                 continue;
99416             var jsFilePath = getOutputJSFileName(inputFileName, configFile, ignoreCase);
99417             if (jsFilePath)
99418                 return jsFilePath;
99419             if (ts.fileExtensionIs(inputFileName, ".json" /* Json */))
99420                 continue;
99421             if (ts.getEmitDeclarations(configFile.options)) {
99422                 return getOutputDeclarationFileName(inputFileName, configFile, ignoreCase);
99423             }
99424         }
99425         var buildInfoPath = getTsBuildInfoEmitOutputFilePath(configFile.options);
99426         if (buildInfoPath)
99427             return buildInfoPath;
99428         return ts.Debug.fail("project " + configFile.options.configFilePath + " expected to have at least one output");
99429     }
99430     ts.getFirstProjectOutput = getFirstProjectOutput;
99431     /*@internal*/
99432     // targetSourceFile is when users only want one file in entire project to be emitted. This is used in compileOnSave feature
99433     function emitFiles(resolver, host, targetSourceFile, _a, emitOnlyDtsFiles, onlyBuildInfo, forceDtsEmit) {
99434         var scriptTransformers = _a.scriptTransformers, declarationTransformers = _a.declarationTransformers;
99435         var compilerOptions = host.getCompilerOptions();
99436         var sourceMapDataList = (compilerOptions.sourceMap || compilerOptions.inlineSourceMap || ts.getAreDeclarationMapsEnabled(compilerOptions)) ? [] : undefined;
99437         var emittedFilesList = compilerOptions.listEmittedFiles ? [] : undefined;
99438         var emitterDiagnostics = ts.createDiagnosticCollection();
99439         var newLine = ts.getNewLineCharacter(compilerOptions, function () { return host.getNewLine(); });
99440         var writer = ts.createTextWriter(newLine);
99441         var _b = ts.performance.createTimer("printTime", "beforePrint", "afterPrint"), enter = _b.enter, exit = _b.exit;
99442         var bundleBuildInfo;
99443         var emitSkipped = false;
99444         var exportedModulesFromDeclarationEmit;
99445         // Emit each output file
99446         enter();
99447         forEachEmittedFile(host, emitSourceFileOrBundle, ts.getSourceFilesToEmit(host, targetSourceFile, forceDtsEmit), forceDtsEmit, onlyBuildInfo, !targetSourceFile);
99448         exit();
99449         return {
99450             emitSkipped: emitSkipped,
99451             diagnostics: emitterDiagnostics.getDiagnostics(),
99452             emittedFiles: emittedFilesList,
99453             sourceMaps: sourceMapDataList,
99454             exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit
99455         };
99456         function emitSourceFileOrBundle(_a, sourceFileOrBundle) {
99457             var jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
99458             var buildInfoDirectory;
99459             if (buildInfoPath && sourceFileOrBundle && ts.isBundle(sourceFileOrBundle)) {
99460                 buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
99461                 bundleBuildInfo = {
99462                     commonSourceDirectory: relativeToBuildInfo(host.getCommonSourceDirectory()),
99463                     sourceFiles: sourceFileOrBundle.sourceFiles.map(function (file) { return relativeToBuildInfo(ts.getNormalizedAbsolutePath(file.fileName, host.getCurrentDirectory())); })
99464                 };
99465             }
99466             ts.tracing.push("emit" /* Emit */, "emitJsFileOrBundle", { jsFilePath: jsFilePath });
99467             emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo);
99468             ts.tracing.pop();
99469             ts.tracing.push("emit" /* Emit */, "emitDeclarationFileOrBundle", { declarationFilePath: declarationFilePath });
99470             emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo);
99471             ts.tracing.pop();
99472             ts.tracing.push("emit" /* Emit */, "emitBuildInfo", { buildInfoPath: buildInfoPath });
99473             emitBuildInfo(bundleBuildInfo, buildInfoPath);
99474             ts.tracing.pop();
99475             if (!emitSkipped && emittedFilesList) {
99476                 if (!emitOnlyDtsFiles) {
99477                     if (jsFilePath) {
99478                         emittedFilesList.push(jsFilePath);
99479                     }
99480                     if (sourceMapFilePath) {
99481                         emittedFilesList.push(sourceMapFilePath);
99482                     }
99483                     if (buildInfoPath) {
99484                         emittedFilesList.push(buildInfoPath);
99485                     }
99486                 }
99487                 if (declarationFilePath) {
99488                     emittedFilesList.push(declarationFilePath);
99489                 }
99490                 if (declarationMapPath) {
99491                     emittedFilesList.push(declarationMapPath);
99492                 }
99493             }
99494             function relativeToBuildInfo(path) {
99495                 return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, host.getCanonicalFileName));
99496             }
99497         }
99498         function emitBuildInfo(bundle, buildInfoPath) {
99499             // Write build information if applicable
99500             if (!buildInfoPath || targetSourceFile || emitSkipped)
99501                 return;
99502             var program = host.getProgramBuildInfo();
99503             if (host.isEmitBlocked(buildInfoPath)) {
99504                 emitSkipped = true;
99505                 return;
99506             }
99507             var version = ts.version; // Extracted into a const so the form is stable between namespace and module
99508             ts.writeFile(host, emitterDiagnostics, buildInfoPath, getBuildInfoText({ bundle: bundle, program: program, version: version }), /*writeByteOrderMark*/ false);
99509         }
99510         function emitJsFileOrBundle(sourceFileOrBundle, jsFilePath, sourceMapFilePath, relativeToBuildInfo) {
99511             if (!sourceFileOrBundle || emitOnlyDtsFiles || !jsFilePath) {
99512                 return;
99513             }
99514             // Make sure not to write js file and source map file if any of them cannot be written
99515             if ((jsFilePath && host.isEmitBlocked(jsFilePath)) || compilerOptions.noEmit) {
99516                 emitSkipped = true;
99517                 return;
99518             }
99519             // Transform the source files
99520             var transform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, [sourceFileOrBundle], scriptTransformers, /*allowDtsFiles*/ false);
99521             var printerOptions = {
99522                 removeComments: compilerOptions.removeComments,
99523                 newLine: compilerOptions.newLine,
99524                 noEmitHelpers: compilerOptions.noEmitHelpers,
99525                 module: compilerOptions.module,
99526                 target: compilerOptions.target,
99527                 sourceMap: compilerOptions.sourceMap,
99528                 inlineSourceMap: compilerOptions.inlineSourceMap,
99529                 inlineSources: compilerOptions.inlineSources,
99530                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
99531                 writeBundleFileInfo: !!bundleBuildInfo,
99532                 relativeToBuildInfo: relativeToBuildInfo
99533             };
99534             // Create a printer to print the nodes
99535             var printer = createPrinter(printerOptions, {
99536                 // resolver hooks
99537                 hasGlobalName: resolver.hasGlobalName,
99538                 // transform hooks
99539                 onEmitNode: transform.emitNodeWithNotification,
99540                 isEmitNotificationEnabled: transform.isEmitNotificationEnabled,
99541                 substituteNode: transform.substituteNode,
99542             });
99543             ts.Debug.assert(transform.transformed.length === 1, "Should only see one output from the transform");
99544             printSourceFileOrBundle(jsFilePath, sourceMapFilePath, transform.transformed[0], printer, compilerOptions);
99545             // Clean up emit nodes on parse tree
99546             transform.dispose();
99547             if (bundleBuildInfo)
99548                 bundleBuildInfo.js = printer.bundleFileInfo;
99549         }
99550         function emitDeclarationFileOrBundle(sourceFileOrBundle, declarationFilePath, declarationMapPath, relativeToBuildInfo) {
99551             if (!sourceFileOrBundle)
99552                 return;
99553             if (!declarationFilePath) {
99554                 if (emitOnlyDtsFiles || compilerOptions.emitDeclarationOnly)
99555                     emitSkipped = true;
99556                 return;
99557             }
99558             var sourceFiles = ts.isSourceFile(sourceFileOrBundle) ? [sourceFileOrBundle] : sourceFileOrBundle.sourceFiles;
99559             var filesForEmit = forceDtsEmit ? sourceFiles : ts.filter(sourceFiles, ts.isSourceFileNotJson);
99560             // Setup and perform the transformation to retrieve declarations from the input files
99561             var inputListOrBundle = ts.outFile(compilerOptions) ? [ts.factory.createBundle(filesForEmit, !ts.isSourceFile(sourceFileOrBundle) ? sourceFileOrBundle.prepends : undefined)] : filesForEmit;
99562             if (emitOnlyDtsFiles && !ts.getEmitDeclarations(compilerOptions)) {
99563                 // Checker wont collect the linked aliases since thats only done when declaration is enabled.
99564                 // Do that here when emitting only dts files
99565                 filesForEmit.forEach(collectLinkedAliases);
99566             }
99567             var declarationTransform = ts.transformNodes(resolver, host, ts.factory, compilerOptions, inputListOrBundle, declarationTransformers, /*allowDtsFiles*/ false);
99568             if (ts.length(declarationTransform.diagnostics)) {
99569                 for (var _a = 0, _b = declarationTransform.diagnostics; _a < _b.length; _a++) {
99570                     var diagnostic = _b[_a];
99571                     emitterDiagnostics.add(diagnostic);
99572                 }
99573             }
99574             var printerOptions = {
99575                 removeComments: compilerOptions.removeComments,
99576                 newLine: compilerOptions.newLine,
99577                 noEmitHelpers: true,
99578                 module: compilerOptions.module,
99579                 target: compilerOptions.target,
99580                 sourceMap: compilerOptions.sourceMap,
99581                 inlineSourceMap: compilerOptions.inlineSourceMap,
99582                 extendedDiagnostics: compilerOptions.extendedDiagnostics,
99583                 onlyPrintJsDocStyle: true,
99584                 writeBundleFileInfo: !!bundleBuildInfo,
99585                 recordInternalSection: !!bundleBuildInfo,
99586                 relativeToBuildInfo: relativeToBuildInfo
99587             };
99588             var declarationPrinter = createPrinter(printerOptions, {
99589                 // resolver hooks
99590                 hasGlobalName: resolver.hasGlobalName,
99591                 // transform hooks
99592                 onEmitNode: declarationTransform.emitNodeWithNotification,
99593                 isEmitNotificationEnabled: declarationTransform.isEmitNotificationEnabled,
99594                 substituteNode: declarationTransform.substituteNode,
99595             });
99596             var declBlocked = (!!declarationTransform.diagnostics && !!declarationTransform.diagnostics.length) || !!host.isEmitBlocked(declarationFilePath) || !!compilerOptions.noEmit;
99597             emitSkipped = emitSkipped || declBlocked;
99598             if (!declBlocked || forceDtsEmit) {
99599                 ts.Debug.assert(declarationTransform.transformed.length === 1, "Should only see one output from the decl transform");
99600                 printSourceFileOrBundle(declarationFilePath, declarationMapPath, declarationTransform.transformed[0], declarationPrinter, {
99601                     sourceMap: compilerOptions.declarationMap,
99602                     sourceRoot: compilerOptions.sourceRoot,
99603                     mapRoot: compilerOptions.mapRoot,
99604                     extendedDiagnostics: compilerOptions.extendedDiagnostics,
99605                 });
99606                 if (forceDtsEmit && declarationTransform.transformed[0].kind === 297 /* SourceFile */) {
99607                     var sourceFile = declarationTransform.transformed[0];
99608                     exportedModulesFromDeclarationEmit = sourceFile.exportedModulesFromDeclarationEmit;
99609                 }
99610             }
99611             declarationTransform.dispose();
99612             if (bundleBuildInfo)
99613                 bundleBuildInfo.dts = declarationPrinter.bundleFileInfo;
99614         }
99615         function collectLinkedAliases(node) {
99616             if (ts.isExportAssignment(node)) {
99617                 if (node.expression.kind === 78 /* Identifier */) {
99618                     resolver.collectLinkedAliases(node.expression, /*setVisibility*/ true);
99619                 }
99620                 return;
99621             }
99622             else if (ts.isExportSpecifier(node)) {
99623                 resolver.collectLinkedAliases(node.propertyName || node.name, /*setVisibility*/ true);
99624                 return;
99625             }
99626             ts.forEachChild(node, collectLinkedAliases);
99627         }
99628         function printSourceFileOrBundle(jsFilePath, sourceMapFilePath, sourceFileOrBundle, printer, mapOptions) {
99629             var bundle = sourceFileOrBundle.kind === 298 /* Bundle */ ? sourceFileOrBundle : undefined;
99630             var sourceFile = sourceFileOrBundle.kind === 297 /* SourceFile */ ? sourceFileOrBundle : undefined;
99631             var sourceFiles = bundle ? bundle.sourceFiles : [sourceFile];
99632             var sourceMapGenerator;
99633             if (shouldEmitSourceMaps(mapOptions, sourceFileOrBundle)) {
99634                 sourceMapGenerator = ts.createSourceMapGenerator(host, ts.getBaseFileName(ts.normalizeSlashes(jsFilePath)), getSourceRoot(mapOptions), getSourceMapDirectory(mapOptions, jsFilePath, sourceFile), mapOptions);
99635             }
99636             if (bundle) {
99637                 printer.writeBundle(bundle, writer, sourceMapGenerator);
99638             }
99639             else {
99640                 printer.writeFile(sourceFile, writer, sourceMapGenerator);
99641             }
99642             if (sourceMapGenerator) {
99643                 if (sourceMapDataList) {
99644                     sourceMapDataList.push({
99645                         inputSourceFileNames: sourceMapGenerator.getSources(),
99646                         sourceMap: sourceMapGenerator.toJSON()
99647                     });
99648                 }
99649                 var sourceMappingURL = getSourceMappingURL(mapOptions, sourceMapGenerator, jsFilePath, sourceMapFilePath, sourceFile);
99650                 if (sourceMappingURL) {
99651                     if (!writer.isAtStartOfLine())
99652                         writer.rawWrite(newLine);
99653                     writer.writeComment("//# " + "sourceMappingURL" + "=" + sourceMappingURL); // Tools can sometimes see this line as a source mapping url comment
99654                 }
99655                 // Write the source map
99656                 if (sourceMapFilePath) {
99657                     var sourceMap = sourceMapGenerator.toString();
99658                     ts.writeFile(host, emitterDiagnostics, sourceMapFilePath, sourceMap, /*writeByteOrderMark*/ false, sourceFiles);
99659                 }
99660             }
99661             else {
99662                 writer.writeLine();
99663             }
99664             // Write the output file
99665             ts.writeFile(host, emitterDiagnostics, jsFilePath, writer.getText(), !!compilerOptions.emitBOM, sourceFiles);
99666             // Reset state
99667             writer.clear();
99668         }
99669         function shouldEmitSourceMaps(mapOptions, sourceFileOrBundle) {
99670             return (mapOptions.sourceMap || mapOptions.inlineSourceMap)
99671                 && (sourceFileOrBundle.kind !== 297 /* SourceFile */ || !ts.fileExtensionIs(sourceFileOrBundle.fileName, ".json" /* Json */));
99672         }
99673         function getSourceRoot(mapOptions) {
99674             // Normalize source root and make sure it has trailing "/" so that it can be used to combine paths with the
99675             // relative paths of the sources list in the sourcemap
99676             var sourceRoot = ts.normalizeSlashes(mapOptions.sourceRoot || "");
99677             return sourceRoot ? ts.ensureTrailingDirectorySeparator(sourceRoot) : sourceRoot;
99678         }
99679         function getSourceMapDirectory(mapOptions, filePath, sourceFile) {
99680             if (mapOptions.sourceRoot)
99681                 return host.getCommonSourceDirectory();
99682             if (mapOptions.mapRoot) {
99683                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
99684                 if (sourceFile) {
99685                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
99686                     // 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
99687                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
99688                 }
99689                 if (ts.getRootLength(sourceMapDir) === 0) {
99690                     // The relative paths are relative to the common directory
99691                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
99692                 }
99693                 return sourceMapDir;
99694             }
99695             return ts.getDirectoryPath(ts.normalizePath(filePath));
99696         }
99697         function getSourceMappingURL(mapOptions, sourceMapGenerator, filePath, sourceMapFilePath, sourceFile) {
99698             if (mapOptions.inlineSourceMap) {
99699                 // Encode the sourceMap into the sourceMap url
99700                 var sourceMapText = sourceMapGenerator.toString();
99701                 var base64SourceMapText = ts.base64encode(ts.sys, sourceMapText);
99702                 return "data:application/json;base64," + base64SourceMapText;
99703             }
99704             var sourceMapFile = ts.getBaseFileName(ts.normalizeSlashes(ts.Debug.checkDefined(sourceMapFilePath)));
99705             if (mapOptions.mapRoot) {
99706                 var sourceMapDir = ts.normalizeSlashes(mapOptions.mapRoot);
99707                 if (sourceFile) {
99708                     // For modules or multiple emit files the mapRoot will have directory structure like the sources
99709                     // 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
99710                     sourceMapDir = ts.getDirectoryPath(ts.getSourceFilePathInNewDir(sourceFile.fileName, host, sourceMapDir));
99711                 }
99712                 if (ts.getRootLength(sourceMapDir) === 0) {
99713                     // The relative paths are relative to the common directory
99714                     sourceMapDir = ts.combinePaths(host.getCommonSourceDirectory(), sourceMapDir);
99715                     return encodeURI(ts.getRelativePathToDirectoryOrUrl(ts.getDirectoryPath(ts.normalizePath(filePath)), // get the relative sourceMapDir path based on jsFilePath
99716                     ts.combinePaths(sourceMapDir, sourceMapFile), // this is where user expects to see sourceMap
99717                     host.getCurrentDirectory(), host.getCanonicalFileName, 
99718                     /*isAbsolutePathAnUrl*/ true));
99719                 }
99720                 else {
99721                     return encodeURI(ts.combinePaths(sourceMapDir, sourceMapFile));
99722                 }
99723             }
99724             return encodeURI(sourceMapFile);
99725         }
99726     }
99727     ts.emitFiles = emitFiles;
99728     /*@internal*/
99729     function getBuildInfoText(buildInfo) {
99730         return JSON.stringify(buildInfo, undefined, 2);
99731     }
99732     ts.getBuildInfoText = getBuildInfoText;
99733     /*@internal*/
99734     function getBuildInfo(buildInfoText) {
99735         return JSON.parse(buildInfoText);
99736     }
99737     ts.getBuildInfo = getBuildInfo;
99738     /*@internal*/
99739     ts.notImplementedResolver = {
99740         hasGlobalName: ts.notImplemented,
99741         getReferencedExportContainer: ts.notImplemented,
99742         getReferencedImportDeclaration: ts.notImplemented,
99743         getReferencedDeclarationWithCollidingName: ts.notImplemented,
99744         isDeclarationWithCollidingName: ts.notImplemented,
99745         isValueAliasDeclaration: ts.notImplemented,
99746         isReferencedAliasDeclaration: ts.notImplemented,
99747         isTopLevelValueImportEqualsWithEntityName: ts.notImplemented,
99748         getNodeCheckFlags: ts.notImplemented,
99749         isDeclarationVisible: ts.notImplemented,
99750         isLateBound: function (_node) { return false; },
99751         collectLinkedAliases: ts.notImplemented,
99752         isImplementationOfOverload: ts.notImplemented,
99753         isRequiredInitializedParameter: ts.notImplemented,
99754         isOptionalUninitializedParameterProperty: ts.notImplemented,
99755         isExpandoFunctionDeclaration: ts.notImplemented,
99756         getPropertiesOfContainerFunction: ts.notImplemented,
99757         createTypeOfDeclaration: ts.notImplemented,
99758         createReturnTypeOfSignatureDeclaration: ts.notImplemented,
99759         createTypeOfExpression: ts.notImplemented,
99760         createLiteralConstValue: ts.notImplemented,
99761         isSymbolAccessible: ts.notImplemented,
99762         isEntityNameVisible: ts.notImplemented,
99763         // Returns the constant value this property access resolves to: notImplemented, or 'undefined' for a non-constant
99764         getConstantValue: ts.notImplemented,
99765         getReferencedValueDeclaration: ts.notImplemented,
99766         getTypeReferenceSerializationKind: ts.notImplemented,
99767         isOptionalParameter: ts.notImplemented,
99768         moduleExportsSomeValue: ts.notImplemented,
99769         isArgumentsLocalBinding: ts.notImplemented,
99770         getExternalModuleFileFromDeclaration: ts.notImplemented,
99771         getTypeReferenceDirectivesForEntityName: ts.notImplemented,
99772         getTypeReferenceDirectivesForSymbol: ts.notImplemented,
99773         isLiteralConstDeclaration: ts.notImplemented,
99774         getJsxFactoryEntity: ts.notImplemented,
99775         getJsxFragmentFactoryEntity: ts.notImplemented,
99776         getAllAccessorDeclarations: ts.notImplemented,
99777         getSymbolOfExternalModuleSpecifier: ts.notImplemented,
99778         isBindingCapturedByNode: ts.notImplemented,
99779         getDeclarationStatementsForSourceFile: ts.notImplemented,
99780         isImportRequiredByAugmentation: ts.notImplemented,
99781     };
99782     function createSourceFilesFromBundleBuildInfo(bundle, buildInfoDirectory, host) {
99783         var _a;
99784         var jsBundle = ts.Debug.checkDefined(bundle.js);
99785         var prologueMap = ((_a = jsBundle.sources) === null || _a === void 0 ? void 0 : _a.prologues) && ts.arrayToMap(jsBundle.sources.prologues, function (prologueInfo) { return prologueInfo.file; });
99786         return bundle.sourceFiles.map(function (fileName, index) {
99787             var _a, _b;
99788             var prologueInfo = prologueMap === null || prologueMap === void 0 ? void 0 : prologueMap.get(index);
99789             var statements = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.directives.map(function (directive) {
99790                 var literal = ts.setTextRange(ts.factory.createStringLiteral(directive.expression.text), directive.expression);
99791                 var statement = ts.setTextRange(ts.factory.createExpressionStatement(literal), directive);
99792                 ts.setParent(literal, statement);
99793                 return statement;
99794             });
99795             var eofToken = ts.factory.createToken(1 /* EndOfFileToken */);
99796             var sourceFile = ts.factory.createSourceFile(statements !== null && statements !== void 0 ? statements : [], eofToken, 0 /* None */);
99797             sourceFile.fileName = ts.getRelativePathFromDirectory(host.getCurrentDirectory(), ts.getNormalizedAbsolutePath(fileName, buildInfoDirectory), !host.useCaseSensitiveFileNames());
99798             sourceFile.text = (_a = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text) !== null && _a !== void 0 ? _a : "";
99799             ts.setTextRangePosWidth(sourceFile, 0, (_b = prologueInfo === null || prologueInfo === void 0 ? void 0 : prologueInfo.text.length) !== null && _b !== void 0 ? _b : 0);
99800             ts.setEachParent(sourceFile.statements, sourceFile);
99801             ts.setTextRangePosWidth(eofToken, sourceFile.end, 0);
99802             ts.setParent(eofToken, sourceFile);
99803             return sourceFile;
99804         });
99805     }
99806     /*@internal*/
99807     function emitUsingBuildInfo(config, host, getCommandLine, customTransformers) {
99808         var _a = getOutputPathsForBundle(config.options, /*forceDtsPaths*/ false), buildInfoPath = _a.buildInfoPath, jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath;
99809         var buildInfoText = host.readFile(ts.Debug.checkDefined(buildInfoPath));
99810         if (!buildInfoText)
99811             return buildInfoPath;
99812         var jsFileText = host.readFile(ts.Debug.checkDefined(jsFilePath));
99813         if (!jsFileText)
99814             return jsFilePath;
99815         var sourceMapText = sourceMapFilePath && host.readFile(sourceMapFilePath);
99816         // error if no source map or for now if inline sourcemap
99817         if ((sourceMapFilePath && !sourceMapText) || config.options.inlineSourceMap)
99818             return sourceMapFilePath || "inline sourcemap decoding";
99819         // read declaration text
99820         var declarationText = declarationFilePath && host.readFile(declarationFilePath);
99821         if (declarationFilePath && !declarationText)
99822             return declarationFilePath;
99823         var declarationMapText = declarationMapPath && host.readFile(declarationMapPath);
99824         // error if no source map or for now if inline sourcemap
99825         if ((declarationMapPath && !declarationMapText) || config.options.inlineSourceMap)
99826             return declarationMapPath || "inline sourcemap decoding";
99827         var buildInfo = getBuildInfo(buildInfoText);
99828         if (!buildInfo.bundle || !buildInfo.bundle.js || (declarationText && !buildInfo.bundle.dts))
99829             return buildInfoPath;
99830         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
99831         var ownPrependInput = ts.createInputFiles(jsFileText, declarationText, sourceMapFilePath, sourceMapText, declarationMapPath, declarationMapText, jsFilePath, declarationFilePath, buildInfoPath, buildInfo, 
99832         /*onlyOwnText*/ true);
99833         var outputFiles = [];
99834         var prependNodes = ts.createPrependNodes(config.projectReferences, getCommandLine, function (f) { return host.readFile(f); });
99835         var sourceFilesForJsEmit = createSourceFilesFromBundleBuildInfo(buildInfo.bundle, buildInfoDirectory, host);
99836         var emitHost = {
99837             getPrependNodes: ts.memoize(function () { return __spreadArrays(prependNodes, [ownPrependInput]); }),
99838             getCanonicalFileName: host.getCanonicalFileName,
99839             getCommonSourceDirectory: function () { return ts.getNormalizedAbsolutePath(buildInfo.bundle.commonSourceDirectory, buildInfoDirectory); },
99840             getCompilerOptions: function () { return config.options; },
99841             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
99842             getNewLine: function () { return host.getNewLine(); },
99843             getSourceFile: ts.returnUndefined,
99844             getSourceFileByPath: ts.returnUndefined,
99845             getSourceFiles: function () { return sourceFilesForJsEmit; },
99846             getLibFileFromReference: ts.notImplemented,
99847             isSourceFileFromExternalLibrary: ts.returnFalse,
99848             getResolvedProjectReferenceToRedirect: ts.returnUndefined,
99849             getProjectReferenceRedirect: ts.returnUndefined,
99850             isSourceOfProjectReferenceRedirect: ts.returnFalse,
99851             writeFile: function (name, text, writeByteOrderMark) {
99852                 switch (name) {
99853                     case jsFilePath:
99854                         if (jsFileText === text)
99855                             return;
99856                         break;
99857                     case sourceMapFilePath:
99858                         if (sourceMapText === text)
99859                             return;
99860                         break;
99861                     case buildInfoPath:
99862                         var newBuildInfo = getBuildInfo(text);
99863                         newBuildInfo.program = buildInfo.program;
99864                         // Update sourceFileInfo
99865                         var _a = buildInfo.bundle, js = _a.js, dts = _a.dts, sourceFiles = _a.sourceFiles;
99866                         newBuildInfo.bundle.js.sources = js.sources;
99867                         if (dts) {
99868                             newBuildInfo.bundle.dts.sources = dts.sources;
99869                         }
99870                         newBuildInfo.bundle.sourceFiles = sourceFiles;
99871                         outputFiles.push({ name: name, text: getBuildInfoText(newBuildInfo), writeByteOrderMark: writeByteOrderMark });
99872                         return;
99873                     case declarationFilePath:
99874                         if (declarationText === text)
99875                             return;
99876                         break;
99877                     case declarationMapPath:
99878                         if (declarationMapText === text)
99879                             return;
99880                         break;
99881                     default:
99882                         ts.Debug.fail("Unexpected path: " + name);
99883                 }
99884                 outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark });
99885             },
99886             isEmitBlocked: ts.returnFalse,
99887             readFile: function (f) { return host.readFile(f); },
99888             fileExists: function (f) { return host.fileExists(f); },
99889             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
99890             getProgramBuildInfo: ts.returnUndefined,
99891             getSourceFileFromReference: ts.returnUndefined,
99892             redirectTargetsMap: ts.createMultiMap()
99893         };
99894         emitFiles(ts.notImplementedResolver, emitHost, 
99895         /*targetSourceFile*/ undefined, ts.getTransformers(config.options, customTransformers));
99896         return outputFiles;
99897     }
99898     ts.emitUsingBuildInfo = emitUsingBuildInfo;
99899     var PipelinePhase;
99900     (function (PipelinePhase) {
99901         PipelinePhase[PipelinePhase["Notification"] = 0] = "Notification";
99902         PipelinePhase[PipelinePhase["Substitution"] = 1] = "Substitution";
99903         PipelinePhase[PipelinePhase["Comments"] = 2] = "Comments";
99904         PipelinePhase[PipelinePhase["SourceMaps"] = 3] = "SourceMaps";
99905         PipelinePhase[PipelinePhase["Emit"] = 4] = "Emit";
99906     })(PipelinePhase || (PipelinePhase = {}));
99907     function createPrinter(printerOptions, handlers) {
99908         if (printerOptions === void 0) { printerOptions = {}; }
99909         if (handlers === void 0) { handlers = {}; }
99910         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;
99911         var extendedDiagnostics = !!printerOptions.extendedDiagnostics;
99912         var newLine = ts.getNewLineCharacter(printerOptions);
99913         var moduleKind = ts.getEmitModuleKind(printerOptions);
99914         var bundledHelpers = new ts.Map();
99915         var currentSourceFile;
99916         var nodeIdToGeneratedName; // Map of generated names for specific nodes.
99917         var autoGeneratedIdToGeneratedName; // Map of generated names for temp and loop variables.
99918         var generatedNames; // Set of names generated by the NameGenerator.
99919         var tempFlagsStack; // Stack of enclosing name generation scopes.
99920         var tempFlags; // TempFlags for the current name generation scope.
99921         var reservedNamesStack; // Stack of TempFlags reserved in enclosing name generation scopes.
99922         var reservedNames; // TempFlags to reserve in nested name generation scopes.
99923         var preserveSourceNewlines = printerOptions.preserveSourceNewlines; // Can be overridden inside nodes with the `IgnoreSourceNewlines` emit flag.
99924         var nextListElementPos; // See comment in `getLeadingLineTerminatorCount`.
99925         var writer;
99926         var ownWriter; // Reusable `EmitTextWriter` for basic printing.
99927         var write = writeBase;
99928         var isOwnFileEmit;
99929         var bundleFileInfo = printerOptions.writeBundleFileInfo ? { sections: [] } : undefined;
99930         var relativeToBuildInfo = bundleFileInfo ? ts.Debug.checkDefined(printerOptions.relativeToBuildInfo) : undefined;
99931         var recordInternalSection = printerOptions.recordInternalSection;
99932         var sourceFileTextPos = 0;
99933         var sourceFileTextKind = "text" /* Text */;
99934         // Source Maps
99935         var sourceMapsDisabled = true;
99936         var sourceMapGenerator;
99937         var sourceMapSource;
99938         var sourceMapSourceIndex = -1;
99939         var mostRecentlyAddedSourceMapSource;
99940         var mostRecentlyAddedSourceMapSourceIndex = -1;
99941         // Comments
99942         var containerPos = -1;
99943         var containerEnd = -1;
99944         var declarationListContainerEnd = -1;
99945         var currentLineMap;
99946         var detachedCommentsInfo;
99947         var hasWrittenComment = false;
99948         var commentsDisabled = !!printerOptions.removeComments;
99949         var lastNode;
99950         var lastSubstitution;
99951         var _c = ts.performance.createTimerIf(extendedDiagnostics, "commentTime", "beforeComment", "afterComment"), enterComment = _c.enter, exitComment = _c.exit;
99952         reset();
99953         return {
99954             // public API
99955             printNode: printNode,
99956             printList: printList,
99957             printFile: printFile,
99958             printBundle: printBundle,
99959             // internal API
99960             writeNode: writeNode,
99961             writeList: writeList,
99962             writeFile: writeFile,
99963             writeBundle: writeBundle,
99964             bundleFileInfo: bundleFileInfo
99965         };
99966         function printNode(hint, node, sourceFile) {
99967             switch (hint) {
99968                 case 0 /* SourceFile */:
99969                     ts.Debug.assert(ts.isSourceFile(node), "Expected a SourceFile node.");
99970                     break;
99971                 case 2 /* IdentifierName */:
99972                     ts.Debug.assert(ts.isIdentifier(node), "Expected an Identifier node.");
99973                     break;
99974                 case 1 /* Expression */:
99975                     ts.Debug.assert(ts.isExpression(node), "Expected an Expression node.");
99976                     break;
99977             }
99978             switch (node.kind) {
99979                 case 297 /* SourceFile */: return printFile(node);
99980                 case 298 /* Bundle */: return printBundle(node);
99981                 case 299 /* UnparsedSource */: return printUnparsedSource(node);
99982             }
99983             writeNode(hint, node, sourceFile, beginPrint());
99984             return endPrint();
99985         }
99986         function printList(format, nodes, sourceFile) {
99987             writeList(format, nodes, sourceFile, beginPrint());
99988             return endPrint();
99989         }
99990         function printBundle(bundle) {
99991             writeBundle(bundle, beginPrint(), /*sourceMapEmitter*/ undefined);
99992             return endPrint();
99993         }
99994         function printFile(sourceFile) {
99995             writeFile(sourceFile, beginPrint(), /*sourceMapEmitter*/ undefined);
99996             return endPrint();
99997         }
99998         function printUnparsedSource(unparsed) {
99999             writeUnparsedSource(unparsed, beginPrint());
100000             return endPrint();
100001         }
100002         function writeNode(hint, node, sourceFile, output) {
100003             var previousWriter = writer;
100004             setWriter(output, /*_sourceMapGenerator*/ undefined);
100005             print(hint, node, sourceFile);
100006             reset();
100007             writer = previousWriter;
100008         }
100009         function writeList(format, nodes, sourceFile, output) {
100010             var previousWriter = writer;
100011             setWriter(output, /*_sourceMapGenerator*/ undefined);
100012             if (sourceFile) {
100013                 setSourceFile(sourceFile);
100014             }
100015             emitList(syntheticParent, nodes, format);
100016             reset();
100017             writer = previousWriter;
100018         }
100019         function getTextPosWithWriteLine() {
100020             return writer.getTextPosWithWriteLine ? writer.getTextPosWithWriteLine() : writer.getTextPos();
100021         }
100022         function updateOrPushBundleFileTextLike(pos, end, kind) {
100023             var last = ts.lastOrUndefined(bundleFileInfo.sections);
100024             if (last && last.kind === kind) {
100025                 last.end = end;
100026             }
100027             else {
100028                 bundleFileInfo.sections.push({ pos: pos, end: end, kind: kind });
100029             }
100030         }
100031         function recordBundleFileInternalSectionStart(node) {
100032             if (recordInternalSection &&
100033                 bundleFileInfo &&
100034                 currentSourceFile &&
100035                 (ts.isDeclaration(node) || ts.isVariableStatement(node)) &&
100036                 ts.isInternalDeclaration(node, currentSourceFile) &&
100037                 sourceFileTextKind !== "internal" /* Internal */) {
100038                 var prevSourceFileTextKind = sourceFileTextKind;
100039                 recordBundleFileTextLikeSection(writer.getTextPos());
100040                 sourceFileTextPos = getTextPosWithWriteLine();
100041                 sourceFileTextKind = "internal" /* Internal */;
100042                 return prevSourceFileTextKind;
100043             }
100044             return undefined;
100045         }
100046         function recordBundleFileInternalSectionEnd(prevSourceFileTextKind) {
100047             if (prevSourceFileTextKind) {
100048                 recordBundleFileTextLikeSection(writer.getTextPos());
100049                 sourceFileTextPos = getTextPosWithWriteLine();
100050                 sourceFileTextKind = prevSourceFileTextKind;
100051             }
100052         }
100053         function recordBundleFileTextLikeSection(end) {
100054             if (sourceFileTextPos < end) {
100055                 updateOrPushBundleFileTextLike(sourceFileTextPos, end, sourceFileTextKind);
100056                 return true;
100057             }
100058             return false;
100059         }
100060         function writeBundle(bundle, output, sourceMapGenerator) {
100061             var _a;
100062             isOwnFileEmit = false;
100063             var previousWriter = writer;
100064             setWriter(output, sourceMapGenerator);
100065             emitShebangIfNeeded(bundle);
100066             emitPrologueDirectivesIfNeeded(bundle);
100067             emitHelpers(bundle);
100068             emitSyntheticTripleSlashReferencesIfNeeded(bundle);
100069             for (var _b = 0, _c = bundle.prepends; _b < _c.length; _b++) {
100070                 var prepend = _c[_b];
100071                 writeLine();
100072                 var pos = writer.getTextPos();
100073                 var savedSections = bundleFileInfo && bundleFileInfo.sections;
100074                 if (savedSections)
100075                     bundleFileInfo.sections = [];
100076                 print(4 /* Unspecified */, prepend, /*sourceFile*/ undefined);
100077                 if (bundleFileInfo) {
100078                     var newSections = bundleFileInfo.sections;
100079                     bundleFileInfo.sections = savedSections;
100080                     if (prepend.oldFileOfCurrentEmit)
100081                         (_a = bundleFileInfo.sections).push.apply(_a, newSections);
100082                     else {
100083                         newSections.forEach(function (section) { return ts.Debug.assert(ts.isBundleFileTextLike(section)); });
100084                         bundleFileInfo.sections.push({
100085                             pos: pos,
100086                             end: writer.getTextPos(),
100087                             kind: "prepend" /* Prepend */,
100088                             data: relativeToBuildInfo(prepend.fileName),
100089                             texts: newSections
100090                         });
100091                     }
100092                 }
100093             }
100094             sourceFileTextPos = getTextPosWithWriteLine();
100095             for (var _d = 0, _e = bundle.sourceFiles; _d < _e.length; _d++) {
100096                 var sourceFile = _e[_d];
100097                 print(0 /* SourceFile */, sourceFile, sourceFile);
100098             }
100099             if (bundleFileInfo && bundle.sourceFiles.length) {
100100                 var end = writer.getTextPos();
100101                 if (recordBundleFileTextLikeSection(end)) {
100102                     // Store prologues
100103                     var prologues = getPrologueDirectivesFromBundledSourceFiles(bundle);
100104                     if (prologues) {
100105                         if (!bundleFileInfo.sources)
100106                             bundleFileInfo.sources = {};
100107                         bundleFileInfo.sources.prologues = prologues;
100108                     }
100109                     // Store helpes
100110                     var helpers = getHelpersFromBundledSourceFiles(bundle);
100111                     if (helpers) {
100112                         if (!bundleFileInfo.sources)
100113                             bundleFileInfo.sources = {};
100114                         bundleFileInfo.sources.helpers = helpers;
100115                     }
100116                 }
100117             }
100118             reset();
100119             writer = previousWriter;
100120         }
100121         function writeUnparsedSource(unparsed, output) {
100122             var previousWriter = writer;
100123             setWriter(output, /*_sourceMapGenerator*/ undefined);
100124             print(4 /* Unspecified */, unparsed, /*sourceFile*/ undefined);
100125             reset();
100126             writer = previousWriter;
100127         }
100128         function writeFile(sourceFile, output, sourceMapGenerator) {
100129             isOwnFileEmit = true;
100130             var previousWriter = writer;
100131             setWriter(output, sourceMapGenerator);
100132             emitShebangIfNeeded(sourceFile);
100133             emitPrologueDirectivesIfNeeded(sourceFile);
100134             print(0 /* SourceFile */, sourceFile, sourceFile);
100135             reset();
100136             writer = previousWriter;
100137         }
100138         function beginPrint() {
100139             return ownWriter || (ownWriter = ts.createTextWriter(newLine));
100140         }
100141         function endPrint() {
100142             var text = ownWriter.getText();
100143             ownWriter.clear();
100144             return text;
100145         }
100146         function print(hint, node, sourceFile) {
100147             if (sourceFile) {
100148                 setSourceFile(sourceFile);
100149             }
100150             pipelineEmit(hint, node);
100151         }
100152         function setSourceFile(sourceFile) {
100153             currentSourceFile = sourceFile;
100154             currentLineMap = undefined;
100155             detachedCommentsInfo = undefined;
100156             if (sourceFile) {
100157                 setSourceMapSource(sourceFile);
100158             }
100159         }
100160         function setWriter(_writer, _sourceMapGenerator) {
100161             if (_writer && printerOptions.omitTrailingSemicolon) {
100162                 _writer = ts.getTrailingSemicolonDeferringWriter(_writer);
100163             }
100164             writer = _writer; // TODO: GH#18217
100165             sourceMapGenerator = _sourceMapGenerator;
100166             sourceMapsDisabled = !writer || !sourceMapGenerator;
100167         }
100168         function reset() {
100169             nodeIdToGeneratedName = [];
100170             autoGeneratedIdToGeneratedName = [];
100171             generatedNames = new ts.Set();
100172             tempFlagsStack = [];
100173             tempFlags = 0 /* Auto */;
100174             reservedNamesStack = [];
100175             currentSourceFile = undefined;
100176             currentLineMap = undefined;
100177             detachedCommentsInfo = undefined;
100178             lastNode = undefined;
100179             lastSubstitution = undefined;
100180             setWriter(/*output*/ undefined, /*_sourceMapGenerator*/ undefined);
100181         }
100182         function getCurrentLineMap() {
100183             return currentLineMap || (currentLineMap = ts.getLineStarts(currentSourceFile));
100184         }
100185         function emit(node) {
100186             if (node === undefined)
100187                 return;
100188             var prevSourceFileTextKind = recordBundleFileInternalSectionStart(node);
100189             var substitute = pipelineEmit(4 /* Unspecified */, node);
100190             recordBundleFileInternalSectionEnd(prevSourceFileTextKind);
100191             return substitute;
100192         }
100193         function emitIdentifierName(node) {
100194             if (node === undefined)
100195                 return;
100196             return pipelineEmit(2 /* IdentifierName */, node);
100197         }
100198         function emitExpression(node) {
100199             if (node === undefined)
100200                 return;
100201             return pipelineEmit(1 /* Expression */, node);
100202         }
100203         function emitJsxAttributeValue(node) {
100204             return pipelineEmit(ts.isStringLiteral(node) ? 6 /* JsxAttributeValue */ : 4 /* Unspecified */, node);
100205         }
100206         function pipelineEmit(emitHint, node) {
100207             var savedLastNode = lastNode;
100208             var savedLastSubstitution = lastSubstitution;
100209             var savedPreserveSourceNewlines = preserveSourceNewlines;
100210             lastNode = node;
100211             lastSubstitution = undefined;
100212             if (preserveSourceNewlines && !!(ts.getEmitFlags(node) & 134217728 /* IgnoreSourceNewlines */)) {
100213                 preserveSourceNewlines = false;
100214             }
100215             var pipelinePhase = getPipelinePhase(0 /* Notification */, emitHint, node);
100216             pipelinePhase(emitHint, node);
100217             ts.Debug.assert(lastNode === node);
100218             var substitute = lastSubstitution;
100219             lastNode = savedLastNode;
100220             lastSubstitution = savedLastSubstitution;
100221             preserveSourceNewlines = savedPreserveSourceNewlines;
100222             return substitute || node;
100223         }
100224         function getPipelinePhase(phase, emitHint, node) {
100225             switch (phase) {
100226                 case 0 /* Notification */:
100227                     if (onEmitNode !== ts.noEmitNotification && (!isEmitNotificationEnabled || isEmitNotificationEnabled(node))) {
100228                         return pipelineEmitWithNotification;
100229                     }
100230                 // falls through
100231                 case 1 /* Substitution */:
100232                     if (substituteNode !== ts.noEmitSubstitution && (lastSubstitution = substituteNode(emitHint, node)) !== node) {
100233                         return pipelineEmitWithSubstitution;
100234                     }
100235                 // falls through
100236                 case 2 /* Comments */:
100237                     if (!commentsDisabled && node.kind !== 297 /* SourceFile */) {
100238                         return pipelineEmitWithComments;
100239                     }
100240                 // falls through
100241                 case 3 /* SourceMaps */:
100242                     if (!sourceMapsDisabled && node.kind !== 297 /* SourceFile */ && !ts.isInJsonFile(node)) {
100243                         return pipelineEmitWithSourceMap;
100244                     }
100245                 // falls through
100246                 case 4 /* Emit */:
100247                     return pipelineEmitWithHint;
100248                 default:
100249                     return ts.Debug.assertNever(phase);
100250             }
100251         }
100252         function getNextPipelinePhase(currentPhase, emitHint, node) {
100253             return getPipelinePhase(currentPhase + 1, emitHint, node);
100254         }
100255         function pipelineEmitWithNotification(hint, node) {
100256             ts.Debug.assert(lastNode === node);
100257             var pipelinePhase = getNextPipelinePhase(0 /* Notification */, hint, node);
100258             onEmitNode(hint, node, pipelinePhase);
100259             ts.Debug.assert(lastNode === node);
100260         }
100261         function pipelineEmitWithHint(hint, node) {
100262             ts.Debug.assert(lastNode === node || lastSubstitution === node);
100263             if (hint === 0 /* SourceFile */)
100264                 return emitSourceFile(ts.cast(node, ts.isSourceFile));
100265             if (hint === 2 /* IdentifierName */)
100266                 return emitIdentifier(ts.cast(node, ts.isIdentifier));
100267             if (hint === 6 /* JsxAttributeValue */)
100268                 return emitLiteral(ts.cast(node, ts.isStringLiteral), /*jsxAttributeEscape*/ true);
100269             if (hint === 3 /* MappedTypeParameter */)
100270                 return emitMappedTypeParameter(ts.cast(node, ts.isTypeParameterDeclaration));
100271             if (hint === 5 /* EmbeddedStatement */) {
100272                 ts.Debug.assertNode(node, ts.isEmptyStatement);
100273                 return emitEmptyStatement(/*isEmbeddedStatement*/ true);
100274             }
100275             if (hint === 4 /* Unspecified */) {
100276                 if (ts.isKeyword(node.kind))
100277                     return writeTokenNode(node, writeKeyword);
100278                 switch (node.kind) {
100279                     // Pseudo-literals
100280                     case 15 /* TemplateHead */:
100281                     case 16 /* TemplateMiddle */:
100282                     case 17 /* TemplateTail */:
100283                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
100284                     case 299 /* UnparsedSource */:
100285                     case 293 /* UnparsedPrepend */:
100286                         return emitUnparsedSourceOrPrepend(node);
100287                     case 292 /* UnparsedPrologue */:
100288                         return writeUnparsedNode(node);
100289                     case 294 /* UnparsedText */:
100290                     case 295 /* UnparsedInternalText */:
100291                         return emitUnparsedTextLike(node);
100292                     case 296 /* UnparsedSyntheticReference */:
100293                         return emitUnparsedSyntheticReference(node);
100294                     // Identifiers
100295                     case 78 /* Identifier */:
100296                         return emitIdentifier(node);
100297                     // PrivateIdentifiers
100298                     case 79 /* PrivateIdentifier */:
100299                         return emitPrivateIdentifier(node);
100300                     // Parse tree nodes
100301                     // Names
100302                     case 157 /* QualifiedName */:
100303                         return emitQualifiedName(node);
100304                     case 158 /* ComputedPropertyName */:
100305                         return emitComputedPropertyName(node);
100306                     // Signature elements
100307                     case 159 /* TypeParameter */:
100308                         return emitTypeParameter(node);
100309                     case 160 /* Parameter */:
100310                         return emitParameter(node);
100311                     case 161 /* Decorator */:
100312                         return emitDecorator(node);
100313                     // Type members
100314                     case 162 /* PropertySignature */:
100315                         return emitPropertySignature(node);
100316                     case 163 /* PropertyDeclaration */:
100317                         return emitPropertyDeclaration(node);
100318                     case 164 /* MethodSignature */:
100319                         return emitMethodSignature(node);
100320                     case 165 /* MethodDeclaration */:
100321                         return emitMethodDeclaration(node);
100322                     case 166 /* Constructor */:
100323                         return emitConstructor(node);
100324                     case 167 /* GetAccessor */:
100325                     case 168 /* SetAccessor */:
100326                         return emitAccessorDeclaration(node);
100327                     case 169 /* CallSignature */:
100328                         return emitCallSignature(node);
100329                     case 170 /* ConstructSignature */:
100330                         return emitConstructSignature(node);
100331                     case 171 /* IndexSignature */:
100332                         return emitIndexSignature(node);
100333                     case 194 /* TemplateLiteralTypeSpan */:
100334                         return emitTemplateTypeSpan(node);
100335                     // Types
100336                     case 172 /* TypePredicate */:
100337                         return emitTypePredicate(node);
100338                     case 173 /* TypeReference */:
100339                         return emitTypeReference(node);
100340                     case 174 /* FunctionType */:
100341                         return emitFunctionType(node);
100342                     case 308 /* JSDocFunctionType */:
100343                         return emitJSDocFunctionType(node);
100344                     case 175 /* ConstructorType */:
100345                         return emitConstructorType(node);
100346                     case 176 /* TypeQuery */:
100347                         return emitTypeQuery(node);
100348                     case 177 /* TypeLiteral */:
100349                         return emitTypeLiteral(node);
100350                     case 178 /* ArrayType */:
100351                         return emitArrayType(node);
100352                     case 179 /* TupleType */:
100353                         return emitTupleType(node);
100354                     case 180 /* OptionalType */:
100355                         return emitOptionalType(node);
100356                     case 182 /* UnionType */:
100357                         return emitUnionType(node);
100358                     case 183 /* IntersectionType */:
100359                         return emitIntersectionType(node);
100360                     case 184 /* ConditionalType */:
100361                         return emitConditionalType(node);
100362                     case 185 /* InferType */:
100363                         return emitInferType(node);
100364                     case 186 /* ParenthesizedType */:
100365                         return emitParenthesizedType(node);
100366                     case 223 /* ExpressionWithTypeArguments */:
100367                         return emitExpressionWithTypeArguments(node);
100368                     case 187 /* ThisType */:
100369                         return emitThisType();
100370                     case 188 /* TypeOperator */:
100371                         return emitTypeOperator(node);
100372                     case 189 /* IndexedAccessType */:
100373                         return emitIndexedAccessType(node);
100374                     case 190 /* MappedType */:
100375                         return emitMappedType(node);
100376                     case 191 /* LiteralType */:
100377                         return emitLiteralType(node);
100378                     case 193 /* TemplateLiteralType */:
100379                         return emitTemplateType(node);
100380                     case 195 /* ImportType */:
100381                         return emitImportTypeNode(node);
100382                     case 303 /* JSDocAllType */:
100383                         writePunctuation("*");
100384                         return;
100385                     case 304 /* JSDocUnknownType */:
100386                         writePunctuation("?");
100387                         return;
100388                     case 305 /* JSDocNullableType */:
100389                         return emitJSDocNullableType(node);
100390                     case 306 /* JSDocNonNullableType */:
100391                         return emitJSDocNonNullableType(node);
100392                     case 307 /* JSDocOptionalType */:
100393                         return emitJSDocOptionalType(node);
100394                     case 181 /* RestType */:
100395                     case 309 /* JSDocVariadicType */:
100396                         return emitRestOrJSDocVariadicType(node);
100397                     case 192 /* NamedTupleMember */:
100398                         return emitNamedTupleMember(node);
100399                     // Binding patterns
100400                     case 196 /* ObjectBindingPattern */:
100401                         return emitObjectBindingPattern(node);
100402                     case 197 /* ArrayBindingPattern */:
100403                         return emitArrayBindingPattern(node);
100404                     case 198 /* BindingElement */:
100405                         return emitBindingElement(node);
100406                     // Misc
100407                     case 228 /* TemplateSpan */:
100408                         return emitTemplateSpan(node);
100409                     case 229 /* SemicolonClassElement */:
100410                         return emitSemicolonClassElement();
100411                     // Statements
100412                     case 230 /* Block */:
100413                         return emitBlock(node);
100414                     case 232 /* VariableStatement */:
100415                         return emitVariableStatement(node);
100416                     case 231 /* EmptyStatement */:
100417                         return emitEmptyStatement(/*isEmbeddedStatement*/ false);
100418                     case 233 /* ExpressionStatement */:
100419                         return emitExpressionStatement(node);
100420                     case 234 /* IfStatement */:
100421                         return emitIfStatement(node);
100422                     case 235 /* DoStatement */:
100423                         return emitDoStatement(node);
100424                     case 236 /* WhileStatement */:
100425                         return emitWhileStatement(node);
100426                     case 237 /* ForStatement */:
100427                         return emitForStatement(node);
100428                     case 238 /* ForInStatement */:
100429                         return emitForInStatement(node);
100430                     case 239 /* ForOfStatement */:
100431                         return emitForOfStatement(node);
100432                     case 240 /* ContinueStatement */:
100433                         return emitContinueStatement(node);
100434                     case 241 /* BreakStatement */:
100435                         return emitBreakStatement(node);
100436                     case 242 /* ReturnStatement */:
100437                         return emitReturnStatement(node);
100438                     case 243 /* WithStatement */:
100439                         return emitWithStatement(node);
100440                     case 244 /* SwitchStatement */:
100441                         return emitSwitchStatement(node);
100442                     case 245 /* LabeledStatement */:
100443                         return emitLabeledStatement(node);
100444                     case 246 /* ThrowStatement */:
100445                         return emitThrowStatement(node);
100446                     case 247 /* TryStatement */:
100447                         return emitTryStatement(node);
100448                     case 248 /* DebuggerStatement */:
100449                         return emitDebuggerStatement(node);
100450                     // Declarations
100451                     case 249 /* VariableDeclaration */:
100452                         return emitVariableDeclaration(node);
100453                     case 250 /* VariableDeclarationList */:
100454                         return emitVariableDeclarationList(node);
100455                     case 251 /* FunctionDeclaration */:
100456                         return emitFunctionDeclaration(node);
100457                     case 252 /* ClassDeclaration */:
100458                         return emitClassDeclaration(node);
100459                     case 253 /* InterfaceDeclaration */:
100460                         return emitInterfaceDeclaration(node);
100461                     case 254 /* TypeAliasDeclaration */:
100462                         return emitTypeAliasDeclaration(node);
100463                     case 255 /* EnumDeclaration */:
100464                         return emitEnumDeclaration(node);
100465                     case 256 /* ModuleDeclaration */:
100466                         return emitModuleDeclaration(node);
100467                     case 257 /* ModuleBlock */:
100468                         return emitModuleBlock(node);
100469                     case 258 /* CaseBlock */:
100470                         return emitCaseBlock(node);
100471                     case 259 /* NamespaceExportDeclaration */:
100472                         return emitNamespaceExportDeclaration(node);
100473                     case 260 /* ImportEqualsDeclaration */:
100474                         return emitImportEqualsDeclaration(node);
100475                     case 261 /* ImportDeclaration */:
100476                         return emitImportDeclaration(node);
100477                     case 262 /* ImportClause */:
100478                         return emitImportClause(node);
100479                     case 263 /* NamespaceImport */:
100480                         return emitNamespaceImport(node);
100481                     case 269 /* NamespaceExport */:
100482                         return emitNamespaceExport(node);
100483                     case 264 /* NamedImports */:
100484                         return emitNamedImports(node);
100485                     case 265 /* ImportSpecifier */:
100486                         return emitImportSpecifier(node);
100487                     case 266 /* ExportAssignment */:
100488                         return emitExportAssignment(node);
100489                     case 267 /* ExportDeclaration */:
100490                         return emitExportDeclaration(node);
100491                     case 268 /* NamedExports */:
100492                         return emitNamedExports(node);
100493                     case 270 /* ExportSpecifier */:
100494                         return emitExportSpecifier(node);
100495                     case 271 /* MissingDeclaration */:
100496                         return;
100497                     // Module references
100498                     case 272 /* ExternalModuleReference */:
100499                         return emitExternalModuleReference(node);
100500                     // JSX (non-expression)
100501                     case 11 /* JsxText */:
100502                         return emitJsxText(node);
100503                     case 275 /* JsxOpeningElement */:
100504                     case 278 /* JsxOpeningFragment */:
100505                         return emitJsxOpeningElementOrFragment(node);
100506                     case 276 /* JsxClosingElement */:
100507                     case 279 /* JsxClosingFragment */:
100508                         return emitJsxClosingElementOrFragment(node);
100509                     case 280 /* JsxAttribute */:
100510                         return emitJsxAttribute(node);
100511                     case 281 /* JsxAttributes */:
100512                         return emitJsxAttributes(node);
100513                     case 282 /* JsxSpreadAttribute */:
100514                         return emitJsxSpreadAttribute(node);
100515                     case 283 /* JsxExpression */:
100516                         return emitJsxExpression(node);
100517                     // Clauses
100518                     case 284 /* CaseClause */:
100519                         return emitCaseClause(node);
100520                     case 285 /* DefaultClause */:
100521                         return emitDefaultClause(node);
100522                     case 286 /* HeritageClause */:
100523                         return emitHeritageClause(node);
100524                     case 287 /* CatchClause */:
100525                         return emitCatchClause(node);
100526                     // Property assignments
100527                     case 288 /* PropertyAssignment */:
100528                         return emitPropertyAssignment(node);
100529                     case 289 /* ShorthandPropertyAssignment */:
100530                         return emitShorthandPropertyAssignment(node);
100531                     case 290 /* SpreadAssignment */:
100532                         return emitSpreadAssignment(node);
100533                     // Enum
100534                     case 291 /* EnumMember */:
100535                         return emitEnumMember(node);
100536                     // JSDoc nodes (only used in codefixes currently)
100537                     case 326 /* JSDocParameterTag */:
100538                     case 333 /* JSDocPropertyTag */:
100539                         return emitJSDocPropertyLikeTag(node);
100540                     case 327 /* JSDocReturnTag */:
100541                     case 329 /* JSDocTypeTag */:
100542                     case 328 /* JSDocThisTag */:
100543                     case 325 /* JSDocEnumTag */:
100544                         return emitJSDocSimpleTypedTag(node);
100545                     case 316 /* JSDocImplementsTag */:
100546                     case 315 /* JSDocAugmentsTag */:
100547                         return emitJSDocHeritageTag(node);
100548                     case 330 /* JSDocTemplateTag */:
100549                         return emitJSDocTemplateTag(node);
100550                     case 331 /* JSDocTypedefTag */:
100551                         return emitJSDocTypedefTag(node);
100552                     case 324 /* JSDocCallbackTag */:
100553                         return emitJSDocCallbackTag(node);
100554                     case 313 /* JSDocSignature */:
100555                         return emitJSDocSignature(node);
100556                     case 312 /* JSDocTypeLiteral */:
100557                         return emitJSDocTypeLiteral(node);
100558                     case 319 /* JSDocClassTag */:
100559                     case 314 /* JSDocTag */:
100560                         return emitJSDocSimpleTag(node);
100561                     case 332 /* JSDocSeeTag */:
100562                         return emitJSDocSeeTag(node);
100563                     case 302 /* JSDocNameReference */:
100564                         return emitJSDocNameReference(node);
100565                     case 311 /* JSDocComment */:
100566                         return emitJSDoc(node);
100567                     // Transformation nodes (ignored)
100568                 }
100569                 if (ts.isExpression(node)) {
100570                     hint = 1 /* Expression */;
100571                     if (substituteNode !== ts.noEmitSubstitution) {
100572                         lastSubstitution = node = substituteNode(hint, node);
100573                     }
100574                 }
100575                 else if (ts.isToken(node)) {
100576                     return writeTokenNode(node, writePunctuation);
100577                 }
100578             }
100579             if (hint === 1 /* Expression */) {
100580                 switch (node.kind) {
100581                     // Literals
100582                     case 8 /* NumericLiteral */:
100583                     case 9 /* BigIntLiteral */:
100584                         return emitNumericOrBigIntLiteral(node);
100585                     case 10 /* StringLiteral */:
100586                     case 13 /* RegularExpressionLiteral */:
100587                     case 14 /* NoSubstitutionTemplateLiteral */:
100588                         return emitLiteral(node, /*jsxAttributeEscape*/ false);
100589                     // Identifiers
100590                     case 78 /* Identifier */:
100591                         return emitIdentifier(node);
100592                     // Reserved words
100593                     case 94 /* FalseKeyword */:
100594                     case 103 /* NullKeyword */:
100595                     case 105 /* SuperKeyword */:
100596                     case 109 /* TrueKeyword */:
100597                     case 107 /* ThisKeyword */:
100598                     case 99 /* ImportKeyword */:
100599                         writeTokenNode(node, writeKeyword);
100600                         return;
100601                     // Expressions
100602                     case 199 /* ArrayLiteralExpression */:
100603                         return emitArrayLiteralExpression(node);
100604                     case 200 /* ObjectLiteralExpression */:
100605                         return emitObjectLiteralExpression(node);
100606                     case 201 /* PropertyAccessExpression */:
100607                         return emitPropertyAccessExpression(node);
100608                     case 202 /* ElementAccessExpression */:
100609                         return emitElementAccessExpression(node);
100610                     case 203 /* CallExpression */:
100611                         return emitCallExpression(node);
100612                     case 204 /* NewExpression */:
100613                         return emitNewExpression(node);
100614                     case 205 /* TaggedTemplateExpression */:
100615                         return emitTaggedTemplateExpression(node);
100616                     case 206 /* TypeAssertionExpression */:
100617                         return emitTypeAssertionExpression(node);
100618                     case 207 /* ParenthesizedExpression */:
100619                         return emitParenthesizedExpression(node);
100620                     case 208 /* FunctionExpression */:
100621                         return emitFunctionExpression(node);
100622                     case 209 /* ArrowFunction */:
100623                         return emitArrowFunction(node);
100624                     case 210 /* DeleteExpression */:
100625                         return emitDeleteExpression(node);
100626                     case 211 /* TypeOfExpression */:
100627                         return emitTypeOfExpression(node);
100628                     case 212 /* VoidExpression */:
100629                         return emitVoidExpression(node);
100630                     case 213 /* AwaitExpression */:
100631                         return emitAwaitExpression(node);
100632                     case 214 /* PrefixUnaryExpression */:
100633                         return emitPrefixUnaryExpression(node);
100634                     case 215 /* PostfixUnaryExpression */:
100635                         return emitPostfixUnaryExpression(node);
100636                     case 216 /* BinaryExpression */:
100637                         return emitBinaryExpression(node);
100638                     case 217 /* ConditionalExpression */:
100639                         return emitConditionalExpression(node);
100640                     case 218 /* TemplateExpression */:
100641                         return emitTemplateExpression(node);
100642                     case 219 /* YieldExpression */:
100643                         return emitYieldExpression(node);
100644                     case 220 /* SpreadElement */:
100645                         return emitSpreadExpression(node);
100646                     case 221 /* ClassExpression */:
100647                         return emitClassExpression(node);
100648                     case 222 /* OmittedExpression */:
100649                         return;
100650                     case 224 /* AsExpression */:
100651                         return emitAsExpression(node);
100652                     case 225 /* NonNullExpression */:
100653                         return emitNonNullExpression(node);
100654                     case 226 /* MetaProperty */:
100655                         return emitMetaProperty(node);
100656                     // JSX
100657                     case 273 /* JsxElement */:
100658                         return emitJsxElement(node);
100659                     case 274 /* JsxSelfClosingElement */:
100660                         return emitJsxSelfClosingElement(node);
100661                     case 277 /* JsxFragment */:
100662                         return emitJsxFragment(node);
100663                     // Transformation nodes
100664                     case 336 /* PartiallyEmittedExpression */:
100665                         return emitPartiallyEmittedExpression(node);
100666                     case 337 /* CommaListExpression */:
100667                         return emitCommaList(node);
100668                 }
100669             }
100670         }
100671         function emitMappedTypeParameter(node) {
100672             emit(node.name);
100673             writeSpace();
100674             writeKeyword("in");
100675             writeSpace();
100676             emit(node.constraint);
100677         }
100678         function pipelineEmitWithSubstitution(hint, node) {
100679             ts.Debug.assert(lastNode === node || lastSubstitution === node);
100680             var pipelinePhase = getNextPipelinePhase(1 /* Substitution */, hint, node);
100681             pipelinePhase(hint, lastSubstitution);
100682             ts.Debug.assert(lastNode === node || lastSubstitution === node);
100683         }
100684         function getHelpersFromBundledSourceFiles(bundle) {
100685             var result;
100686             if (moduleKind === ts.ModuleKind.None || printerOptions.noEmitHelpers) {
100687                 return undefined;
100688             }
100689             var bundledHelpers = new ts.Map();
100690             for (var _a = 0, _b = bundle.sourceFiles; _a < _b.length; _a++) {
100691                 var sourceFile = _b[_a];
100692                 var shouldSkip = ts.getExternalHelpersModuleName(sourceFile) !== undefined;
100693                 var helpers = getSortedEmitHelpers(sourceFile);
100694                 if (!helpers)
100695                     continue;
100696                 for (var _c = 0, helpers_5 = helpers; _c < helpers_5.length; _c++) {
100697                     var helper = helpers_5[_c];
100698                     if (!helper.scoped && !shouldSkip && !bundledHelpers.get(helper.name)) {
100699                         bundledHelpers.set(helper.name, true);
100700                         (result || (result = [])).push(helper.name);
100701                     }
100702                 }
100703             }
100704             return result;
100705         }
100706         function emitHelpers(node) {
100707             var helpersEmitted = false;
100708             var bundle = node.kind === 298 /* Bundle */ ? node : undefined;
100709             if (bundle && moduleKind === ts.ModuleKind.None) {
100710                 return;
100711             }
100712             var numPrepends = bundle ? bundle.prepends.length : 0;
100713             var numNodes = bundle ? bundle.sourceFiles.length + numPrepends : 1;
100714             for (var i = 0; i < numNodes; i++) {
100715                 var currentNode = bundle ? i < numPrepends ? bundle.prepends[i] : bundle.sourceFiles[i - numPrepends] : node;
100716                 var sourceFile = ts.isSourceFile(currentNode) ? currentNode : ts.isUnparsedSource(currentNode) ? undefined : currentSourceFile;
100717                 var shouldSkip = printerOptions.noEmitHelpers || (!!sourceFile && ts.hasRecordedExternalHelpers(sourceFile));
100718                 var shouldBundle = (ts.isSourceFile(currentNode) || ts.isUnparsedSource(currentNode)) && !isOwnFileEmit;
100719                 var helpers = ts.isUnparsedSource(currentNode) ? currentNode.helpers : getSortedEmitHelpers(currentNode);
100720                 if (helpers) {
100721                     for (var _a = 0, helpers_6 = helpers; _a < helpers_6.length; _a++) {
100722                         var helper = helpers_6[_a];
100723                         if (!helper.scoped) {
100724                             // Skip the helper if it can be skipped and the noEmitHelpers compiler
100725                             // option is set, or if it can be imported and the importHelpers compiler
100726                             // option is set.
100727                             if (shouldSkip)
100728                                 continue;
100729                             // Skip the helper if it can be bundled but hasn't already been emitted and we
100730                             // are emitting a bundled module.
100731                             if (shouldBundle) {
100732                                 if (bundledHelpers.get(helper.name)) {
100733                                     continue;
100734                                 }
100735                                 bundledHelpers.set(helper.name, true);
100736                             }
100737                         }
100738                         else if (bundle) {
100739                             // Skip the helper if it is scoped and we are emitting bundled helpers
100740                             continue;
100741                         }
100742                         var pos = getTextPosWithWriteLine();
100743                         if (typeof helper.text === "string") {
100744                             writeLines(helper.text);
100745                         }
100746                         else {
100747                             writeLines(helper.text(makeFileLevelOptimisticUniqueName));
100748                         }
100749                         if (bundleFileInfo)
100750                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "emitHelpers" /* EmitHelpers */, data: helper.name });
100751                         helpersEmitted = true;
100752                     }
100753                 }
100754             }
100755             return helpersEmitted;
100756         }
100757         function getSortedEmitHelpers(node) {
100758             var helpers = ts.getEmitHelpers(node);
100759             return helpers && ts.stableSort(helpers, ts.compareEmitHelpers);
100760         }
100761         //
100762         // Literals/Pseudo-literals
100763         //
100764         // SyntaxKind.NumericLiteral
100765         // SyntaxKind.BigIntLiteral
100766         function emitNumericOrBigIntLiteral(node) {
100767             emitLiteral(node, /*jsxAttributeEscape*/ false);
100768         }
100769         // SyntaxKind.StringLiteral
100770         // SyntaxKind.RegularExpressionLiteral
100771         // SyntaxKind.NoSubstitutionTemplateLiteral
100772         // SyntaxKind.TemplateHead
100773         // SyntaxKind.TemplateMiddle
100774         // SyntaxKind.TemplateTail
100775         function emitLiteral(node, jsxAttributeEscape) {
100776             var text = getLiteralTextOfNode(node, printerOptions.neverAsciiEscape, jsxAttributeEscape);
100777             if ((printerOptions.sourceMap || printerOptions.inlineSourceMap)
100778                 && (node.kind === 10 /* StringLiteral */ || ts.isTemplateLiteralKind(node.kind))) {
100779                 writeLiteral(text);
100780             }
100781             else {
100782                 // Quick info expects all literals to be called with writeStringLiteral, as there's no specific type for numberLiterals
100783                 writeStringLiteral(text);
100784             }
100785         }
100786         // SyntaxKind.UnparsedSource
100787         // SyntaxKind.UnparsedPrepend
100788         function emitUnparsedSourceOrPrepend(unparsed) {
100789             for (var _a = 0, _b = unparsed.texts; _a < _b.length; _a++) {
100790                 var text = _b[_a];
100791                 writeLine();
100792                 emit(text);
100793             }
100794         }
100795         // SyntaxKind.UnparsedPrologue
100796         // SyntaxKind.UnparsedText
100797         // SyntaxKind.UnparsedInternal
100798         // SyntaxKind.UnparsedSyntheticReference
100799         function writeUnparsedNode(unparsed) {
100800             writer.rawWrite(unparsed.parent.text.substring(unparsed.pos, unparsed.end));
100801         }
100802         // SyntaxKind.UnparsedText
100803         // SyntaxKind.UnparsedInternal
100804         function emitUnparsedTextLike(unparsed) {
100805             var pos = getTextPosWithWriteLine();
100806             writeUnparsedNode(unparsed);
100807             if (bundleFileInfo) {
100808                 updateOrPushBundleFileTextLike(pos, writer.getTextPos(), unparsed.kind === 294 /* UnparsedText */ ?
100809                     "text" /* Text */ :
100810                     "internal" /* Internal */);
100811             }
100812         }
100813         // SyntaxKind.UnparsedSyntheticReference
100814         function emitUnparsedSyntheticReference(unparsed) {
100815             var pos = getTextPosWithWriteLine();
100816             writeUnparsedNode(unparsed);
100817             if (bundleFileInfo) {
100818                 var section = ts.clone(unparsed.section);
100819                 section.pos = pos;
100820                 section.end = writer.getTextPos();
100821                 bundleFileInfo.sections.push(section);
100822             }
100823         }
100824         //
100825         // Identifiers
100826         //
100827         function emitIdentifier(node) {
100828             var writeText = node.symbol ? writeSymbol : write;
100829             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
100830             emitList(node, node.typeArguments, 53776 /* TypeParameters */); // Call emitList directly since it could be an array of TypeParameterDeclarations _or_ type arguments
100831         }
100832         //
100833         // Names
100834         //
100835         function emitPrivateIdentifier(node) {
100836             var writeText = node.symbol ? writeSymbol : write;
100837             writeText(getTextOfNode(node, /*includeTrivia*/ false), node.symbol);
100838         }
100839         function emitQualifiedName(node) {
100840             emitEntityName(node.left);
100841             writePunctuation(".");
100842             emit(node.right);
100843         }
100844         function emitEntityName(node) {
100845             if (node.kind === 78 /* Identifier */) {
100846                 emitExpression(node);
100847             }
100848             else {
100849                 emit(node);
100850             }
100851         }
100852         function emitComputedPropertyName(node) {
100853             writePunctuation("[");
100854             emitExpression(node.expression);
100855             writePunctuation("]");
100856         }
100857         //
100858         // Signature elements
100859         //
100860         function emitTypeParameter(node) {
100861             emit(node.name);
100862             if (node.constraint) {
100863                 writeSpace();
100864                 writeKeyword("extends");
100865                 writeSpace();
100866                 emit(node.constraint);
100867             }
100868             if (node.default) {
100869                 writeSpace();
100870                 writeOperator("=");
100871                 writeSpace();
100872                 emit(node.default);
100873             }
100874         }
100875         function emitParameter(node) {
100876             emitDecorators(node, node.decorators);
100877             emitModifiers(node, node.modifiers);
100878             emit(node.dotDotDotToken);
100879             emitNodeWithWriter(node.name, writeParameter);
100880             emit(node.questionToken);
100881             if (node.parent && node.parent.kind === 308 /* JSDocFunctionType */ && !node.name) {
100882                 emit(node.type);
100883             }
100884             else {
100885                 emitTypeAnnotation(node.type);
100886             }
100887             // 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.
100888             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);
100889         }
100890         function emitDecorator(decorator) {
100891             writePunctuation("@");
100892             emitExpression(decorator.expression);
100893         }
100894         //
100895         // Type members
100896         //
100897         function emitPropertySignature(node) {
100898             emitDecorators(node, node.decorators);
100899             emitModifiers(node, node.modifiers);
100900             emitNodeWithWriter(node.name, writeProperty);
100901             emit(node.questionToken);
100902             emitTypeAnnotation(node.type);
100903             writeTrailingSemicolon();
100904         }
100905         function emitPropertyDeclaration(node) {
100906             emitDecorators(node, node.decorators);
100907             emitModifiers(node, node.modifiers);
100908             emit(node.name);
100909             emit(node.questionToken);
100910             emit(node.exclamationToken);
100911             emitTypeAnnotation(node.type);
100912             emitInitializer(node.initializer, node.type ? node.type.end : node.questionToken ? node.questionToken.end : node.name.end, node);
100913             writeTrailingSemicolon();
100914         }
100915         function emitMethodSignature(node) {
100916             pushNameGenerationScope(node);
100917             emitDecorators(node, node.decorators);
100918             emitModifiers(node, node.modifiers);
100919             emit(node.name);
100920             emit(node.questionToken);
100921             emitTypeParameters(node, node.typeParameters);
100922             emitParameters(node, node.parameters);
100923             emitTypeAnnotation(node.type);
100924             writeTrailingSemicolon();
100925             popNameGenerationScope(node);
100926         }
100927         function emitMethodDeclaration(node) {
100928             emitDecorators(node, node.decorators);
100929             emitModifiers(node, node.modifiers);
100930             emit(node.asteriskToken);
100931             emit(node.name);
100932             emit(node.questionToken);
100933             emitSignatureAndBody(node, emitSignatureHead);
100934         }
100935         function emitConstructor(node) {
100936             emitModifiers(node, node.modifiers);
100937             writeKeyword("constructor");
100938             emitSignatureAndBody(node, emitSignatureHead);
100939         }
100940         function emitAccessorDeclaration(node) {
100941             emitDecorators(node, node.decorators);
100942             emitModifiers(node, node.modifiers);
100943             writeKeyword(node.kind === 167 /* GetAccessor */ ? "get" : "set");
100944             writeSpace();
100945             emit(node.name);
100946             emitSignatureAndBody(node, emitSignatureHead);
100947         }
100948         function emitCallSignature(node) {
100949             pushNameGenerationScope(node);
100950             emitDecorators(node, node.decorators);
100951             emitModifiers(node, node.modifiers);
100952             emitTypeParameters(node, node.typeParameters);
100953             emitParameters(node, node.parameters);
100954             emitTypeAnnotation(node.type);
100955             writeTrailingSemicolon();
100956             popNameGenerationScope(node);
100957         }
100958         function emitConstructSignature(node) {
100959             pushNameGenerationScope(node);
100960             emitDecorators(node, node.decorators);
100961             emitModifiers(node, node.modifiers);
100962             writeKeyword("new");
100963             writeSpace();
100964             emitTypeParameters(node, node.typeParameters);
100965             emitParameters(node, node.parameters);
100966             emitTypeAnnotation(node.type);
100967             writeTrailingSemicolon();
100968             popNameGenerationScope(node);
100969         }
100970         function emitIndexSignature(node) {
100971             emitDecorators(node, node.decorators);
100972             emitModifiers(node, node.modifiers);
100973             emitParametersForIndexSignature(node, node.parameters);
100974             emitTypeAnnotation(node.type);
100975             writeTrailingSemicolon();
100976         }
100977         function emitTemplateTypeSpan(node) {
100978             emit(node.type);
100979             emit(node.literal);
100980         }
100981         function emitSemicolonClassElement() {
100982             writeTrailingSemicolon();
100983         }
100984         //
100985         // Types
100986         //
100987         function emitTypePredicate(node) {
100988             if (node.assertsModifier) {
100989                 emit(node.assertsModifier);
100990                 writeSpace();
100991             }
100992             emit(node.parameterName);
100993             if (node.type) {
100994                 writeSpace();
100995                 writeKeyword("is");
100996                 writeSpace();
100997                 emit(node.type);
100998             }
100999         }
101000         function emitTypeReference(node) {
101001             emit(node.typeName);
101002             emitTypeArguments(node, node.typeArguments);
101003         }
101004         function emitFunctionType(node) {
101005             pushNameGenerationScope(node);
101006             emitTypeParameters(node, node.typeParameters);
101007             emitParametersForArrow(node, node.parameters);
101008             writeSpace();
101009             writePunctuation("=>");
101010             writeSpace();
101011             emit(node.type);
101012             popNameGenerationScope(node);
101013         }
101014         function emitJSDocFunctionType(node) {
101015             writeKeyword("function");
101016             emitParameters(node, node.parameters);
101017             writePunctuation(":");
101018             emit(node.type);
101019         }
101020         function emitJSDocNullableType(node) {
101021             writePunctuation("?");
101022             emit(node.type);
101023         }
101024         function emitJSDocNonNullableType(node) {
101025             writePunctuation("!");
101026             emit(node.type);
101027         }
101028         function emitJSDocOptionalType(node) {
101029             emit(node.type);
101030             writePunctuation("=");
101031         }
101032         function emitConstructorType(node) {
101033             pushNameGenerationScope(node);
101034             writeKeyword("new");
101035             writeSpace();
101036             emitTypeParameters(node, node.typeParameters);
101037             emitParameters(node, node.parameters);
101038             writeSpace();
101039             writePunctuation("=>");
101040             writeSpace();
101041             emit(node.type);
101042             popNameGenerationScope(node);
101043         }
101044         function emitTypeQuery(node) {
101045             writeKeyword("typeof");
101046             writeSpace();
101047             emit(node.exprName);
101048         }
101049         function emitTypeLiteral(node) {
101050             writePunctuation("{");
101051             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineTypeLiteralMembers */ : 32897 /* MultiLineTypeLiteralMembers */;
101052             emitList(node, node.members, flags | 524288 /* NoSpaceIfEmpty */);
101053             writePunctuation("}");
101054         }
101055         function emitArrayType(node) {
101056             emit(node.elementType);
101057             writePunctuation("[");
101058             writePunctuation("]");
101059         }
101060         function emitRestOrJSDocVariadicType(node) {
101061             writePunctuation("...");
101062             emit(node.type);
101063         }
101064         function emitTupleType(node) {
101065             emitTokenWithComment(22 /* OpenBracketToken */, node.pos, writePunctuation, node);
101066             var flags = ts.getEmitFlags(node) & 1 /* SingleLine */ ? 528 /* SingleLineTupleTypeElements */ : 657 /* MultiLineTupleTypeElements */;
101067             emitList(node, node.elements, flags | 524288 /* NoSpaceIfEmpty */);
101068             emitTokenWithComment(23 /* CloseBracketToken */, node.elements.end, writePunctuation, node);
101069         }
101070         function emitNamedTupleMember(node) {
101071             emit(node.dotDotDotToken);
101072             emit(node.name);
101073             emit(node.questionToken);
101074             emitTokenWithComment(58 /* ColonToken */, node.name.end, writePunctuation, node);
101075             writeSpace();
101076             emit(node.type);
101077         }
101078         function emitOptionalType(node) {
101079             emit(node.type);
101080             writePunctuation("?");
101081         }
101082         function emitUnionType(node) {
101083             emitList(node, node.types, 516 /* UnionTypeConstituents */);
101084         }
101085         function emitIntersectionType(node) {
101086             emitList(node, node.types, 520 /* IntersectionTypeConstituents */);
101087         }
101088         function emitConditionalType(node) {
101089             emit(node.checkType);
101090             writeSpace();
101091             writeKeyword("extends");
101092             writeSpace();
101093             emit(node.extendsType);
101094             writeSpace();
101095             writePunctuation("?");
101096             writeSpace();
101097             emit(node.trueType);
101098             writeSpace();
101099             writePunctuation(":");
101100             writeSpace();
101101             emit(node.falseType);
101102         }
101103         function emitInferType(node) {
101104             writeKeyword("infer");
101105             writeSpace();
101106             emit(node.typeParameter);
101107         }
101108         function emitParenthesizedType(node) {
101109             writePunctuation("(");
101110             emit(node.type);
101111             writePunctuation(")");
101112         }
101113         function emitThisType() {
101114             writeKeyword("this");
101115         }
101116         function emitTypeOperator(node) {
101117             writeTokenText(node.operator, writeKeyword);
101118             writeSpace();
101119             emit(node.type);
101120         }
101121         function emitIndexedAccessType(node) {
101122             emit(node.objectType);
101123             writePunctuation("[");
101124             emit(node.indexType);
101125             writePunctuation("]");
101126         }
101127         function emitMappedType(node) {
101128             var emitFlags = ts.getEmitFlags(node);
101129             writePunctuation("{");
101130             if (emitFlags & 1 /* SingleLine */) {
101131                 writeSpace();
101132             }
101133             else {
101134                 writeLine();
101135                 increaseIndent();
101136             }
101137             if (node.readonlyToken) {
101138                 emit(node.readonlyToken);
101139                 if (node.readonlyToken.kind !== 142 /* ReadonlyKeyword */) {
101140                     writeKeyword("readonly");
101141                 }
101142                 writeSpace();
101143             }
101144             writePunctuation("[");
101145             pipelineEmit(3 /* MappedTypeParameter */, node.typeParameter);
101146             if (node.nameType) {
101147                 writeSpace();
101148                 writeKeyword("as");
101149                 writeSpace();
101150                 emit(node.nameType);
101151             }
101152             writePunctuation("]");
101153             if (node.questionToken) {
101154                 emit(node.questionToken);
101155                 if (node.questionToken.kind !== 57 /* QuestionToken */) {
101156                     writePunctuation("?");
101157                 }
101158             }
101159             writePunctuation(":");
101160             writeSpace();
101161             emit(node.type);
101162             writeTrailingSemicolon();
101163             if (emitFlags & 1 /* SingleLine */) {
101164                 writeSpace();
101165             }
101166             else {
101167                 writeLine();
101168                 decreaseIndent();
101169             }
101170             writePunctuation("}");
101171         }
101172         function emitLiteralType(node) {
101173             emitExpression(node.literal);
101174         }
101175         function emitTemplateType(node) {
101176             emit(node.head);
101177             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
101178         }
101179         function emitImportTypeNode(node) {
101180             if (node.isTypeOf) {
101181                 writeKeyword("typeof");
101182                 writeSpace();
101183             }
101184             writeKeyword("import");
101185             writePunctuation("(");
101186             emit(node.argument);
101187             writePunctuation(")");
101188             if (node.qualifier) {
101189                 writePunctuation(".");
101190                 emit(node.qualifier);
101191             }
101192             emitTypeArguments(node, node.typeArguments);
101193         }
101194         //
101195         // Binding patterns
101196         //
101197         function emitObjectBindingPattern(node) {
101198             writePunctuation("{");
101199             emitList(node, node.elements, 525136 /* ObjectBindingPatternElements */);
101200             writePunctuation("}");
101201         }
101202         function emitArrayBindingPattern(node) {
101203             writePunctuation("[");
101204             emitList(node, node.elements, 524880 /* ArrayBindingPatternElements */);
101205             writePunctuation("]");
101206         }
101207         function emitBindingElement(node) {
101208             emit(node.dotDotDotToken);
101209             if (node.propertyName) {
101210                 emit(node.propertyName);
101211                 writePunctuation(":");
101212                 writeSpace();
101213             }
101214             emit(node.name);
101215             emitInitializer(node.initializer, node.name.end, node);
101216         }
101217         //
101218         // Expressions
101219         //
101220         function emitArrayLiteralExpression(node) {
101221             var elements = node.elements;
101222             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
101223             emitExpressionList(node, elements, 8914 /* ArrayLiteralExpressionElements */ | preferNewLine);
101224         }
101225         function emitObjectLiteralExpression(node) {
101226             ts.forEach(node.properties, generateMemberNames);
101227             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
101228             if (indentedFlag) {
101229                 increaseIndent();
101230             }
101231             var preferNewLine = node.multiLine ? 65536 /* PreferNewLine */ : 0 /* None */;
101232             var allowTrailingComma = currentSourceFile.languageVersion >= 1 /* ES5 */ && !ts.isJsonSourceFile(currentSourceFile) ? 64 /* AllowTrailingComma */ : 0 /* None */;
101233             emitList(node, node.properties, 526226 /* ObjectLiteralExpressionProperties */ | allowTrailingComma | preferNewLine);
101234             if (indentedFlag) {
101235                 decreaseIndent();
101236             }
101237         }
101238         function emitPropertyAccessExpression(node) {
101239             var expression = ts.cast(emitExpression(node.expression), ts.isExpression);
101240             var token = node.questionDotToken || ts.setTextRangePosEnd(ts.factory.createToken(24 /* DotToken */), node.expression.end, node.name.pos);
101241             var linesBeforeDot = getLinesBetweenNodes(node, node.expression, token);
101242             var linesAfterDot = getLinesBetweenNodes(node, token, node.name);
101243             writeLinesAndIndent(linesBeforeDot, /*writeSpaceIfNotIndenting*/ false);
101244             var shouldEmitDotDot = token.kind !== 28 /* QuestionDotToken */ &&
101245                 mayNeedDotDotForPropertyAccess(expression) &&
101246                 !writer.hasTrailingComment() &&
101247                 !writer.hasTrailingWhitespace();
101248             if (shouldEmitDotDot) {
101249                 writePunctuation(".");
101250             }
101251             if (node.questionDotToken) {
101252                 emit(token);
101253             }
101254             else {
101255                 emitTokenWithComment(token.kind, node.expression.end, writePunctuation, node);
101256             }
101257             writeLinesAndIndent(linesAfterDot, /*writeSpaceIfNotIndenting*/ false);
101258             emit(node.name);
101259             decreaseIndentIf(linesBeforeDot, linesAfterDot);
101260         }
101261         // 1..toString is a valid property access, emit a dot after the literal
101262         // Also emit a dot if expression is a integer const enum value - it will appear in generated code as numeric literal
101263         function mayNeedDotDotForPropertyAccess(expression) {
101264             expression = ts.skipPartiallyEmittedExpressions(expression);
101265             if (ts.isNumericLiteral(expression)) {
101266                 // check if numeric literal is a decimal literal that was originally written with a dot
101267                 var text = getLiteralTextOfNode(expression, /*neverAsciiEscape*/ true, /*jsxAttributeEscape*/ false);
101268                 // If he number will be printed verbatim and it doesn't already contain a dot, add one
101269                 // if the expression doesn't have any comments that will be emitted.
101270                 return !expression.numericLiteralFlags && !ts.stringContains(text, ts.tokenToString(24 /* DotToken */));
101271             }
101272             else if (ts.isAccessExpression(expression)) {
101273                 // check if constant enum value is integer
101274                 var constantValue = ts.getConstantValue(expression);
101275                 // isFinite handles cases when constantValue is undefined
101276                 return typeof constantValue === "number" && isFinite(constantValue)
101277                     && Math.floor(constantValue) === constantValue;
101278             }
101279         }
101280         function emitElementAccessExpression(node) {
101281             emitExpression(node.expression);
101282             emit(node.questionDotToken);
101283             emitTokenWithComment(22 /* OpenBracketToken */, node.expression.end, writePunctuation, node);
101284             emitExpression(node.argumentExpression);
101285             emitTokenWithComment(23 /* CloseBracketToken */, node.argumentExpression.end, writePunctuation, node);
101286         }
101287         function emitCallExpression(node) {
101288             emitExpression(node.expression);
101289             emit(node.questionDotToken);
101290             emitTypeArguments(node, node.typeArguments);
101291             emitExpressionList(node, node.arguments, 2576 /* CallExpressionArguments */);
101292         }
101293         function emitNewExpression(node) {
101294             emitTokenWithComment(102 /* NewKeyword */, node.pos, writeKeyword, node);
101295             writeSpace();
101296             emitExpression(node.expression);
101297             emitTypeArguments(node, node.typeArguments);
101298             emitExpressionList(node, node.arguments, 18960 /* NewExpressionArguments */);
101299         }
101300         function emitTaggedTemplateExpression(node) {
101301             emitExpression(node.tag);
101302             emitTypeArguments(node, node.typeArguments);
101303             writeSpace();
101304             emitExpression(node.template);
101305         }
101306         function emitTypeAssertionExpression(node) {
101307             writePunctuation("<");
101308             emit(node.type);
101309             writePunctuation(">");
101310             emitExpression(node.expression);
101311         }
101312         function emitParenthesizedExpression(node) {
101313             var openParenPos = emitTokenWithComment(20 /* OpenParenToken */, node.pos, writePunctuation, node);
101314             var indented = writeLineSeparatorsAndIndentBefore(node.expression, node);
101315             emitExpression(node.expression);
101316             writeLineSeparatorsAfter(node.expression, node);
101317             decreaseIndentIf(indented);
101318             emitTokenWithComment(21 /* CloseParenToken */, node.expression ? node.expression.end : openParenPos, writePunctuation, node);
101319         }
101320         function emitFunctionExpression(node) {
101321             generateNameIfNeeded(node.name);
101322             emitFunctionDeclarationOrExpression(node);
101323         }
101324         function emitArrowFunction(node) {
101325             emitDecorators(node, node.decorators);
101326             emitModifiers(node, node.modifiers);
101327             emitSignatureAndBody(node, emitArrowFunctionHead);
101328         }
101329         function emitArrowFunctionHead(node) {
101330             emitTypeParameters(node, node.typeParameters);
101331             emitParametersForArrow(node, node.parameters);
101332             emitTypeAnnotation(node.type);
101333             writeSpace();
101334             emit(node.equalsGreaterThanToken);
101335         }
101336         function emitDeleteExpression(node) {
101337             emitTokenWithComment(88 /* DeleteKeyword */, node.pos, writeKeyword, node);
101338             writeSpace();
101339             emitExpression(node.expression);
101340         }
101341         function emitTypeOfExpression(node) {
101342             emitTokenWithComment(111 /* TypeOfKeyword */, node.pos, writeKeyword, node);
101343             writeSpace();
101344             emitExpression(node.expression);
101345         }
101346         function emitVoidExpression(node) {
101347             emitTokenWithComment(113 /* VoidKeyword */, node.pos, writeKeyword, node);
101348             writeSpace();
101349             emitExpression(node.expression);
101350         }
101351         function emitAwaitExpression(node) {
101352             emitTokenWithComment(130 /* AwaitKeyword */, node.pos, writeKeyword, node);
101353             writeSpace();
101354             emitExpression(node.expression);
101355         }
101356         function emitPrefixUnaryExpression(node) {
101357             writeTokenText(node.operator, writeOperator);
101358             if (shouldEmitWhitespaceBeforeOperand(node)) {
101359                 writeSpace();
101360             }
101361             emitExpression(node.operand);
101362         }
101363         function shouldEmitWhitespaceBeforeOperand(node) {
101364             // In some cases, we need to emit a space between the operator and the operand. One obvious case
101365             // is when the operator is an identifier, like delete or typeof. We also need to do this for plus
101366             // and minus expressions in certain cases. Specifically, consider the following two cases (parens
101367             // are just for clarity of exposition, and not part of the source code):
101368             //
101369             //  (+(+1))
101370             //  (+(++1))
101371             //
101372             // We need to emit a space in both cases. In the first case, the absence of a space will make
101373             // the resulting expression a prefix increment operation. And in the second, it will make the resulting
101374             // expression a prefix increment whose operand is a plus expression - (++(+x))
101375             // The same is true of minus of course.
101376             var operand = node.operand;
101377             return operand.kind === 214 /* PrefixUnaryExpression */
101378                 && ((node.operator === 39 /* PlusToken */ && (operand.operator === 39 /* PlusToken */ || operand.operator === 45 /* PlusPlusToken */))
101379                     || (node.operator === 40 /* MinusToken */ && (operand.operator === 40 /* MinusToken */ || operand.operator === 46 /* MinusMinusToken */)));
101380         }
101381         function emitPostfixUnaryExpression(node) {
101382             emitExpression(node.operand);
101383             writeTokenText(node.operator, writeOperator);
101384         }
101385         var EmitBinaryExpressionState;
101386         (function (EmitBinaryExpressionState) {
101387             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitLeft"] = 0] = "EmitLeft";
101388             EmitBinaryExpressionState[EmitBinaryExpressionState["EmitRight"] = 1] = "EmitRight";
101389             EmitBinaryExpressionState[EmitBinaryExpressionState["FinishEmit"] = 2] = "FinishEmit";
101390         })(EmitBinaryExpressionState || (EmitBinaryExpressionState = {}));
101391         /**
101392          * emitBinaryExpression includes an embedded work stack to attempt to handle as many nested binary expressions
101393          * as possible without creating any additional stack frames. This can only be done when the emit pipeline does
101394          * not require notification/substitution/comment/sourcemap decorations.
101395          */
101396         function emitBinaryExpression(node) {
101397             var nodeStack = [node];
101398             var stateStack = [0 /* EmitLeft */];
101399             var stackIndex = 0;
101400             while (stackIndex >= 0) {
101401                 node = nodeStack[stackIndex];
101402                 switch (stateStack[stackIndex]) {
101403                     case 0 /* EmitLeft */: {
101404                         maybePipelineEmitExpression(node.left);
101405                         break;
101406                     }
101407                     case 1 /* EmitRight */: {
101408                         var isCommaOperator = node.operatorToken.kind !== 27 /* CommaToken */;
101409                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
101410                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
101411                         writeLinesAndIndent(linesBeforeOperator, isCommaOperator);
101412                         emitLeadingCommentsOfPosition(node.operatorToken.pos);
101413                         writeTokenNode(node.operatorToken, node.operatorToken.kind === 100 /* InKeyword */ ? writeKeyword : writeOperator);
101414                         emitTrailingCommentsOfPosition(node.operatorToken.end, /*prefixSpace*/ true); // Binary operators should have a space before the comment starts
101415                         writeLinesAndIndent(linesAfterOperator, /*writeSpaceIfNotIndenting*/ true);
101416                         maybePipelineEmitExpression(node.right);
101417                         break;
101418                     }
101419                     case 2 /* FinishEmit */: {
101420                         var linesBeforeOperator = getLinesBetweenNodes(node, node.left, node.operatorToken);
101421                         var linesAfterOperator = getLinesBetweenNodes(node, node.operatorToken, node.right);
101422                         decreaseIndentIf(linesBeforeOperator, linesAfterOperator);
101423                         stackIndex--;
101424                         break;
101425                     }
101426                     default: return ts.Debug.fail("Invalid state " + stateStack[stackIndex] + " for emitBinaryExpressionWorker");
101427                 }
101428             }
101429             function maybePipelineEmitExpression(next) {
101430                 // Advance the state of this unit of work,
101431                 stateStack[stackIndex]++;
101432                 // Then actually do the work of emitting the node `next` returned by the prior state
101433                 // The following section should be identical to `pipelineEmit` save it assumes EmitHint.Expression and offloads
101434                 // binary expression handling, where possible, to the contained work queue
101435                 // #region trampolinePipelineEmit
101436                 var savedLastNode = lastNode;
101437                 var savedLastSubstitution = lastSubstitution;
101438                 lastNode = next;
101439                 lastSubstitution = undefined;
101440                 var pipelinePhase = getPipelinePhase(0 /* Notification */, 1 /* Expression */, next);
101441                 if (pipelinePhase === pipelineEmitWithHint && ts.isBinaryExpression(next)) {
101442                     // If the target pipeline phase is emit directly, and the next node's also a binary expression,
101443                     // skip all the intermediate indirection and push the expression directly onto the work stack
101444                     stackIndex++;
101445                     stateStack[stackIndex] = 0 /* EmitLeft */;
101446                     nodeStack[stackIndex] = next;
101447                 }
101448                 else {
101449                     pipelinePhase(1 /* Expression */, next);
101450                 }
101451                 ts.Debug.assert(lastNode === next);
101452                 lastNode = savedLastNode;
101453                 lastSubstitution = savedLastSubstitution;
101454                 // #endregion trampolinePipelineEmit
101455             }
101456         }
101457         function emitConditionalExpression(node) {
101458             var linesBeforeQuestion = getLinesBetweenNodes(node, node.condition, node.questionToken);
101459             var linesAfterQuestion = getLinesBetweenNodes(node, node.questionToken, node.whenTrue);
101460             var linesBeforeColon = getLinesBetweenNodes(node, node.whenTrue, node.colonToken);
101461             var linesAfterColon = getLinesBetweenNodes(node, node.colonToken, node.whenFalse);
101462             emitExpression(node.condition);
101463             writeLinesAndIndent(linesBeforeQuestion, /*writeSpaceIfNotIndenting*/ true);
101464             emit(node.questionToken);
101465             writeLinesAndIndent(linesAfterQuestion, /*writeSpaceIfNotIndenting*/ true);
101466             emitExpression(node.whenTrue);
101467             decreaseIndentIf(linesBeforeQuestion, linesAfterQuestion);
101468             writeLinesAndIndent(linesBeforeColon, /*writeSpaceIfNotIndenting*/ true);
101469             emit(node.colonToken);
101470             writeLinesAndIndent(linesAfterColon, /*writeSpaceIfNotIndenting*/ true);
101471             emitExpression(node.whenFalse);
101472             decreaseIndentIf(linesBeforeColon, linesAfterColon);
101473         }
101474         function emitTemplateExpression(node) {
101475             emit(node.head);
101476             emitList(node, node.templateSpans, 262144 /* TemplateExpressionSpans */);
101477         }
101478         function emitYieldExpression(node) {
101479             emitTokenWithComment(124 /* YieldKeyword */, node.pos, writeKeyword, node);
101480             emit(node.asteriskToken);
101481             emitExpressionWithLeadingSpace(node.expression);
101482         }
101483         function emitSpreadExpression(node) {
101484             emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
101485             emitExpression(node.expression);
101486         }
101487         function emitClassExpression(node) {
101488             generateNameIfNeeded(node.name);
101489             emitClassDeclarationOrExpression(node);
101490         }
101491         function emitExpressionWithTypeArguments(node) {
101492             emitExpression(node.expression);
101493             emitTypeArguments(node, node.typeArguments);
101494         }
101495         function emitAsExpression(node) {
101496             emitExpression(node.expression);
101497             if (node.type) {
101498                 writeSpace();
101499                 writeKeyword("as");
101500                 writeSpace();
101501                 emit(node.type);
101502             }
101503         }
101504         function emitNonNullExpression(node) {
101505             emitExpression(node.expression);
101506             writeOperator("!");
101507         }
101508         function emitMetaProperty(node) {
101509             writeToken(node.keywordToken, node.pos, writePunctuation);
101510             writePunctuation(".");
101511             emit(node.name);
101512         }
101513         //
101514         // Misc
101515         //
101516         function emitTemplateSpan(node) {
101517             emitExpression(node.expression);
101518             emit(node.literal);
101519         }
101520         //
101521         // Statements
101522         //
101523         function emitBlock(node) {
101524             emitBlockStatements(node, /*forceSingleLine*/ !node.multiLine && isEmptyBlock(node));
101525         }
101526         function emitBlockStatements(node, forceSingleLine) {
101527             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, /*contextNode*/ node);
101528             var format = forceSingleLine || ts.getEmitFlags(node) & 1 /* SingleLine */ ? 768 /* SingleLineBlockStatements */ : 129 /* MultiLineBlockStatements */;
101529             emitList(node, node.statements, format);
101530             emitTokenWithComment(19 /* CloseBraceToken */, node.statements.end, writePunctuation, /*contextNode*/ node, /*indentLeading*/ !!(format & 1 /* MultiLine */));
101531         }
101532         function emitVariableStatement(node) {
101533             emitModifiers(node, node.modifiers);
101534             emit(node.declarationList);
101535             writeTrailingSemicolon();
101536         }
101537         function emitEmptyStatement(isEmbeddedStatement) {
101538             // While most trailing semicolons are possibly insignificant, an embedded "empty"
101539             // statement is significant and cannot be elided by a trailing-semicolon-omitting writer.
101540             if (isEmbeddedStatement) {
101541                 writePunctuation(";");
101542             }
101543             else {
101544                 writeTrailingSemicolon();
101545             }
101546         }
101547         function emitExpressionStatement(node) {
101548             emitExpression(node.expression);
101549             // Emit semicolon in non json files
101550             // or if json file that created synthesized expression(eg.define expression statement when --out and amd code generation)
101551             if (!ts.isJsonSourceFile(currentSourceFile) || ts.nodeIsSynthesized(node.expression)) {
101552                 writeTrailingSemicolon();
101553             }
101554         }
101555         function emitIfStatement(node) {
101556             var openParenPos = emitTokenWithComment(98 /* IfKeyword */, node.pos, writeKeyword, node);
101557             writeSpace();
101558             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101559             emitExpression(node.expression);
101560             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101561             emitEmbeddedStatement(node, node.thenStatement);
101562             if (node.elseStatement) {
101563                 writeLineOrSpace(node, node.thenStatement, node.elseStatement);
101564                 emitTokenWithComment(90 /* ElseKeyword */, node.thenStatement.end, writeKeyword, node);
101565                 if (node.elseStatement.kind === 234 /* IfStatement */) {
101566                     writeSpace();
101567                     emit(node.elseStatement);
101568                 }
101569                 else {
101570                     emitEmbeddedStatement(node, node.elseStatement);
101571                 }
101572             }
101573         }
101574         function emitWhileClause(node, startPos) {
101575             var openParenPos = emitTokenWithComment(114 /* WhileKeyword */, startPos, writeKeyword, node);
101576             writeSpace();
101577             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101578             emitExpression(node.expression);
101579             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101580         }
101581         function emitDoStatement(node) {
101582             emitTokenWithComment(89 /* DoKeyword */, node.pos, writeKeyword, node);
101583             emitEmbeddedStatement(node, node.statement);
101584             if (ts.isBlock(node.statement) && !preserveSourceNewlines) {
101585                 writeSpace();
101586             }
101587             else {
101588                 writeLineOrSpace(node, node.statement, node.expression);
101589             }
101590             emitWhileClause(node, node.statement.end);
101591             writeTrailingSemicolon();
101592         }
101593         function emitWhileStatement(node) {
101594             emitWhileClause(node, node.pos);
101595             emitEmbeddedStatement(node, node.statement);
101596         }
101597         function emitForStatement(node) {
101598             var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
101599             writeSpace();
101600             var pos = emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, /*contextNode*/ node);
101601             emitForBinding(node.initializer);
101602             pos = emitTokenWithComment(26 /* SemicolonToken */, node.initializer ? node.initializer.end : pos, writePunctuation, node);
101603             emitExpressionWithLeadingSpace(node.condition);
101604             pos = emitTokenWithComment(26 /* SemicolonToken */, node.condition ? node.condition.end : pos, writePunctuation, node);
101605             emitExpressionWithLeadingSpace(node.incrementor);
101606             emitTokenWithComment(21 /* CloseParenToken */, node.incrementor ? node.incrementor.end : pos, writePunctuation, node);
101607             emitEmbeddedStatement(node, node.statement);
101608         }
101609         function emitForInStatement(node) {
101610             var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
101611             writeSpace();
101612             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101613             emitForBinding(node.initializer);
101614             writeSpace();
101615             emitTokenWithComment(100 /* InKeyword */, node.initializer.end, writeKeyword, node);
101616             writeSpace();
101617             emitExpression(node.expression);
101618             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101619             emitEmbeddedStatement(node, node.statement);
101620         }
101621         function emitForOfStatement(node) {
101622             var openParenPos = emitTokenWithComment(96 /* ForKeyword */, node.pos, writeKeyword, node);
101623             writeSpace();
101624             emitWithTrailingSpace(node.awaitModifier);
101625             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101626             emitForBinding(node.initializer);
101627             writeSpace();
101628             emitTokenWithComment(156 /* OfKeyword */, node.initializer.end, writeKeyword, node);
101629             writeSpace();
101630             emitExpression(node.expression);
101631             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101632             emitEmbeddedStatement(node, node.statement);
101633         }
101634         function emitForBinding(node) {
101635             if (node !== undefined) {
101636                 if (node.kind === 250 /* VariableDeclarationList */) {
101637                     emit(node);
101638                 }
101639                 else {
101640                     emitExpression(node);
101641                 }
101642             }
101643         }
101644         function emitContinueStatement(node) {
101645             emitTokenWithComment(85 /* ContinueKeyword */, node.pos, writeKeyword, node);
101646             emitWithLeadingSpace(node.label);
101647             writeTrailingSemicolon();
101648         }
101649         function emitBreakStatement(node) {
101650             emitTokenWithComment(80 /* BreakKeyword */, node.pos, writeKeyword, node);
101651             emitWithLeadingSpace(node.label);
101652             writeTrailingSemicolon();
101653         }
101654         function emitTokenWithComment(token, pos, writer, contextNode, indentLeading) {
101655             var node = ts.getParseTreeNode(contextNode);
101656             var isSimilarNode = node && node.kind === contextNode.kind;
101657             var startPos = pos;
101658             if (isSimilarNode && currentSourceFile) {
101659                 pos = ts.skipTrivia(currentSourceFile.text, pos);
101660             }
101661             if (emitLeadingCommentsOfPosition && isSimilarNode && contextNode.pos !== startPos) {
101662                 var needsIndent = indentLeading && currentSourceFile && !ts.positionsAreOnSameLine(startPos, pos, currentSourceFile);
101663                 if (needsIndent) {
101664                     increaseIndent();
101665                 }
101666                 emitLeadingCommentsOfPosition(startPos);
101667                 if (needsIndent) {
101668                     decreaseIndent();
101669                 }
101670             }
101671             pos = writeTokenText(token, writer, pos);
101672             if (emitTrailingCommentsOfPosition && isSimilarNode && contextNode.end !== pos) {
101673                 emitTrailingCommentsOfPosition(pos, /*prefixSpace*/ true);
101674             }
101675             return pos;
101676         }
101677         function emitReturnStatement(node) {
101678             emitTokenWithComment(104 /* ReturnKeyword */, node.pos, writeKeyword, /*contextNode*/ node);
101679             emitExpressionWithLeadingSpace(node.expression);
101680             writeTrailingSemicolon();
101681         }
101682         function emitWithStatement(node) {
101683             var openParenPos = emitTokenWithComment(115 /* WithKeyword */, node.pos, writeKeyword, node);
101684             writeSpace();
101685             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101686             emitExpression(node.expression);
101687             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101688             emitEmbeddedStatement(node, node.statement);
101689         }
101690         function emitSwitchStatement(node) {
101691             var openParenPos = emitTokenWithComment(106 /* SwitchKeyword */, node.pos, writeKeyword, node);
101692             writeSpace();
101693             emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
101694             emitExpression(node.expression);
101695             emitTokenWithComment(21 /* CloseParenToken */, node.expression.end, writePunctuation, node);
101696             writeSpace();
101697             emit(node.caseBlock);
101698         }
101699         function emitLabeledStatement(node) {
101700             emit(node.label);
101701             emitTokenWithComment(58 /* ColonToken */, node.label.end, writePunctuation, node);
101702             writeSpace();
101703             emit(node.statement);
101704         }
101705         function emitThrowStatement(node) {
101706             emitTokenWithComment(108 /* ThrowKeyword */, node.pos, writeKeyword, node);
101707             emitExpressionWithLeadingSpace(node.expression);
101708             writeTrailingSemicolon();
101709         }
101710         function emitTryStatement(node) {
101711             emitTokenWithComment(110 /* TryKeyword */, node.pos, writeKeyword, node);
101712             writeSpace();
101713             emit(node.tryBlock);
101714             if (node.catchClause) {
101715                 writeLineOrSpace(node, node.tryBlock, node.catchClause);
101716                 emit(node.catchClause);
101717             }
101718             if (node.finallyBlock) {
101719                 writeLineOrSpace(node, node.catchClause || node.tryBlock, node.finallyBlock);
101720                 emitTokenWithComment(95 /* FinallyKeyword */, (node.catchClause || node.tryBlock).end, writeKeyword, node);
101721                 writeSpace();
101722                 emit(node.finallyBlock);
101723             }
101724         }
101725         function emitDebuggerStatement(node) {
101726             writeToken(86 /* DebuggerKeyword */, node.pos, writeKeyword);
101727             writeTrailingSemicolon();
101728         }
101729         //
101730         // Declarations
101731         //
101732         function emitVariableDeclaration(node) {
101733             emit(node.name);
101734             emit(node.exclamationToken);
101735             emitTypeAnnotation(node.type);
101736             emitInitializer(node.initializer, node.type ? node.type.end : node.name.end, node);
101737         }
101738         function emitVariableDeclarationList(node) {
101739             writeKeyword(ts.isLet(node) ? "let" : ts.isVarConst(node) ? "const" : "var");
101740             writeSpace();
101741             emitList(node, node.declarations, 528 /* VariableDeclarationList */);
101742         }
101743         function emitFunctionDeclaration(node) {
101744             emitFunctionDeclarationOrExpression(node);
101745         }
101746         function emitFunctionDeclarationOrExpression(node) {
101747             emitDecorators(node, node.decorators);
101748             emitModifiers(node, node.modifiers);
101749             writeKeyword("function");
101750             emit(node.asteriskToken);
101751             writeSpace();
101752             emitIdentifierName(node.name);
101753             emitSignatureAndBody(node, emitSignatureHead);
101754         }
101755         function emitBlockCallback(_hint, body) {
101756             emitBlockFunctionBody(body);
101757         }
101758         function emitSignatureAndBody(node, emitSignatureHead) {
101759             var body = node.body;
101760             if (body) {
101761                 if (ts.isBlock(body)) {
101762                     var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
101763                     if (indentedFlag) {
101764                         increaseIndent();
101765                     }
101766                     pushNameGenerationScope(node);
101767                     ts.forEach(node.parameters, generateNames);
101768                     generateNames(node.body);
101769                     emitSignatureHead(node);
101770                     if (onEmitNode) {
101771                         onEmitNode(4 /* Unspecified */, body, emitBlockCallback);
101772                     }
101773                     else {
101774                         emitBlockFunctionBody(body);
101775                     }
101776                     popNameGenerationScope(node);
101777                     if (indentedFlag) {
101778                         decreaseIndent();
101779                     }
101780                 }
101781                 else {
101782                     emitSignatureHead(node);
101783                     writeSpace();
101784                     emitExpression(body);
101785                 }
101786             }
101787             else {
101788                 emitSignatureHead(node);
101789                 writeTrailingSemicolon();
101790             }
101791         }
101792         function emitSignatureHead(node) {
101793             emitTypeParameters(node, node.typeParameters);
101794             emitParameters(node, node.parameters);
101795             emitTypeAnnotation(node.type);
101796         }
101797         function shouldEmitBlockFunctionBodyOnSingleLine(body) {
101798             // We must emit a function body as a single-line body in the following case:
101799             // * The body has NodeEmitFlags.SingleLine specified.
101800             // We must emit a function body as a multi-line body in the following cases:
101801             // * The body is explicitly marked as multi-line.
101802             // * A non-synthesized body's start and end position are on different lines.
101803             // * Any statement in the body starts on a new line.
101804             if (ts.getEmitFlags(body) & 1 /* SingleLine */) {
101805                 return true;
101806             }
101807             if (body.multiLine) {
101808                 return false;
101809             }
101810             if (!ts.nodeIsSynthesized(body) && !ts.rangeIsOnSingleLine(body, currentSourceFile)) {
101811                 return false;
101812             }
101813             if (getLeadingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)
101814                 || getClosingLineTerminatorCount(body, body.statements, 2 /* PreserveLines */)) {
101815                 return false;
101816             }
101817             var previousStatement;
101818             for (var _a = 0, _b = body.statements; _a < _b.length; _a++) {
101819                 var statement = _b[_a];
101820                 if (getSeparatingLineTerminatorCount(previousStatement, statement, 2 /* PreserveLines */) > 0) {
101821                     return false;
101822                 }
101823                 previousStatement = statement;
101824             }
101825             return true;
101826         }
101827         function emitBlockFunctionBody(body) {
101828             writeSpace();
101829             writePunctuation("{");
101830             increaseIndent();
101831             var emitBlockFunctionBody = shouldEmitBlockFunctionBodyOnSingleLine(body)
101832                 ? emitBlockFunctionBodyOnSingleLine
101833                 : emitBlockFunctionBodyWorker;
101834             if (emitBodyWithDetachedComments) {
101835                 emitBodyWithDetachedComments(body, body.statements, emitBlockFunctionBody);
101836             }
101837             else {
101838                 emitBlockFunctionBody(body);
101839             }
101840             decreaseIndent();
101841             writeToken(19 /* CloseBraceToken */, body.statements.end, writePunctuation, body);
101842         }
101843         function emitBlockFunctionBodyOnSingleLine(body) {
101844             emitBlockFunctionBodyWorker(body, /*emitBlockFunctionBodyOnSingleLine*/ true);
101845         }
101846         function emitBlockFunctionBodyWorker(body, emitBlockFunctionBodyOnSingleLine) {
101847             // Emit all the prologue directives (like "use strict").
101848             var statementOffset = emitPrologueDirectives(body.statements);
101849             var pos = writer.getTextPos();
101850             emitHelpers(body);
101851             if (statementOffset === 0 && pos === writer.getTextPos() && emitBlockFunctionBodyOnSingleLine) {
101852                 decreaseIndent();
101853                 emitList(body, body.statements, 768 /* SingleLineFunctionBodyStatements */);
101854                 increaseIndent();
101855             }
101856             else {
101857                 emitList(body, body.statements, 1 /* MultiLineFunctionBodyStatements */, statementOffset);
101858             }
101859         }
101860         function emitClassDeclaration(node) {
101861             emitClassDeclarationOrExpression(node);
101862         }
101863         function emitClassDeclarationOrExpression(node) {
101864             ts.forEach(node.members, generateMemberNames);
101865             emitDecorators(node, node.decorators);
101866             emitModifiers(node, node.modifiers);
101867             writeKeyword("class");
101868             if (node.name) {
101869                 writeSpace();
101870                 emitIdentifierName(node.name);
101871             }
101872             var indentedFlag = ts.getEmitFlags(node) & 65536 /* Indented */;
101873             if (indentedFlag) {
101874                 increaseIndent();
101875             }
101876             emitTypeParameters(node, node.typeParameters);
101877             emitList(node, node.heritageClauses, 0 /* ClassHeritageClauses */);
101878             writeSpace();
101879             writePunctuation("{");
101880             emitList(node, node.members, 129 /* ClassMembers */);
101881             writePunctuation("}");
101882             if (indentedFlag) {
101883                 decreaseIndent();
101884             }
101885         }
101886         function emitInterfaceDeclaration(node) {
101887             emitDecorators(node, node.decorators);
101888             emitModifiers(node, node.modifiers);
101889             writeKeyword("interface");
101890             writeSpace();
101891             emit(node.name);
101892             emitTypeParameters(node, node.typeParameters);
101893             emitList(node, node.heritageClauses, 512 /* HeritageClauses */);
101894             writeSpace();
101895             writePunctuation("{");
101896             emitList(node, node.members, 129 /* InterfaceMembers */);
101897             writePunctuation("}");
101898         }
101899         function emitTypeAliasDeclaration(node) {
101900             emitDecorators(node, node.decorators);
101901             emitModifiers(node, node.modifiers);
101902             writeKeyword("type");
101903             writeSpace();
101904             emit(node.name);
101905             emitTypeParameters(node, node.typeParameters);
101906             writeSpace();
101907             writePunctuation("=");
101908             writeSpace();
101909             emit(node.type);
101910             writeTrailingSemicolon();
101911         }
101912         function emitEnumDeclaration(node) {
101913             emitModifiers(node, node.modifiers);
101914             writeKeyword("enum");
101915             writeSpace();
101916             emit(node.name);
101917             writeSpace();
101918             writePunctuation("{");
101919             emitList(node, node.members, 145 /* EnumMembers */);
101920             writePunctuation("}");
101921         }
101922         function emitModuleDeclaration(node) {
101923             emitModifiers(node, node.modifiers);
101924             if (~node.flags & 1024 /* GlobalAugmentation */) {
101925                 writeKeyword(node.flags & 16 /* Namespace */ ? "namespace" : "module");
101926                 writeSpace();
101927             }
101928             emit(node.name);
101929             var body = node.body;
101930             if (!body)
101931                 return writeTrailingSemicolon();
101932             while (body.kind === 256 /* ModuleDeclaration */) {
101933                 writePunctuation(".");
101934                 emit(body.name);
101935                 body = body.body;
101936             }
101937             writeSpace();
101938             emit(body);
101939         }
101940         function emitModuleBlock(node) {
101941             pushNameGenerationScope(node);
101942             ts.forEach(node.statements, generateNames);
101943             emitBlockStatements(node, /*forceSingleLine*/ isEmptyBlock(node));
101944             popNameGenerationScope(node);
101945         }
101946         function emitCaseBlock(node) {
101947             emitTokenWithComment(18 /* OpenBraceToken */, node.pos, writePunctuation, node);
101948             emitList(node, node.clauses, 129 /* CaseBlockClauses */);
101949             emitTokenWithComment(19 /* CloseBraceToken */, node.clauses.end, writePunctuation, node, /*indentLeading*/ true);
101950         }
101951         function emitImportEqualsDeclaration(node) {
101952             emitModifiers(node, node.modifiers);
101953             emitTokenWithComment(99 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
101954             writeSpace();
101955             emit(node.name);
101956             writeSpace();
101957             emitTokenWithComment(62 /* EqualsToken */, node.name.end, writePunctuation, node);
101958             writeSpace();
101959             emitModuleReference(node.moduleReference);
101960             writeTrailingSemicolon();
101961         }
101962         function emitModuleReference(node) {
101963             if (node.kind === 78 /* Identifier */) {
101964                 emitExpression(node);
101965             }
101966             else {
101967                 emit(node);
101968             }
101969         }
101970         function emitImportDeclaration(node) {
101971             emitModifiers(node, node.modifiers);
101972             emitTokenWithComment(99 /* ImportKeyword */, node.modifiers ? node.modifiers.end : node.pos, writeKeyword, node);
101973             writeSpace();
101974             if (node.importClause) {
101975                 emit(node.importClause);
101976                 writeSpace();
101977                 emitTokenWithComment(153 /* FromKeyword */, node.importClause.end, writeKeyword, node);
101978                 writeSpace();
101979             }
101980             emitExpression(node.moduleSpecifier);
101981             writeTrailingSemicolon();
101982         }
101983         function emitImportClause(node) {
101984             if (node.isTypeOnly) {
101985                 emitTokenWithComment(149 /* TypeKeyword */, node.pos, writeKeyword, node);
101986                 writeSpace();
101987             }
101988             emit(node.name);
101989             if (node.name && node.namedBindings) {
101990                 emitTokenWithComment(27 /* CommaToken */, node.name.end, writePunctuation, node);
101991                 writeSpace();
101992             }
101993             emit(node.namedBindings);
101994         }
101995         function emitNamespaceImport(node) {
101996             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
101997             writeSpace();
101998             emitTokenWithComment(126 /* AsKeyword */, asPos, writeKeyword, node);
101999             writeSpace();
102000             emit(node.name);
102001         }
102002         function emitNamedImports(node) {
102003             emitNamedImportsOrExports(node);
102004         }
102005         function emitImportSpecifier(node) {
102006             emitImportOrExportSpecifier(node);
102007         }
102008         function emitExportAssignment(node) {
102009             var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
102010             writeSpace();
102011             if (node.isExportEquals) {
102012                 emitTokenWithComment(62 /* EqualsToken */, nextPos, writeOperator, node);
102013             }
102014             else {
102015                 emitTokenWithComment(87 /* DefaultKeyword */, nextPos, writeKeyword, node);
102016             }
102017             writeSpace();
102018             emitExpression(node.expression);
102019             writeTrailingSemicolon();
102020         }
102021         function emitExportDeclaration(node) {
102022             var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
102023             writeSpace();
102024             if (node.isTypeOnly) {
102025                 nextPos = emitTokenWithComment(149 /* TypeKeyword */, nextPos, writeKeyword, node);
102026                 writeSpace();
102027             }
102028             if (node.exportClause) {
102029                 emit(node.exportClause);
102030             }
102031             else {
102032                 nextPos = emitTokenWithComment(41 /* AsteriskToken */, nextPos, writePunctuation, node);
102033             }
102034             if (node.moduleSpecifier) {
102035                 writeSpace();
102036                 var fromPos = node.exportClause ? node.exportClause.end : nextPos;
102037                 emitTokenWithComment(153 /* FromKeyword */, fromPos, writeKeyword, node);
102038                 writeSpace();
102039                 emitExpression(node.moduleSpecifier);
102040             }
102041             writeTrailingSemicolon();
102042         }
102043         function emitNamespaceExportDeclaration(node) {
102044             var nextPos = emitTokenWithComment(92 /* ExportKeyword */, node.pos, writeKeyword, node);
102045             writeSpace();
102046             nextPos = emitTokenWithComment(126 /* AsKeyword */, nextPos, writeKeyword, node);
102047             writeSpace();
102048             nextPos = emitTokenWithComment(140 /* NamespaceKeyword */, nextPos, writeKeyword, node);
102049             writeSpace();
102050             emit(node.name);
102051             writeTrailingSemicolon();
102052         }
102053         function emitNamespaceExport(node) {
102054             var asPos = emitTokenWithComment(41 /* AsteriskToken */, node.pos, writePunctuation, node);
102055             writeSpace();
102056             emitTokenWithComment(126 /* AsKeyword */, asPos, writeKeyword, node);
102057             writeSpace();
102058             emit(node.name);
102059         }
102060         function emitNamedExports(node) {
102061             emitNamedImportsOrExports(node);
102062         }
102063         function emitExportSpecifier(node) {
102064             emitImportOrExportSpecifier(node);
102065         }
102066         function emitNamedImportsOrExports(node) {
102067             writePunctuation("{");
102068             emitList(node, node.elements, 525136 /* NamedImportsOrExportsElements */);
102069             writePunctuation("}");
102070         }
102071         function emitImportOrExportSpecifier(node) {
102072             if (node.propertyName) {
102073                 emit(node.propertyName);
102074                 writeSpace();
102075                 emitTokenWithComment(126 /* AsKeyword */, node.propertyName.end, writeKeyword, node);
102076                 writeSpace();
102077             }
102078             emit(node.name);
102079         }
102080         //
102081         // Module references
102082         //
102083         function emitExternalModuleReference(node) {
102084             writeKeyword("require");
102085             writePunctuation("(");
102086             emitExpression(node.expression);
102087             writePunctuation(")");
102088         }
102089         //
102090         // JSX
102091         //
102092         function emitJsxElement(node) {
102093             emit(node.openingElement);
102094             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
102095             emit(node.closingElement);
102096         }
102097         function emitJsxSelfClosingElement(node) {
102098             writePunctuation("<");
102099             emitJsxTagName(node.tagName);
102100             emitTypeArguments(node, node.typeArguments);
102101             writeSpace();
102102             emit(node.attributes);
102103             writePunctuation("/>");
102104         }
102105         function emitJsxFragment(node) {
102106             emit(node.openingFragment);
102107             emitList(node, node.children, 262144 /* JsxElementOrFragmentChildren */);
102108             emit(node.closingFragment);
102109         }
102110         function emitJsxOpeningElementOrFragment(node) {
102111             writePunctuation("<");
102112             if (ts.isJsxOpeningElement(node)) {
102113                 var indented = writeLineSeparatorsAndIndentBefore(node.tagName, node);
102114                 emitJsxTagName(node.tagName);
102115                 emitTypeArguments(node, node.typeArguments);
102116                 if (node.attributes.properties && node.attributes.properties.length > 0) {
102117                     writeSpace();
102118                 }
102119                 emit(node.attributes);
102120                 writeLineSeparatorsAfter(node.attributes, node);
102121                 decreaseIndentIf(indented);
102122             }
102123             writePunctuation(">");
102124         }
102125         function emitJsxText(node) {
102126             writer.writeLiteral(node.text);
102127         }
102128         function emitJsxClosingElementOrFragment(node) {
102129             writePunctuation("</");
102130             if (ts.isJsxClosingElement(node)) {
102131                 emitJsxTagName(node.tagName);
102132             }
102133             writePunctuation(">");
102134         }
102135         function emitJsxAttributes(node) {
102136             emitList(node, node.properties, 262656 /* JsxElementAttributes */);
102137         }
102138         function emitJsxAttribute(node) {
102139             emit(node.name);
102140             emitNodeWithPrefix("=", writePunctuation, node.initializer, emitJsxAttributeValue);
102141         }
102142         function emitJsxSpreadAttribute(node) {
102143             writePunctuation("{...");
102144             emitExpression(node.expression);
102145             writePunctuation("}");
102146         }
102147         function emitJsxExpression(node) {
102148             if (node.expression) {
102149                 writePunctuation("{");
102150                 emit(node.dotDotDotToken);
102151                 emitExpression(node.expression);
102152                 writePunctuation("}");
102153             }
102154         }
102155         function emitJsxTagName(node) {
102156             if (node.kind === 78 /* Identifier */) {
102157                 emitExpression(node);
102158             }
102159             else {
102160                 emit(node);
102161             }
102162         }
102163         //
102164         // Clauses
102165         //
102166         function emitCaseClause(node) {
102167             emitTokenWithComment(81 /* CaseKeyword */, node.pos, writeKeyword, node);
102168             writeSpace();
102169             emitExpression(node.expression);
102170             emitCaseOrDefaultClauseRest(node, node.statements, node.expression.end);
102171         }
102172         function emitDefaultClause(node) {
102173             var pos = emitTokenWithComment(87 /* DefaultKeyword */, node.pos, writeKeyword, node);
102174             emitCaseOrDefaultClauseRest(node, node.statements, pos);
102175         }
102176         function emitCaseOrDefaultClauseRest(parentNode, statements, colonPos) {
102177             var emitAsSingleStatement = statements.length === 1 &&
102178                 (
102179                 // treat synthesized nodes as located on the same line for emit purposes
102180                 ts.nodeIsSynthesized(parentNode) ||
102181                     ts.nodeIsSynthesized(statements[0]) ||
102182                     ts.rangeStartPositionsAreOnSameLine(parentNode, statements[0], currentSourceFile));
102183             var format = 163969 /* CaseOrDefaultClauseStatements */;
102184             if (emitAsSingleStatement) {
102185                 writeToken(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
102186                 writeSpace();
102187                 format &= ~(1 /* MultiLine */ | 128 /* Indented */);
102188             }
102189             else {
102190                 emitTokenWithComment(58 /* ColonToken */, colonPos, writePunctuation, parentNode);
102191             }
102192             emitList(parentNode, statements, format);
102193         }
102194         function emitHeritageClause(node) {
102195             writeSpace();
102196             writeTokenText(node.token, writeKeyword);
102197             writeSpace();
102198             emitList(node, node.types, 528 /* HeritageClauseTypes */);
102199         }
102200         function emitCatchClause(node) {
102201             var openParenPos = emitTokenWithComment(82 /* CatchKeyword */, node.pos, writeKeyword, node);
102202             writeSpace();
102203             if (node.variableDeclaration) {
102204                 emitTokenWithComment(20 /* OpenParenToken */, openParenPos, writePunctuation, node);
102205                 emit(node.variableDeclaration);
102206                 emitTokenWithComment(21 /* CloseParenToken */, node.variableDeclaration.end, writePunctuation, node);
102207                 writeSpace();
102208             }
102209             emit(node.block);
102210         }
102211         //
102212         // Property assignments
102213         //
102214         function emitPropertyAssignment(node) {
102215             emit(node.name);
102216             writePunctuation(":");
102217             writeSpace();
102218             // This is to ensure that we emit comment in the following case:
102219             //      For example:
102220             //          obj = {
102221             //              id: /*comment1*/ ()=>void
102222             //          }
102223             // "comment1" is not considered to be leading comment for node.initializer
102224             // but rather a trailing comment on the previous node.
102225             var initializer = node.initializer;
102226             if (emitTrailingCommentsOfPosition && (ts.getEmitFlags(initializer) & 512 /* NoLeadingComments */) === 0) {
102227                 var commentRange = ts.getCommentRange(initializer);
102228                 emitTrailingCommentsOfPosition(commentRange.pos);
102229             }
102230             emitExpression(initializer);
102231         }
102232         function emitShorthandPropertyAssignment(node) {
102233             emit(node.name);
102234             if (node.objectAssignmentInitializer) {
102235                 writeSpace();
102236                 writePunctuation("=");
102237                 writeSpace();
102238                 emitExpression(node.objectAssignmentInitializer);
102239             }
102240         }
102241         function emitSpreadAssignment(node) {
102242             if (node.expression) {
102243                 emitTokenWithComment(25 /* DotDotDotToken */, node.pos, writePunctuation, node);
102244                 emitExpression(node.expression);
102245             }
102246         }
102247         //
102248         // Enum
102249         //
102250         function emitEnumMember(node) {
102251             emit(node.name);
102252             emitInitializer(node.initializer, node.name.end, node);
102253         }
102254         //
102255         // JSDoc
102256         //
102257         function emitJSDoc(node) {
102258             write("/**");
102259             if (node.comment) {
102260                 var lines = node.comment.split(/\r\n?|\n/g);
102261                 for (var _a = 0, lines_2 = lines; _a < lines_2.length; _a++) {
102262                     var line = lines_2[_a];
102263                     writeLine();
102264                     writeSpace();
102265                     writePunctuation("*");
102266                     writeSpace();
102267                     write(line);
102268                 }
102269             }
102270             if (node.tags) {
102271                 if (node.tags.length === 1 && node.tags[0].kind === 329 /* JSDocTypeTag */ && !node.comment) {
102272                     writeSpace();
102273                     emit(node.tags[0]);
102274                 }
102275                 else {
102276                     emitList(node, node.tags, 33 /* JSDocComment */);
102277                 }
102278             }
102279             writeSpace();
102280             write("*/");
102281         }
102282         function emitJSDocSimpleTypedTag(tag) {
102283             emitJSDocTagName(tag.tagName);
102284             emitJSDocTypeExpression(tag.typeExpression);
102285             emitJSDocComment(tag.comment);
102286         }
102287         function emitJSDocSeeTag(tag) {
102288             emitJSDocTagName(tag.tagName);
102289             emit(tag.name);
102290             emitJSDocComment(tag.comment);
102291         }
102292         function emitJSDocNameReference(node) {
102293             writeSpace();
102294             writePunctuation("{");
102295             emit(node.name);
102296             writePunctuation("}");
102297         }
102298         function emitJSDocHeritageTag(tag) {
102299             emitJSDocTagName(tag.tagName);
102300             writeSpace();
102301             writePunctuation("{");
102302             emit(tag.class);
102303             writePunctuation("}");
102304             emitJSDocComment(tag.comment);
102305         }
102306         function emitJSDocTemplateTag(tag) {
102307             emitJSDocTagName(tag.tagName);
102308             emitJSDocTypeExpression(tag.constraint);
102309             writeSpace();
102310             emitList(tag, tag.typeParameters, 528 /* CommaListElements */);
102311             emitJSDocComment(tag.comment);
102312         }
102313         function emitJSDocTypedefTag(tag) {
102314             emitJSDocTagName(tag.tagName);
102315             if (tag.typeExpression) {
102316                 if (tag.typeExpression.kind === 301 /* JSDocTypeExpression */) {
102317                     emitJSDocTypeExpression(tag.typeExpression);
102318                 }
102319                 else {
102320                     writeSpace();
102321                     writePunctuation("{");
102322                     write("Object");
102323                     if (tag.typeExpression.isArrayType) {
102324                         writePunctuation("[");
102325                         writePunctuation("]");
102326                     }
102327                     writePunctuation("}");
102328                 }
102329             }
102330             if (tag.fullName) {
102331                 writeSpace();
102332                 emit(tag.fullName);
102333             }
102334             emitJSDocComment(tag.comment);
102335             if (tag.typeExpression && tag.typeExpression.kind === 312 /* JSDocTypeLiteral */) {
102336                 emitJSDocTypeLiteral(tag.typeExpression);
102337             }
102338         }
102339         function emitJSDocCallbackTag(tag) {
102340             emitJSDocTagName(tag.tagName);
102341             if (tag.name) {
102342                 writeSpace();
102343                 emit(tag.name);
102344             }
102345             emitJSDocComment(tag.comment);
102346             emitJSDocSignature(tag.typeExpression);
102347         }
102348         function emitJSDocSimpleTag(tag) {
102349             emitJSDocTagName(tag.tagName);
102350             emitJSDocComment(tag.comment);
102351         }
102352         function emitJSDocTypeLiteral(lit) {
102353             emitList(lit, ts.factory.createNodeArray(lit.jsDocPropertyTags), 33 /* JSDocComment */);
102354         }
102355         function emitJSDocSignature(sig) {
102356             if (sig.typeParameters) {
102357                 emitList(sig, ts.factory.createNodeArray(sig.typeParameters), 33 /* JSDocComment */);
102358             }
102359             if (sig.parameters) {
102360                 emitList(sig, ts.factory.createNodeArray(sig.parameters), 33 /* JSDocComment */);
102361             }
102362             if (sig.type) {
102363                 writeLine();
102364                 writeSpace();
102365                 writePunctuation("*");
102366                 writeSpace();
102367                 emit(sig.type);
102368             }
102369         }
102370         function emitJSDocPropertyLikeTag(param) {
102371             emitJSDocTagName(param.tagName);
102372             emitJSDocTypeExpression(param.typeExpression);
102373             writeSpace();
102374             if (param.isBracketed) {
102375                 writePunctuation("[");
102376             }
102377             emit(param.name);
102378             if (param.isBracketed) {
102379                 writePunctuation("]");
102380             }
102381             emitJSDocComment(param.comment);
102382         }
102383         function emitJSDocTagName(tagName) {
102384             writePunctuation("@");
102385             emit(tagName);
102386         }
102387         function emitJSDocComment(comment) {
102388             if (comment) {
102389                 writeSpace();
102390                 write(comment);
102391             }
102392         }
102393         function emitJSDocTypeExpression(typeExpression) {
102394             if (typeExpression) {
102395                 writeSpace();
102396                 writePunctuation("{");
102397                 emit(typeExpression.type);
102398                 writePunctuation("}");
102399             }
102400         }
102401         //
102402         // Top-level nodes
102403         //
102404         function emitSourceFile(node) {
102405             writeLine();
102406             var statements = node.statements;
102407             if (emitBodyWithDetachedComments) {
102408                 // Emit detached comment if there are no prologue directives or if the first node is synthesized.
102409                 // The synthesized node will have no leading comment so some comments may be missed.
102410                 var shouldEmitDetachedComment = statements.length === 0 ||
102411                     !ts.isPrologueDirective(statements[0]) ||
102412                     ts.nodeIsSynthesized(statements[0]);
102413                 if (shouldEmitDetachedComment) {
102414                     emitBodyWithDetachedComments(node, statements, emitSourceFileWorker);
102415                     return;
102416                 }
102417             }
102418             emitSourceFileWorker(node);
102419         }
102420         function emitSyntheticTripleSlashReferencesIfNeeded(node) {
102421             emitTripleSlashDirectives(!!node.hasNoDefaultLib, node.syntheticFileReferences || [], node.syntheticTypeReferences || [], node.syntheticLibReferences || []);
102422             for (var _a = 0, _b = node.prepends; _a < _b.length; _a++) {
102423                 var prepend = _b[_a];
102424                 if (ts.isUnparsedSource(prepend) && prepend.syntheticReferences) {
102425                     for (var _c = 0, _d = prepend.syntheticReferences; _c < _d.length; _c++) {
102426                         var ref = _d[_c];
102427                         emit(ref);
102428                         writeLine();
102429                     }
102430                 }
102431             }
102432         }
102433         function emitTripleSlashDirectivesIfNeeded(node) {
102434             if (node.isDeclarationFile)
102435                 emitTripleSlashDirectives(node.hasNoDefaultLib, node.referencedFiles, node.typeReferenceDirectives, node.libReferenceDirectives);
102436         }
102437         function emitTripleSlashDirectives(hasNoDefaultLib, files, types, libs) {
102438             if (hasNoDefaultLib) {
102439                 var pos = writer.getTextPos();
102440                 writeComment("/// <reference no-default-lib=\"true\"/>");
102441                 if (bundleFileInfo)
102442                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "no-default-lib" /* NoDefaultLib */ });
102443                 writeLine();
102444             }
102445             if (currentSourceFile && currentSourceFile.moduleName) {
102446                 writeComment("/// <amd-module name=\"" + currentSourceFile.moduleName + "\" />");
102447                 writeLine();
102448             }
102449             if (currentSourceFile && currentSourceFile.amdDependencies) {
102450                 for (var _a = 0, _b = currentSourceFile.amdDependencies; _a < _b.length; _a++) {
102451                     var dep = _b[_a];
102452                     if (dep.name) {
102453                         writeComment("/// <amd-dependency name=\"" + dep.name + "\" path=\"" + dep.path + "\" />");
102454                     }
102455                     else {
102456                         writeComment("/// <amd-dependency path=\"" + dep.path + "\" />");
102457                     }
102458                     writeLine();
102459                 }
102460             }
102461             for (var _c = 0, files_1 = files; _c < files_1.length; _c++) {
102462                 var directive = files_1[_c];
102463                 var pos = writer.getTextPos();
102464                 writeComment("/// <reference path=\"" + directive.fileName + "\" />");
102465                 if (bundleFileInfo)
102466                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "reference" /* Reference */, data: directive.fileName });
102467                 writeLine();
102468             }
102469             for (var _d = 0, types_23 = types; _d < types_23.length; _d++) {
102470                 var directive = types_23[_d];
102471                 var pos = writer.getTextPos();
102472                 writeComment("/// <reference types=\"" + directive.fileName + "\" />");
102473                 if (bundleFileInfo)
102474                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "type" /* Type */, data: directive.fileName });
102475                 writeLine();
102476             }
102477             for (var _e = 0, libs_1 = libs; _e < libs_1.length; _e++) {
102478                 var directive = libs_1[_e];
102479                 var pos = writer.getTextPos();
102480                 writeComment("/// <reference lib=\"" + directive.fileName + "\" />");
102481                 if (bundleFileInfo)
102482                     bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "lib" /* Lib */, data: directive.fileName });
102483                 writeLine();
102484             }
102485         }
102486         function emitSourceFileWorker(node) {
102487             var statements = node.statements;
102488             pushNameGenerationScope(node);
102489             ts.forEach(node.statements, generateNames);
102490             emitHelpers(node);
102491             var index = ts.findIndex(statements, function (statement) { return !ts.isPrologueDirective(statement); });
102492             emitTripleSlashDirectivesIfNeeded(node);
102493             emitList(node, statements, 1 /* MultiLine */, index === -1 ? statements.length : index);
102494             popNameGenerationScope(node);
102495         }
102496         // Transformation nodes
102497         function emitPartiallyEmittedExpression(node) {
102498             emitExpression(node.expression);
102499         }
102500         function emitCommaList(node) {
102501             emitExpressionList(node, node.elements, 528 /* CommaListElements */);
102502         }
102503         /**
102504          * Emits any prologue directives at the start of a Statement list, returning the
102505          * number of prologue directives written to the output.
102506          */
102507         function emitPrologueDirectives(statements, sourceFile, seenPrologueDirectives, recordBundleFileSection) {
102508             var needsToSetSourceFile = !!sourceFile;
102509             for (var i = 0; i < statements.length; i++) {
102510                 var statement = statements[i];
102511                 if (ts.isPrologueDirective(statement)) {
102512                     var shouldEmitPrologueDirective = seenPrologueDirectives ? !seenPrologueDirectives.has(statement.expression.text) : true;
102513                     if (shouldEmitPrologueDirective) {
102514                         if (needsToSetSourceFile) {
102515                             needsToSetSourceFile = false;
102516                             setSourceFile(sourceFile);
102517                         }
102518                         writeLine();
102519                         var pos = writer.getTextPos();
102520                         emit(statement);
102521                         if (recordBundleFileSection && bundleFileInfo)
102522                             bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: statement.expression.text });
102523                         if (seenPrologueDirectives) {
102524                             seenPrologueDirectives.add(statement.expression.text);
102525                         }
102526                     }
102527                 }
102528                 else {
102529                     // return index of the first non prologue directive
102530                     return i;
102531                 }
102532             }
102533             return statements.length;
102534         }
102535         function emitUnparsedPrologues(prologues, seenPrologueDirectives) {
102536             for (var _a = 0, prologues_1 = prologues; _a < prologues_1.length; _a++) {
102537                 var prologue = prologues_1[_a];
102538                 if (!seenPrologueDirectives.has(prologue.data)) {
102539                     writeLine();
102540                     var pos = writer.getTextPos();
102541                     emit(prologue);
102542                     if (bundleFileInfo)
102543                         bundleFileInfo.sections.push({ pos: pos, end: writer.getTextPos(), kind: "prologue" /* Prologue */, data: prologue.data });
102544                     if (seenPrologueDirectives) {
102545                         seenPrologueDirectives.add(prologue.data);
102546                     }
102547                 }
102548             }
102549         }
102550         function emitPrologueDirectivesIfNeeded(sourceFileOrBundle) {
102551             if (ts.isSourceFile(sourceFileOrBundle)) {
102552                 emitPrologueDirectives(sourceFileOrBundle.statements, sourceFileOrBundle);
102553             }
102554             else {
102555                 var seenPrologueDirectives = new ts.Set();
102556                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
102557                     var prepend = _b[_a];
102558                     emitUnparsedPrologues(prepend.prologues, seenPrologueDirectives);
102559                 }
102560                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
102561                     var sourceFile = _d[_c];
102562                     emitPrologueDirectives(sourceFile.statements, sourceFile, seenPrologueDirectives, /*recordBundleFileSection*/ true);
102563                 }
102564                 setSourceFile(undefined);
102565             }
102566         }
102567         function getPrologueDirectivesFromBundledSourceFiles(bundle) {
102568             var seenPrologueDirectives = new ts.Set();
102569             var prologues;
102570             for (var index = 0; index < bundle.sourceFiles.length; index++) {
102571                 var sourceFile = bundle.sourceFiles[index];
102572                 var directives = void 0;
102573                 var end = 0;
102574                 for (var _a = 0, _b = sourceFile.statements; _a < _b.length; _a++) {
102575                     var statement = _b[_a];
102576                     if (!ts.isPrologueDirective(statement))
102577                         break;
102578                     if (seenPrologueDirectives.has(statement.expression.text))
102579                         continue;
102580                     seenPrologueDirectives.add(statement.expression.text);
102581                     (directives || (directives = [])).push({
102582                         pos: statement.pos,
102583                         end: statement.end,
102584                         expression: {
102585                             pos: statement.expression.pos,
102586                             end: statement.expression.end,
102587                             text: statement.expression.text
102588                         }
102589                     });
102590                     end = end < statement.end ? statement.end : end;
102591                 }
102592                 if (directives)
102593                     (prologues || (prologues = [])).push({ file: index, text: sourceFile.text.substring(0, end), directives: directives });
102594             }
102595             return prologues;
102596         }
102597         function emitShebangIfNeeded(sourceFileOrBundle) {
102598             if (ts.isSourceFile(sourceFileOrBundle) || ts.isUnparsedSource(sourceFileOrBundle)) {
102599                 var shebang = ts.getShebang(sourceFileOrBundle.text);
102600                 if (shebang) {
102601                     writeComment(shebang);
102602                     writeLine();
102603                     return true;
102604                 }
102605             }
102606             else {
102607                 for (var _a = 0, _b = sourceFileOrBundle.prepends; _a < _b.length; _a++) {
102608                     var prepend = _b[_a];
102609                     ts.Debug.assertNode(prepend, ts.isUnparsedSource);
102610                     if (emitShebangIfNeeded(prepend)) {
102611                         return true;
102612                     }
102613                 }
102614                 for (var _c = 0, _d = sourceFileOrBundle.sourceFiles; _c < _d.length; _c++) {
102615                     var sourceFile = _d[_c];
102616                     // Emit only the first encountered shebang
102617                     if (emitShebangIfNeeded(sourceFile)) {
102618                         return true;
102619                     }
102620                 }
102621             }
102622         }
102623         //
102624         // Helpers
102625         //
102626         function emitNodeWithWriter(node, writer) {
102627             if (!node)
102628                 return;
102629             var savedWrite = write;
102630             write = writer;
102631             emit(node);
102632             write = savedWrite;
102633         }
102634         function emitModifiers(node, modifiers) {
102635             if (modifiers && modifiers.length) {
102636                 emitList(node, modifiers, 262656 /* Modifiers */);
102637                 writeSpace();
102638             }
102639         }
102640         function emitTypeAnnotation(node) {
102641             if (node) {
102642                 writePunctuation(":");
102643                 writeSpace();
102644                 emit(node);
102645             }
102646         }
102647         function emitInitializer(node, equalCommentStartPos, container) {
102648             if (node) {
102649                 writeSpace();
102650                 emitTokenWithComment(62 /* EqualsToken */, equalCommentStartPos, writeOperator, container);
102651                 writeSpace();
102652                 emitExpression(node);
102653             }
102654         }
102655         function emitNodeWithPrefix(prefix, prefixWriter, node, emit) {
102656             if (node) {
102657                 prefixWriter(prefix);
102658                 emit(node);
102659             }
102660         }
102661         function emitWithLeadingSpace(node) {
102662             if (node) {
102663                 writeSpace();
102664                 emit(node);
102665             }
102666         }
102667         function emitExpressionWithLeadingSpace(node) {
102668             if (node) {
102669                 writeSpace();
102670                 emitExpression(node);
102671             }
102672         }
102673         function emitWithTrailingSpace(node) {
102674             if (node) {
102675                 emit(node);
102676                 writeSpace();
102677             }
102678         }
102679         function emitEmbeddedStatement(parent, node) {
102680             if (ts.isBlock(node) || ts.getEmitFlags(parent) & 1 /* SingleLine */) {
102681                 writeSpace();
102682                 emit(node);
102683             }
102684             else {
102685                 writeLine();
102686                 increaseIndent();
102687                 if (ts.isEmptyStatement(node)) {
102688                     pipelineEmit(5 /* EmbeddedStatement */, node);
102689                 }
102690                 else {
102691                     emit(node);
102692                 }
102693                 decreaseIndent();
102694             }
102695         }
102696         function emitDecorators(parentNode, decorators) {
102697             emitList(parentNode, decorators, 2146305 /* Decorators */);
102698         }
102699         function emitTypeArguments(parentNode, typeArguments) {
102700             emitList(parentNode, typeArguments, 53776 /* TypeArguments */);
102701         }
102702         function emitTypeParameters(parentNode, typeParameters) {
102703             if (ts.isFunctionLike(parentNode) && parentNode.typeArguments) { // Quick info uses type arguments in place of type parameters on instantiated signatures
102704                 return emitTypeArguments(parentNode, parentNode.typeArguments);
102705             }
102706             emitList(parentNode, typeParameters, 53776 /* TypeParameters */);
102707         }
102708         function emitParameters(parentNode, parameters) {
102709             emitList(parentNode, parameters, 2576 /* Parameters */);
102710         }
102711         function canEmitSimpleArrowHead(parentNode, parameters) {
102712             var parameter = ts.singleOrUndefined(parameters);
102713             return parameter
102714                 && parameter.pos === parentNode.pos // may not have parsed tokens between parent and parameter
102715                 && ts.isArrowFunction(parentNode) // only arrow functions may have simple arrow head
102716                 && !parentNode.type // arrow function may not have return type annotation
102717                 && !ts.some(parentNode.decorators) // parent may not have decorators
102718                 && !ts.some(parentNode.modifiers) // parent may not have modifiers
102719                 && !ts.some(parentNode.typeParameters) // parent may not have type parameters
102720                 && !ts.some(parameter.decorators) // parameter may not have decorators
102721                 && !ts.some(parameter.modifiers) // parameter may not have modifiers
102722                 && !parameter.dotDotDotToken // parameter may not be rest
102723                 && !parameter.questionToken // parameter may not be optional
102724                 && !parameter.type // parameter may not have a type annotation
102725                 && !parameter.initializer // parameter may not have an initializer
102726                 && ts.isIdentifier(parameter.name); // parameter name must be identifier
102727         }
102728         function emitParametersForArrow(parentNode, parameters) {
102729             if (canEmitSimpleArrowHead(parentNode, parameters)) {
102730                 emitList(parentNode, parameters, 2576 /* Parameters */ & ~2048 /* Parenthesis */);
102731             }
102732             else {
102733                 emitParameters(parentNode, parameters);
102734             }
102735         }
102736         function emitParametersForIndexSignature(parentNode, parameters) {
102737             emitList(parentNode, parameters, 8848 /* IndexSignatureParameters */);
102738         }
102739         function emitList(parentNode, children, format, start, count) {
102740             emitNodeList(emit, parentNode, children, format, start, count);
102741         }
102742         function emitExpressionList(parentNode, children, format, start, count) {
102743             emitNodeList(emitExpression, parentNode, children, format, start, count); // TODO: GH#18217
102744         }
102745         function writeDelimiter(format) {
102746             switch (format & 60 /* DelimitersMask */) {
102747                 case 0 /* None */:
102748                     break;
102749                 case 16 /* CommaDelimited */:
102750                     writePunctuation(",");
102751                     break;
102752                 case 4 /* BarDelimited */:
102753                     writeSpace();
102754                     writePunctuation("|");
102755                     break;
102756                 case 32 /* AsteriskDelimited */:
102757                     writeSpace();
102758                     writePunctuation("*");
102759                     writeSpace();
102760                     break;
102761                 case 8 /* AmpersandDelimited */:
102762                     writeSpace();
102763                     writePunctuation("&");
102764                     break;
102765             }
102766         }
102767         function emitNodeList(emit, parentNode, children, format, start, count) {
102768             if (start === void 0) { start = 0; }
102769             if (count === void 0) { count = children ? children.length - start : 0; }
102770             var isUndefined = children === undefined;
102771             if (isUndefined && format & 16384 /* OptionalIfUndefined */) {
102772                 return;
102773             }
102774             var isEmpty = children === undefined || start >= children.length || count === 0;
102775             if (isEmpty && format & 32768 /* OptionalIfEmpty */) {
102776                 if (onBeforeEmitNodeArray) {
102777                     onBeforeEmitNodeArray(children);
102778                 }
102779                 if (onAfterEmitNodeArray) {
102780                     onAfterEmitNodeArray(children);
102781                 }
102782                 return;
102783             }
102784             if (format & 15360 /* BracketsMask */) {
102785                 writePunctuation(getOpeningBracket(format));
102786                 if (isEmpty && !isUndefined) {
102787                     // TODO: GH#18217
102788                     emitTrailingCommentsOfPosition(children.pos, /*prefixSpace*/ true); // Emit comments within empty bracketed lists
102789                 }
102790             }
102791             if (onBeforeEmitNodeArray) {
102792                 onBeforeEmitNodeArray(children);
102793             }
102794             if (isEmpty) {
102795                 // Write a line terminator if the parent node was multi-line
102796                 if (format & 1 /* MultiLine */ && !(preserveSourceNewlines && ts.rangeIsOnSingleLine(parentNode, currentSourceFile))) {
102797                     writeLine();
102798                 }
102799                 else if (format & 256 /* SpaceBetweenBraces */ && !(format & 524288 /* NoSpaceIfEmpty */)) {
102800                     writeSpace();
102801                 }
102802             }
102803             else {
102804                 // Write the opening line terminator or leading whitespace.
102805                 var mayEmitInterveningComments = (format & 262144 /* NoInterveningComments */) === 0;
102806                 var shouldEmitInterveningComments = mayEmitInterveningComments;
102807                 var leadingLineTerminatorCount = getLeadingLineTerminatorCount(parentNode, children, format); // TODO: GH#18217
102808                 if (leadingLineTerminatorCount) {
102809                     writeLine(leadingLineTerminatorCount);
102810                     shouldEmitInterveningComments = false;
102811                 }
102812                 else if (format & 256 /* SpaceBetweenBraces */) {
102813                     writeSpace();
102814                 }
102815                 // Increase the indent, if requested.
102816                 if (format & 128 /* Indented */) {
102817                     increaseIndent();
102818                 }
102819                 // Emit each child.
102820                 var previousSibling = void 0;
102821                 var previousSourceFileTextKind = void 0;
102822                 var shouldDecreaseIndentAfterEmit = false;
102823                 for (var i = 0; i < count; i++) {
102824                     var child = children[start + i];
102825                     // Write the delimiter if this is not the first node.
102826                     if (format & 32 /* AsteriskDelimited */) {
102827                         // always write JSDoc in the format "\n *"
102828                         writeLine();
102829                         writeDelimiter(format);
102830                     }
102831                     else if (previousSibling) {
102832                         // i.e
102833                         //      function commentedParameters(
102834                         //          /* Parameter a */
102835                         //          a
102836                         //          /* End of parameter a */ -> this comment isn't considered to be trailing comment of parameter "a" due to newline
102837                         //          ,
102838                         if (format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end) {
102839                             emitLeadingCommentsOfPosition(previousSibling.end);
102840                         }
102841                         writeDelimiter(format);
102842                         recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
102843                         // Write either a line terminator or whitespace to separate the elements.
102844                         var separatingLineTerminatorCount = getSeparatingLineTerminatorCount(previousSibling, child, format);
102845                         if (separatingLineTerminatorCount > 0) {
102846                             // If a synthesized node in a single-line list starts on a new
102847                             // line, we should increase the indent.
102848                             if ((format & (3 /* LinesMask */ | 128 /* Indented */)) === 0 /* SingleLine */) {
102849                                 increaseIndent();
102850                                 shouldDecreaseIndentAfterEmit = true;
102851                             }
102852                             writeLine(separatingLineTerminatorCount);
102853                             shouldEmitInterveningComments = false;
102854                         }
102855                         else if (previousSibling && format & 512 /* SpaceBetweenSiblings */) {
102856                             writeSpace();
102857                         }
102858                     }
102859                     // Emit this child.
102860                     previousSourceFileTextKind = recordBundleFileInternalSectionStart(child);
102861                     if (shouldEmitInterveningComments) {
102862                         if (emitTrailingCommentsOfPosition) {
102863                             var commentRange = ts.getCommentRange(child);
102864                             emitTrailingCommentsOfPosition(commentRange.pos);
102865                         }
102866                     }
102867                     else {
102868                         shouldEmitInterveningComments = mayEmitInterveningComments;
102869                     }
102870                     nextListElementPos = child.pos;
102871                     emit(child);
102872                     if (shouldDecreaseIndentAfterEmit) {
102873                         decreaseIndent();
102874                         shouldDecreaseIndentAfterEmit = false;
102875                     }
102876                     previousSibling = child;
102877                 }
102878                 // Write a trailing comma, if requested.
102879                 var hasTrailingComma = (format & 64 /* AllowTrailingComma */) && children.hasTrailingComma;
102880                 if (format & 16 /* CommaDelimited */ && hasTrailingComma) {
102881                     writePunctuation(",");
102882                 }
102883                 // Emit any trailing comment of the last element in the list
102884                 // i.e
102885                 //       var array = [...
102886                 //          2
102887                 //          /* end of element 2 */
102888                 //       ];
102889                 if (previousSibling && format & 60 /* DelimitersMask */ && previousSibling.end !== parentNode.end && !(ts.getEmitFlags(previousSibling) & 1024 /* NoTrailingComments */)) {
102890                     emitLeadingCommentsOfPosition(previousSibling.end);
102891                 }
102892                 // Decrease the indent, if requested.
102893                 if (format & 128 /* Indented */) {
102894                     decreaseIndent();
102895                 }
102896                 recordBundleFileInternalSectionEnd(previousSourceFileTextKind);
102897                 // Write the closing line terminator or closing whitespace.
102898                 var closingLineTerminatorCount = getClosingLineTerminatorCount(parentNode, children, format);
102899                 if (closingLineTerminatorCount) {
102900                     writeLine(closingLineTerminatorCount);
102901                 }
102902                 else if (format & (2097152 /* SpaceAfterList */ | 256 /* SpaceBetweenBraces */)) {
102903                     writeSpace();
102904                 }
102905             }
102906             if (onAfterEmitNodeArray) {
102907                 onAfterEmitNodeArray(children);
102908             }
102909             if (format & 15360 /* BracketsMask */) {
102910                 if (isEmpty && !isUndefined) {
102911                     // TODO: GH#18217
102912                     emitLeadingCommentsOfPosition(children.end); // Emit leading comments within empty lists
102913                 }
102914                 writePunctuation(getClosingBracket(format));
102915             }
102916         }
102917         // Writers
102918         function writeLiteral(s) {
102919             writer.writeLiteral(s);
102920         }
102921         function writeStringLiteral(s) {
102922             writer.writeStringLiteral(s);
102923         }
102924         function writeBase(s) {
102925             writer.write(s);
102926         }
102927         function writeSymbol(s, sym) {
102928             writer.writeSymbol(s, sym);
102929         }
102930         function writePunctuation(s) {
102931             writer.writePunctuation(s);
102932         }
102933         function writeTrailingSemicolon() {
102934             writer.writeTrailingSemicolon(";");
102935         }
102936         function writeKeyword(s) {
102937             writer.writeKeyword(s);
102938         }
102939         function writeOperator(s) {
102940             writer.writeOperator(s);
102941         }
102942         function writeParameter(s) {
102943             writer.writeParameter(s);
102944         }
102945         function writeComment(s) {
102946             writer.writeComment(s);
102947         }
102948         function writeSpace() {
102949             writer.writeSpace(" ");
102950         }
102951         function writeProperty(s) {
102952             writer.writeProperty(s);
102953         }
102954         function writeLine(count) {
102955             if (count === void 0) { count = 1; }
102956             for (var i = 0; i < count; i++) {
102957                 writer.writeLine(i > 0);
102958             }
102959         }
102960         function increaseIndent() {
102961             writer.increaseIndent();
102962         }
102963         function decreaseIndent() {
102964             writer.decreaseIndent();
102965         }
102966         function writeToken(token, pos, writer, contextNode) {
102967             return !sourceMapsDisabled
102968                 ? emitTokenWithSourceMap(contextNode, token, writer, pos, writeTokenText)
102969                 : writeTokenText(token, writer, pos);
102970         }
102971         function writeTokenNode(node, writer) {
102972             if (onBeforeEmitToken) {
102973                 onBeforeEmitToken(node);
102974             }
102975             writer(ts.tokenToString(node.kind));
102976             if (onAfterEmitToken) {
102977                 onAfterEmitToken(node);
102978             }
102979         }
102980         function writeTokenText(token, writer, pos) {
102981             var tokenString = ts.tokenToString(token);
102982             writer(tokenString);
102983             return pos < 0 ? pos : pos + tokenString.length;
102984         }
102985         function writeLineOrSpace(parentNode, prevChildNode, nextChildNode) {
102986             if (ts.getEmitFlags(parentNode) & 1 /* SingleLine */) {
102987                 writeSpace();
102988             }
102989             else if (preserveSourceNewlines) {
102990                 var lines = getLinesBetweenNodes(parentNode, prevChildNode, nextChildNode);
102991                 if (lines) {
102992                     writeLine(lines);
102993                 }
102994                 else {
102995                     writeSpace();
102996                 }
102997             }
102998             else {
102999                 writeLine();
103000             }
103001         }
103002         function writeLines(text) {
103003             var lines = text.split(/\r\n?|\n/g);
103004             var indentation = ts.guessIndentation(lines);
103005             for (var _a = 0, lines_3 = lines; _a < lines_3.length; _a++) {
103006                 var lineText = lines_3[_a];
103007                 var line = indentation ? lineText.slice(indentation) : lineText;
103008                 if (line.length) {
103009                     writeLine();
103010                     write(line);
103011                 }
103012             }
103013         }
103014         function writeLinesAndIndent(lineCount, writeSpaceIfNotIndenting) {
103015             if (lineCount) {
103016                 increaseIndent();
103017                 writeLine(lineCount);
103018             }
103019             else if (writeSpaceIfNotIndenting) {
103020                 writeSpace();
103021             }
103022         }
103023         // Helper function to decrease the indent if we previously indented.  Allows multiple
103024         // previous indent values to be considered at a time.  This also allows caller to just
103025         // call this once, passing in all their appropriate indent values, instead of needing
103026         // to call this helper function multiple times.
103027         function decreaseIndentIf(value1, value2) {
103028             if (value1) {
103029                 decreaseIndent();
103030             }
103031             if (value2) {
103032                 decreaseIndent();
103033             }
103034         }
103035         function getLeadingLineTerminatorCount(parentNode, children, format) {
103036             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
103037                 if (format & 65536 /* PreferNewLine */) {
103038                     return 1;
103039                 }
103040                 var firstChild_1 = children[0];
103041                 if (firstChild_1 === undefined) {
103042                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
103043                 }
103044                 if (firstChild_1.pos === nextListElementPos) {
103045                     // If this child starts at the beginning of a list item in a parent list, its leading
103046                     // line terminators have already been written as the separating line terminators of the
103047                     // parent list. Example:
103048                     //
103049                     // class Foo {
103050                     //   constructor() {}
103051                     //   public foo() {}
103052                     // }
103053                     //
103054                     // The outer list is the list of class members, with one line terminator between the
103055                     // constructor and the method. The constructor is written, the separating line terminator
103056                     // is written, and then we start emitting the method. Its modifiers ([public]) constitute an inner
103057                     // list, so we look for its leading line terminators. If we didn't know that we had already
103058                     // written a newline as part of the parent list, it would appear that we need to write a
103059                     // leading newline to start the modifiers.
103060                     return 0;
103061                 }
103062                 if (firstChild_1.kind === 11 /* JsxText */) {
103063                     // JsxText will be written with its leading whitespace, so don't add more manually.
103064                     return 0;
103065                 }
103066                 if (!ts.positionIsSynthesized(parentNode.pos) &&
103067                     !ts.nodeIsSynthesized(firstChild_1) &&
103068                     (!firstChild_1.parent || ts.getOriginalNode(firstChild_1.parent) === ts.getOriginalNode(parentNode))) {
103069                     if (preserveSourceNewlines) {
103070                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndPrecedingNonWhitespaceCharacter(firstChild_1.pos, parentNode.pos, currentSourceFile, includeComments); });
103071                     }
103072                     return ts.rangeStartPositionsAreOnSameLine(parentNode, firstChild_1, currentSourceFile) ? 0 : 1;
103073                 }
103074                 if (synthesizedNodeStartsOnNewLine(firstChild_1, format)) {
103075                     return 1;
103076                 }
103077             }
103078             return format & 1 /* MultiLine */ ? 1 : 0;
103079         }
103080         function getSeparatingLineTerminatorCount(previousNode, nextNode, format) {
103081             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
103082                 if (previousNode === undefined || nextNode === undefined) {
103083                     return 0;
103084                 }
103085                 if (nextNode.kind === 11 /* JsxText */) {
103086                     // JsxText will be written with its leading whitespace, so don't add more manually.
103087                     return 0;
103088                 }
103089                 else if (!ts.nodeIsSynthesized(previousNode) && !ts.nodeIsSynthesized(nextNode) && previousNode.parent === nextNode.parent) {
103090                     if (preserveSourceNewlines) {
103091                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(previousNode, nextNode, currentSourceFile, includeComments); });
103092                     }
103093                     return ts.rangeEndIsOnSameLineAsRangeStart(previousNode, nextNode, currentSourceFile) ? 0 : 1;
103094                 }
103095                 else if (synthesizedNodeStartsOnNewLine(previousNode, format) || synthesizedNodeStartsOnNewLine(nextNode, format)) {
103096                     return 1;
103097                 }
103098             }
103099             else if (ts.getStartsOnNewLine(nextNode)) {
103100                 return 1;
103101             }
103102             return format & 1 /* MultiLine */ ? 1 : 0;
103103         }
103104         function getClosingLineTerminatorCount(parentNode, children, format) {
103105             if (format & 2 /* PreserveLines */ || preserveSourceNewlines) {
103106                 if (format & 65536 /* PreferNewLine */) {
103107                     return 1;
103108                 }
103109                 var lastChild = ts.lastOrUndefined(children);
103110                 if (lastChild === undefined) {
103111                     return ts.rangeIsOnSingleLine(parentNode, currentSourceFile) ? 0 : 1;
103112                 }
103113                 if (!ts.positionIsSynthesized(parentNode.pos) && !ts.nodeIsSynthesized(lastChild) && (!lastChild.parent || lastChild.parent === parentNode)) {
103114                     if (preserveSourceNewlines) {
103115                         var end_2 = ts.isNodeArray(children) && !ts.positionIsSynthesized(children.end) ? children.end : lastChild.end;
103116                         return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenPositionAndNextNonWhitespaceCharacter(end_2, parentNode.end, currentSourceFile, includeComments); });
103117                     }
103118                     return ts.rangeEndPositionsAreOnSameLine(parentNode, lastChild, currentSourceFile) ? 0 : 1;
103119                 }
103120                 if (synthesizedNodeStartsOnNewLine(lastChild, format)) {
103121                     return 1;
103122                 }
103123             }
103124             if (format & 1 /* MultiLine */ && !(format & 131072 /* NoTrailingNewLine */)) {
103125                 return 1;
103126             }
103127             return 0;
103128         }
103129         function getEffectiveLines(getLineDifference) {
103130             // If 'preserveSourceNewlines' is disabled, we should never call this function
103131             // because it could be more expensive than alternative approximations.
103132             ts.Debug.assert(!!preserveSourceNewlines);
103133             // We start by measuring the line difference from a position to its adjacent comments,
103134             // so that this is counted as a one-line difference, not two:
103135             //
103136             //   node1;
103137             //   // NODE2 COMMENT
103138             //   node2;
103139             var lines = getLineDifference(/*includeComments*/ true);
103140             if (lines === 0) {
103141                 // However, if the line difference considering comments was 0, we might have this:
103142                 //
103143                 //   node1; // NODE2 COMMENT
103144                 //   node2;
103145                 //
103146                 // in which case we should be ignoring node2's comment, so this too is counted as
103147                 // a one-line difference, not zero.
103148                 return getLineDifference(/*includeComments*/ false);
103149             }
103150             return lines;
103151         }
103152         function writeLineSeparatorsAndIndentBefore(node, parent) {
103153             var leadingNewlines = preserveSourceNewlines && getLeadingLineTerminatorCount(parent, [node], 0 /* None */);
103154             if (leadingNewlines) {
103155                 writeLinesAndIndent(leadingNewlines, /*writeLinesIfNotIndenting*/ false);
103156             }
103157             return !!leadingNewlines;
103158         }
103159         function writeLineSeparatorsAfter(node, parent) {
103160             var trailingNewlines = preserveSourceNewlines && getClosingLineTerminatorCount(parent, [node], 0 /* None */);
103161             if (trailingNewlines) {
103162                 writeLine(trailingNewlines);
103163             }
103164         }
103165         function synthesizedNodeStartsOnNewLine(node, format) {
103166             if (ts.nodeIsSynthesized(node)) {
103167                 var startsOnNewLine = ts.getStartsOnNewLine(node);
103168                 if (startsOnNewLine === undefined) {
103169                     return (format & 65536 /* PreferNewLine */) !== 0;
103170                 }
103171                 return startsOnNewLine;
103172             }
103173             return (format & 65536 /* PreferNewLine */) !== 0;
103174         }
103175         function getLinesBetweenNodes(parent, node1, node2) {
103176             if (ts.getEmitFlags(parent) & 131072 /* NoIndentation */) {
103177                 return 0;
103178             }
103179             parent = skipSynthesizedParentheses(parent);
103180             node1 = skipSynthesizedParentheses(node1);
103181             node2 = skipSynthesizedParentheses(node2);
103182             // Always use a newline for synthesized code if the synthesizer desires it.
103183             if (ts.getStartsOnNewLine(node2)) {
103184                 return 1;
103185             }
103186             if (!ts.nodeIsSynthesized(parent) && !ts.nodeIsSynthesized(node1) && !ts.nodeIsSynthesized(node2)) {
103187                 if (preserveSourceNewlines) {
103188                     return getEffectiveLines(function (includeComments) { return ts.getLinesBetweenRangeEndAndRangeStart(node1, node2, currentSourceFile, includeComments); });
103189                 }
103190                 return ts.rangeEndIsOnSameLineAsRangeStart(node1, node2, currentSourceFile) ? 0 : 1;
103191             }
103192             return 0;
103193         }
103194         function isEmptyBlock(block) {
103195             return block.statements.length === 0
103196                 && ts.rangeEndIsOnSameLineAsRangeStart(block, block, currentSourceFile);
103197         }
103198         function skipSynthesizedParentheses(node) {
103199             while (node.kind === 207 /* ParenthesizedExpression */ && ts.nodeIsSynthesized(node)) {
103200                 node = node.expression;
103201             }
103202             return node;
103203         }
103204         function getTextOfNode(node, includeTrivia) {
103205             if (ts.isGeneratedIdentifier(node)) {
103206                 return generateName(node);
103207             }
103208             else if ((ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) && (ts.nodeIsSynthesized(node) || !node.parent || !currentSourceFile || (node.parent && currentSourceFile && ts.getSourceFileOfNode(node) !== ts.getOriginalNode(currentSourceFile)))) {
103209                 return ts.idText(node);
103210             }
103211             else if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
103212                 return getTextOfNode(node.textSourceNode, includeTrivia);
103213             }
103214             else if (ts.isLiteralExpression(node) && (ts.nodeIsSynthesized(node) || !node.parent)) {
103215                 return node.text;
103216             }
103217             return ts.getSourceTextOfNodeFromSourceFile(currentSourceFile, node, includeTrivia);
103218         }
103219         function getLiteralTextOfNode(node, neverAsciiEscape, jsxAttributeEscape) {
103220             if (node.kind === 10 /* StringLiteral */ && node.textSourceNode) {
103221                 var textSourceNode = node.textSourceNode;
103222                 if (ts.isIdentifier(textSourceNode) || ts.isNumericLiteral(textSourceNode)) {
103223                     var text = ts.isNumericLiteral(textSourceNode) ? textSourceNode.text : getTextOfNode(textSourceNode);
103224                     return jsxAttributeEscape ? "\"" + ts.escapeJsxAttributeString(text) + "\"" :
103225                         neverAsciiEscape || (ts.getEmitFlags(node) & 16777216 /* NoAsciiEscaping */) ? "\"" + ts.escapeString(text) + "\"" :
103226                             "\"" + ts.escapeNonAsciiString(text) + "\"";
103227                 }
103228                 else {
103229                     return getLiteralTextOfNode(textSourceNode, neverAsciiEscape, jsxAttributeEscape);
103230                 }
103231             }
103232             var flags = (neverAsciiEscape ? 1 /* NeverAsciiEscape */ : 0)
103233                 | (jsxAttributeEscape ? 2 /* JsxAttributeEscape */ : 0)
103234                 | (printerOptions.terminateUnterminatedLiterals ? 4 /* TerminateUnterminatedLiterals */ : 0);
103235             return ts.getLiteralText(node, currentSourceFile, flags);
103236         }
103237         /**
103238          * Push a new name generation scope.
103239          */
103240         function pushNameGenerationScope(node) {
103241             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
103242                 return;
103243             }
103244             tempFlagsStack.push(tempFlags);
103245             tempFlags = 0;
103246             reservedNamesStack.push(reservedNames);
103247         }
103248         /**
103249          * Pop the current name generation scope.
103250          */
103251         function popNameGenerationScope(node) {
103252             if (node && ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
103253                 return;
103254             }
103255             tempFlags = tempFlagsStack.pop();
103256             reservedNames = reservedNamesStack.pop();
103257         }
103258         function reserveNameInNestedScopes(name) {
103259             if (!reservedNames || reservedNames === ts.lastOrUndefined(reservedNamesStack)) {
103260                 reservedNames = new ts.Set();
103261             }
103262             reservedNames.add(name);
103263         }
103264         function generateNames(node) {
103265             if (!node)
103266                 return;
103267             switch (node.kind) {
103268                 case 230 /* Block */:
103269                     ts.forEach(node.statements, generateNames);
103270                     break;
103271                 case 245 /* LabeledStatement */:
103272                 case 243 /* WithStatement */:
103273                 case 235 /* DoStatement */:
103274                 case 236 /* WhileStatement */:
103275                     generateNames(node.statement);
103276                     break;
103277                 case 234 /* IfStatement */:
103278                     generateNames(node.thenStatement);
103279                     generateNames(node.elseStatement);
103280                     break;
103281                 case 237 /* ForStatement */:
103282                 case 239 /* ForOfStatement */:
103283                 case 238 /* ForInStatement */:
103284                     generateNames(node.initializer);
103285                     generateNames(node.statement);
103286                     break;
103287                 case 244 /* SwitchStatement */:
103288                     generateNames(node.caseBlock);
103289                     break;
103290                 case 258 /* CaseBlock */:
103291                     ts.forEach(node.clauses, generateNames);
103292                     break;
103293                 case 284 /* CaseClause */:
103294                 case 285 /* DefaultClause */:
103295                     ts.forEach(node.statements, generateNames);
103296                     break;
103297                 case 247 /* TryStatement */:
103298                     generateNames(node.tryBlock);
103299                     generateNames(node.catchClause);
103300                     generateNames(node.finallyBlock);
103301                     break;
103302                 case 287 /* CatchClause */:
103303                     generateNames(node.variableDeclaration);
103304                     generateNames(node.block);
103305                     break;
103306                 case 232 /* VariableStatement */:
103307                     generateNames(node.declarationList);
103308                     break;
103309                 case 250 /* VariableDeclarationList */:
103310                     ts.forEach(node.declarations, generateNames);
103311                     break;
103312                 case 249 /* VariableDeclaration */:
103313                 case 160 /* Parameter */:
103314                 case 198 /* BindingElement */:
103315                 case 252 /* ClassDeclaration */:
103316                     generateNameIfNeeded(node.name);
103317                     break;
103318                 case 251 /* FunctionDeclaration */:
103319                     generateNameIfNeeded(node.name);
103320                     if (ts.getEmitFlags(node) & 524288 /* ReuseTempVariableScope */) {
103321                         ts.forEach(node.parameters, generateNames);
103322                         generateNames(node.body);
103323                     }
103324                     break;
103325                 case 196 /* ObjectBindingPattern */:
103326                 case 197 /* ArrayBindingPattern */:
103327                     ts.forEach(node.elements, generateNames);
103328                     break;
103329                 case 261 /* ImportDeclaration */:
103330                     generateNames(node.importClause);
103331                     break;
103332                 case 262 /* ImportClause */:
103333                     generateNameIfNeeded(node.name);
103334                     generateNames(node.namedBindings);
103335                     break;
103336                 case 263 /* NamespaceImport */:
103337                     generateNameIfNeeded(node.name);
103338                     break;
103339                 case 269 /* NamespaceExport */:
103340                     generateNameIfNeeded(node.name);
103341                     break;
103342                 case 264 /* NamedImports */:
103343                     ts.forEach(node.elements, generateNames);
103344                     break;
103345                 case 265 /* ImportSpecifier */:
103346                     generateNameIfNeeded(node.propertyName || node.name);
103347                     break;
103348             }
103349         }
103350         function generateMemberNames(node) {
103351             if (!node)
103352                 return;
103353             switch (node.kind) {
103354                 case 288 /* PropertyAssignment */:
103355                 case 289 /* ShorthandPropertyAssignment */:
103356                 case 163 /* PropertyDeclaration */:
103357                 case 165 /* MethodDeclaration */:
103358                 case 167 /* GetAccessor */:
103359                 case 168 /* SetAccessor */:
103360                     generateNameIfNeeded(node.name);
103361                     break;
103362             }
103363         }
103364         function generateNameIfNeeded(name) {
103365             if (name) {
103366                 if (ts.isGeneratedIdentifier(name)) {
103367                     generateName(name);
103368                 }
103369                 else if (ts.isBindingPattern(name)) {
103370                     generateNames(name);
103371                 }
103372             }
103373         }
103374         /**
103375          * Generate the text for a generated identifier.
103376          */
103377         function generateName(name) {
103378             if ((name.autoGenerateFlags & 7 /* KindMask */) === 4 /* Node */) {
103379                 // Node names generate unique names based on their original node
103380                 // and are cached based on that node's id.
103381                 return generateNameCached(getNodeForGeneratedName(name), name.autoGenerateFlags);
103382             }
103383             else {
103384                 // Auto, Loop, and Unique names are cached based on their unique
103385                 // autoGenerateId.
103386                 var autoGenerateId = name.autoGenerateId;
103387                 return autoGeneratedIdToGeneratedName[autoGenerateId] || (autoGeneratedIdToGeneratedName[autoGenerateId] = makeName(name));
103388             }
103389         }
103390         function generateNameCached(node, flags) {
103391             var nodeId = ts.getNodeId(node);
103392             return nodeIdToGeneratedName[nodeId] || (nodeIdToGeneratedName[nodeId] = generateNameForNode(node, flags));
103393         }
103394         /**
103395          * Returns a value indicating whether a name is unique globally, within the current file,
103396          * or within the NameGenerator.
103397          */
103398         function isUniqueName(name) {
103399             return isFileLevelUniqueName(name)
103400                 && !generatedNames.has(name)
103401                 && !(reservedNames && reservedNames.has(name));
103402         }
103403         /**
103404          * Returns a value indicating whether a name is unique globally or within the current file.
103405          */
103406         function isFileLevelUniqueName(name) {
103407             return currentSourceFile ? ts.isFileLevelUniqueName(currentSourceFile, name, hasGlobalName) : true;
103408         }
103409         /**
103410          * Returns a value indicating whether a name is unique within a container.
103411          */
103412         function isUniqueLocalName(name, container) {
103413             for (var node = container; ts.isNodeDescendantOf(node, container); node = node.nextContainer) {
103414                 if (node.locals) {
103415                     var local = node.locals.get(ts.escapeLeadingUnderscores(name));
103416                     // We conservatively include alias symbols to cover cases where they're emitted as locals
103417                     if (local && local.flags & (111551 /* Value */ | 1048576 /* ExportValue */ | 2097152 /* Alias */)) {
103418                         return false;
103419                     }
103420                 }
103421             }
103422             return true;
103423         }
103424         /**
103425          * Return the next available name in the pattern _a ... _z, _0, _1, ...
103426          * TempFlags._i or TempFlags._n may be used to express a preference for that dedicated name.
103427          * Note that names generated by makeTempVariableName and makeUniqueName will never conflict.
103428          */
103429         function makeTempVariableName(flags, reservedInNestedScopes) {
103430             if (flags && !(tempFlags & flags)) {
103431                 var name = flags === 268435456 /* _i */ ? "_i" : "_n";
103432                 if (isUniqueName(name)) {
103433                     tempFlags |= flags;
103434                     if (reservedInNestedScopes) {
103435                         reserveNameInNestedScopes(name);
103436                     }
103437                     return name;
103438                 }
103439             }
103440             while (true) {
103441                 var count = tempFlags & 268435455 /* CountMask */;
103442                 tempFlags++;
103443                 // Skip over 'i' and 'n'
103444                 if (count !== 8 && count !== 13) {
103445                     var name = count < 26
103446                         ? "_" + String.fromCharCode(97 /* a */ + count)
103447                         : "_" + (count - 26);
103448                     if (isUniqueName(name)) {
103449                         if (reservedInNestedScopes) {
103450                             reserveNameInNestedScopes(name);
103451                         }
103452                         return name;
103453                     }
103454                 }
103455             }
103456         }
103457         /**
103458          * Generate a name that is unique within the current file and doesn't conflict with any names
103459          * in global scope. The name is formed by adding an '_n' suffix to the specified base name,
103460          * where n is a positive integer. Note that names generated by makeTempVariableName and
103461          * makeUniqueName are guaranteed to never conflict.
103462          * If `optimistic` is set, the first instance will use 'baseName' verbatim instead of 'baseName_1'
103463          */
103464         function makeUniqueName(baseName, checkFn, optimistic, scoped) {
103465             if (checkFn === void 0) { checkFn = isUniqueName; }
103466             if (optimistic) {
103467                 if (checkFn(baseName)) {
103468                     if (scoped) {
103469                         reserveNameInNestedScopes(baseName);
103470                     }
103471                     else {
103472                         generatedNames.add(baseName);
103473                     }
103474                     return baseName;
103475                 }
103476             }
103477             // Find the first unique 'name_n', where n is a positive number
103478             if (baseName.charCodeAt(baseName.length - 1) !== 95 /* _ */) {
103479                 baseName += "_";
103480             }
103481             var i = 1;
103482             while (true) {
103483                 var generatedName = baseName + i;
103484                 if (checkFn(generatedName)) {
103485                     if (scoped) {
103486                         reserveNameInNestedScopes(generatedName);
103487                     }
103488                     else {
103489                         generatedNames.add(generatedName);
103490                     }
103491                     return generatedName;
103492                 }
103493                 i++;
103494             }
103495         }
103496         function makeFileLevelOptimisticUniqueName(name) {
103497             return makeUniqueName(name, isFileLevelUniqueName, /*optimistic*/ true);
103498         }
103499         /**
103500          * Generates a unique name for a ModuleDeclaration or EnumDeclaration.
103501          */
103502         function generateNameForModuleOrEnum(node) {
103503             var name = getTextOfNode(node.name);
103504             // Use module/enum name itself if it is unique, otherwise make a unique variation
103505             return isUniqueLocalName(name, node) ? name : makeUniqueName(name);
103506         }
103507         /**
103508          * Generates a unique name for an ImportDeclaration or ExportDeclaration.
103509          */
103510         function generateNameForImportOrExportDeclaration(node) {
103511             var expr = ts.getExternalModuleName(node); // TODO: GH#18217
103512             var baseName = ts.isStringLiteral(expr) ?
103513                 ts.makeIdentifierFromModuleName(expr.text) : "module";
103514             return makeUniqueName(baseName);
103515         }
103516         /**
103517          * Generates a unique name for a default export.
103518          */
103519         function generateNameForExportDefault() {
103520             return makeUniqueName("default");
103521         }
103522         /**
103523          * Generates a unique name for a class expression.
103524          */
103525         function generateNameForClassExpression() {
103526             return makeUniqueName("class");
103527         }
103528         function generateNameForMethodOrAccessor(node) {
103529             if (ts.isIdentifier(node.name)) {
103530                 return generateNameCached(node.name);
103531             }
103532             return makeTempVariableName(0 /* Auto */);
103533         }
103534         /**
103535          * Generates a unique name from a node.
103536          */
103537         function generateNameForNode(node, flags) {
103538             switch (node.kind) {
103539                 case 78 /* Identifier */:
103540                     return makeUniqueName(getTextOfNode(node), isUniqueName, !!(flags & 16 /* Optimistic */), !!(flags & 8 /* ReservedInNestedScopes */));
103541                 case 256 /* ModuleDeclaration */:
103542                 case 255 /* EnumDeclaration */:
103543                     return generateNameForModuleOrEnum(node);
103544                 case 261 /* ImportDeclaration */:
103545                 case 267 /* ExportDeclaration */:
103546                     return generateNameForImportOrExportDeclaration(node);
103547                 case 251 /* FunctionDeclaration */:
103548                 case 252 /* ClassDeclaration */:
103549                 case 266 /* ExportAssignment */:
103550                     return generateNameForExportDefault();
103551                 case 221 /* ClassExpression */:
103552                     return generateNameForClassExpression();
103553                 case 165 /* MethodDeclaration */:
103554                 case 167 /* GetAccessor */:
103555                 case 168 /* SetAccessor */:
103556                     return generateNameForMethodOrAccessor(node);
103557                 case 158 /* ComputedPropertyName */:
103558                     return makeTempVariableName(0 /* Auto */, /*reserveInNestedScopes*/ true);
103559                 default:
103560                     return makeTempVariableName(0 /* Auto */);
103561             }
103562         }
103563         /**
103564          * Generates a unique identifier for a node.
103565          */
103566         function makeName(name) {
103567             switch (name.autoGenerateFlags & 7 /* KindMask */) {
103568                 case 1 /* Auto */:
103569                     return makeTempVariableName(0 /* Auto */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
103570                 case 2 /* Loop */:
103571                     return makeTempVariableName(268435456 /* _i */, !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
103572                 case 3 /* Unique */:
103573                     return makeUniqueName(ts.idText(name), (name.autoGenerateFlags & 32 /* FileLevel */) ? isFileLevelUniqueName : isUniqueName, !!(name.autoGenerateFlags & 16 /* Optimistic */), !!(name.autoGenerateFlags & 8 /* ReservedInNestedScopes */));
103574             }
103575             return ts.Debug.fail("Unsupported GeneratedIdentifierKind.");
103576         }
103577         /**
103578          * Gets the node from which a name should be generated.
103579          */
103580         function getNodeForGeneratedName(name) {
103581             var autoGenerateId = name.autoGenerateId;
103582             var node = name;
103583             var original = node.original;
103584             while (original) {
103585                 node = original;
103586                 // if "node" is a different generated name (having a different
103587                 // "autoGenerateId"), use it and stop traversing.
103588                 if (ts.isIdentifier(node)
103589                     && !!(node.autoGenerateFlags & 4 /* Node */)
103590                     && node.autoGenerateId !== autoGenerateId) {
103591                     break;
103592                 }
103593                 original = node.original;
103594             }
103595             // otherwise, return the original node for the source;
103596             return node;
103597         }
103598         // Comments
103599         function pipelineEmitWithComments(hint, node) {
103600             ts.Debug.assert(lastNode === node || lastSubstitution === node);
103601             enterComment();
103602             hasWrittenComment = false;
103603             var emitFlags = ts.getEmitFlags(node);
103604             var _a = ts.getCommentRange(node), pos = _a.pos, end = _a.end;
103605             var isEmittedNode = node.kind !== 335 /* NotEmittedStatement */;
103606             // We have to explicitly check that the node is JsxText because if the compilerOptions.jsx is "preserve" we will not do any transformation.
103607             // It is expensive to walk entire tree just to set one kind of node to have no comments.
103608             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0 || node.kind === 11 /* JsxText */;
103609             var skipTrailingComments = end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0 || node.kind === 11 /* JsxText */;
103610             // Save current container state on the stack.
103611             var savedContainerPos = containerPos;
103612             var savedContainerEnd = containerEnd;
103613             var savedDeclarationListContainerEnd = declarationListContainerEnd;
103614             if ((pos > 0 || end > 0) && pos !== end) {
103615                 // Emit leading comments if the position is not synthesized and the node
103616                 // has not opted out from emitting leading comments.
103617                 if (!skipLeadingComments) {
103618                     emitLeadingComments(pos, isEmittedNode);
103619                 }
103620                 if (!skipLeadingComments || (pos >= 0 && (emitFlags & 512 /* NoLeadingComments */) !== 0)) {
103621                     // Advance the container position if comments get emitted or if they've been disabled explicitly using NoLeadingComments.
103622                     containerPos = pos;
103623                 }
103624                 if (!skipTrailingComments || (end >= 0 && (emitFlags & 1024 /* NoTrailingComments */) !== 0)) {
103625                     // As above.
103626                     containerEnd = end;
103627                     // To avoid invalid comment emit in a down-level binding pattern, we
103628                     // keep track of the last declaration list container's end
103629                     if (node.kind === 250 /* VariableDeclarationList */) {
103630                         declarationListContainerEnd = end;
103631                     }
103632                 }
103633             }
103634             ts.forEach(ts.getSyntheticLeadingComments(node), emitLeadingSynthesizedComment);
103635             exitComment();
103636             var pipelinePhase = getNextPipelinePhase(2 /* Comments */, hint, node);
103637             if (emitFlags & 2048 /* NoNestedComments */) {
103638                 commentsDisabled = true;
103639                 pipelinePhase(hint, node);
103640                 commentsDisabled = false;
103641             }
103642             else {
103643                 pipelinePhase(hint, node);
103644             }
103645             enterComment();
103646             ts.forEach(ts.getSyntheticTrailingComments(node), emitTrailingSynthesizedComment);
103647             if ((pos > 0 || end > 0) && pos !== end) {
103648                 // Restore previous container state.
103649                 containerPos = savedContainerPos;
103650                 containerEnd = savedContainerEnd;
103651                 declarationListContainerEnd = savedDeclarationListContainerEnd;
103652                 // Emit trailing comments if the position is not synthesized and the node
103653                 // has not opted out from emitting leading comments and is an emitted node.
103654                 if (!skipTrailingComments && isEmittedNode) {
103655                     emitTrailingComments(end);
103656                 }
103657             }
103658             exitComment();
103659             ts.Debug.assert(lastNode === node || lastSubstitution === node);
103660         }
103661         function emitLeadingSynthesizedComment(comment) {
103662             if (comment.hasLeadingNewline || comment.kind === 2 /* SingleLineCommentTrivia */) {
103663                 writer.writeLine();
103664             }
103665             writeSynthesizedComment(comment);
103666             if (comment.hasTrailingNewLine || comment.kind === 2 /* SingleLineCommentTrivia */) {
103667                 writer.writeLine();
103668             }
103669             else {
103670                 writer.writeSpace(" ");
103671             }
103672         }
103673         function emitTrailingSynthesizedComment(comment) {
103674             if (!writer.isAtStartOfLine()) {
103675                 writer.writeSpace(" ");
103676             }
103677             writeSynthesizedComment(comment);
103678             if (comment.hasTrailingNewLine) {
103679                 writer.writeLine();
103680             }
103681         }
103682         function writeSynthesizedComment(comment) {
103683             var text = formatSynthesizedComment(comment);
103684             var lineMap = comment.kind === 3 /* MultiLineCommentTrivia */ ? ts.computeLineStarts(text) : undefined;
103685             ts.writeCommentRange(text, lineMap, writer, 0, text.length, newLine);
103686         }
103687         function formatSynthesizedComment(comment) {
103688             return comment.kind === 3 /* MultiLineCommentTrivia */
103689                 ? "/*" + comment.text + "*/"
103690                 : "//" + comment.text;
103691         }
103692         function emitBodyWithDetachedComments(node, detachedRange, emitCallback) {
103693             enterComment();
103694             var pos = detachedRange.pos, end = detachedRange.end;
103695             var emitFlags = ts.getEmitFlags(node);
103696             var skipLeadingComments = pos < 0 || (emitFlags & 512 /* NoLeadingComments */) !== 0;
103697             var skipTrailingComments = commentsDisabled || end < 0 || (emitFlags & 1024 /* NoTrailingComments */) !== 0;
103698             if (!skipLeadingComments) {
103699                 emitDetachedCommentsAndUpdateCommentsInfo(detachedRange);
103700             }
103701             exitComment();
103702             if (emitFlags & 2048 /* NoNestedComments */ && !commentsDisabled) {
103703                 commentsDisabled = true;
103704                 emitCallback(node);
103705                 commentsDisabled = false;
103706             }
103707             else {
103708                 emitCallback(node);
103709             }
103710             enterComment();
103711             if (!skipTrailingComments) {
103712                 emitLeadingComments(detachedRange.end, /*isEmittedNode*/ true);
103713                 if (hasWrittenComment && !writer.isAtStartOfLine()) {
103714                     writer.writeLine();
103715                 }
103716             }
103717             exitComment();
103718         }
103719         function emitLeadingComments(pos, isEmittedNode) {
103720             hasWrittenComment = false;
103721             if (isEmittedNode) {
103722                 if (pos === 0 && (currentSourceFile === null || currentSourceFile === void 0 ? void 0 : currentSourceFile.isDeclarationFile)) {
103723                     forEachLeadingCommentToEmit(pos, emitNonTripleSlashLeadingComment);
103724                 }
103725                 else {
103726                     forEachLeadingCommentToEmit(pos, emitLeadingComment);
103727                 }
103728             }
103729             else if (pos === 0) {
103730                 // If the node will not be emitted in JS, remove all the comments(normal, pinned and ///) associated with the node,
103731                 // unless it is a triple slash comment at the top of the file.
103732                 // For Example:
103733                 //      /// <reference-path ...>
103734                 //      declare var x;
103735                 //      /// <reference-path ...>
103736                 //      interface F {}
103737                 //  The first /// will NOT be removed while the second one will be removed even though both node will not be emitted
103738                 forEachLeadingCommentToEmit(pos, emitTripleSlashLeadingComment);
103739             }
103740         }
103741         function emitTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
103742             if (isTripleSlashComment(commentPos, commentEnd)) {
103743                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
103744             }
103745         }
103746         function emitNonTripleSlashLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
103747             if (!isTripleSlashComment(commentPos, commentEnd)) {
103748                 emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos);
103749             }
103750         }
103751         function shouldWriteComment(text, pos) {
103752             if (printerOptions.onlyPrintJsDocStyle) {
103753                 return (ts.isJSDocLikeText(text, pos) || ts.isPinnedComment(text, pos));
103754             }
103755             return true;
103756         }
103757         function emitLeadingComment(commentPos, commentEnd, kind, hasTrailingNewLine, rangePos) {
103758             if (!shouldWriteComment(currentSourceFile.text, commentPos))
103759                 return;
103760             if (!hasWrittenComment) {
103761                 ts.emitNewLineBeforeLeadingCommentOfPosition(getCurrentLineMap(), writer, rangePos, commentPos);
103762                 hasWrittenComment = true;
103763             }
103764             // Leading comments are emitted at /*leading comment1 */space/*leading comment*/space
103765             emitPos(commentPos);
103766             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
103767             emitPos(commentEnd);
103768             if (hasTrailingNewLine) {
103769                 writer.writeLine();
103770             }
103771             else if (kind === 3 /* MultiLineCommentTrivia */) {
103772                 writer.writeSpace(" ");
103773             }
103774         }
103775         function emitLeadingCommentsOfPosition(pos) {
103776             if (commentsDisabled || pos === -1) {
103777                 return;
103778             }
103779             emitLeadingComments(pos, /*isEmittedNode*/ true);
103780         }
103781         function emitTrailingComments(pos) {
103782             forEachTrailingCommentToEmit(pos, emitTrailingComment);
103783         }
103784         function emitTrailingComment(commentPos, commentEnd, _kind, hasTrailingNewLine) {
103785             if (!shouldWriteComment(currentSourceFile.text, commentPos))
103786                 return;
103787             // trailing comments are emitted at space/*trailing comment1 */space/*trailing comment2*/
103788             if (!writer.isAtStartOfLine()) {
103789                 writer.writeSpace(" ");
103790             }
103791             emitPos(commentPos);
103792             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
103793             emitPos(commentEnd);
103794             if (hasTrailingNewLine) {
103795                 writer.writeLine();
103796             }
103797         }
103798         function emitTrailingCommentsOfPosition(pos, prefixSpace) {
103799             if (commentsDisabled) {
103800                 return;
103801             }
103802             enterComment();
103803             forEachTrailingCommentToEmit(pos, prefixSpace ? emitTrailingComment : emitTrailingCommentOfPosition);
103804             exitComment();
103805         }
103806         function emitTrailingCommentOfPosition(commentPos, commentEnd, _kind, hasTrailingNewLine) {
103807             // trailing comments of a position are emitted at /*trailing comment1 */space/*trailing comment*/space
103808             emitPos(commentPos);
103809             ts.writeCommentRange(currentSourceFile.text, getCurrentLineMap(), writer, commentPos, commentEnd, newLine);
103810             emitPos(commentEnd);
103811             if (hasTrailingNewLine) {
103812                 writer.writeLine();
103813             }
103814             else {
103815                 writer.writeSpace(" ");
103816             }
103817         }
103818         function forEachLeadingCommentToEmit(pos, cb) {
103819             // Emit the leading comments only if the container's pos doesn't match because the container should take care of emitting these comments
103820             if (currentSourceFile && (containerPos === -1 || pos !== containerPos)) {
103821                 if (hasDetachedComments(pos)) {
103822                     forEachLeadingCommentWithoutDetachedComments(cb);
103823                 }
103824                 else {
103825                     ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
103826                 }
103827             }
103828         }
103829         function forEachTrailingCommentToEmit(end, cb) {
103830             // Emit the trailing comments only if the container's end doesn't match because the container should take care of emitting these comments
103831             if (currentSourceFile && (containerEnd === -1 || (end !== containerEnd && end !== declarationListContainerEnd))) {
103832                 ts.forEachTrailingCommentRange(currentSourceFile.text, end, cb);
103833             }
103834         }
103835         function hasDetachedComments(pos) {
103836             return detachedCommentsInfo !== undefined && ts.last(detachedCommentsInfo).nodePos === pos;
103837         }
103838         function forEachLeadingCommentWithoutDetachedComments(cb) {
103839             // get the leading comments from detachedPos
103840             var pos = ts.last(detachedCommentsInfo).detachedCommentEndPos;
103841             if (detachedCommentsInfo.length - 1) {
103842                 detachedCommentsInfo.pop();
103843             }
103844             else {
103845                 detachedCommentsInfo = undefined;
103846             }
103847             ts.forEachLeadingCommentRange(currentSourceFile.text, pos, cb, /*state*/ pos);
103848         }
103849         function emitDetachedCommentsAndUpdateCommentsInfo(range) {
103850             var currentDetachedCommentInfo = ts.emitDetachedComments(currentSourceFile.text, getCurrentLineMap(), writer, emitComment, range, newLine, commentsDisabled);
103851             if (currentDetachedCommentInfo) {
103852                 if (detachedCommentsInfo) {
103853                     detachedCommentsInfo.push(currentDetachedCommentInfo);
103854                 }
103855                 else {
103856                     detachedCommentsInfo = [currentDetachedCommentInfo];
103857                 }
103858             }
103859         }
103860         function emitComment(text, lineMap, writer, commentPos, commentEnd, newLine) {
103861             if (!shouldWriteComment(currentSourceFile.text, commentPos))
103862                 return;
103863             emitPos(commentPos);
103864             ts.writeCommentRange(text, lineMap, writer, commentPos, commentEnd, newLine);
103865             emitPos(commentEnd);
103866         }
103867         /**
103868          * Determine if the given comment is a triple-slash
103869          *
103870          * @return true if the comment is a triple-slash comment else false
103871          */
103872         function isTripleSlashComment(commentPos, commentEnd) {
103873             return ts.isRecognizedTripleSlashComment(currentSourceFile.text, commentPos, commentEnd);
103874         }
103875         // Source Maps
103876         function getParsedSourceMap(node) {
103877             if (node.parsedSourceMap === undefined && node.sourceMapText !== undefined) {
103878                 node.parsedSourceMap = ts.tryParseRawSourceMap(node.sourceMapText) || false;
103879             }
103880             return node.parsedSourceMap || undefined;
103881         }
103882         function pipelineEmitWithSourceMap(hint, node) {
103883             ts.Debug.assert(lastNode === node || lastSubstitution === node);
103884             var pipelinePhase = getNextPipelinePhase(3 /* SourceMaps */, hint, node);
103885             if (ts.isUnparsedSource(node) || ts.isUnparsedPrepend(node)) {
103886                 pipelinePhase(hint, node);
103887             }
103888             else if (ts.isUnparsedNode(node)) {
103889                 var parsed = getParsedSourceMap(node.parent);
103890                 if (parsed && sourceMapGenerator) {
103891                     sourceMapGenerator.appendSourceMap(writer.getLine(), writer.getColumn(), parsed, node.parent.sourceMapPath, node.parent.getLineAndCharacterOfPosition(node.pos), node.parent.getLineAndCharacterOfPosition(node.end));
103892                 }
103893                 pipelinePhase(hint, node);
103894             }
103895             else {
103896                 var _a = ts.getSourceMapRange(node), pos = _a.pos, end = _a.end, _b = _a.source, source = _b === void 0 ? sourceMapSource : _b;
103897                 var emitFlags = ts.getEmitFlags(node);
103898                 if (node.kind !== 335 /* NotEmittedStatement */
103899                     && (emitFlags & 16 /* NoLeadingSourceMap */) === 0
103900                     && pos >= 0) {
103901                     emitSourcePos(source, skipSourceTrivia(source, pos));
103902                 }
103903                 if (emitFlags & 64 /* NoNestedSourceMaps */) {
103904                     sourceMapsDisabled = true;
103905                     pipelinePhase(hint, node);
103906                     sourceMapsDisabled = false;
103907                 }
103908                 else {
103909                     pipelinePhase(hint, node);
103910                 }
103911                 if (node.kind !== 335 /* NotEmittedStatement */
103912                     && (emitFlags & 32 /* NoTrailingSourceMap */) === 0
103913                     && end >= 0) {
103914                     emitSourcePos(source, end);
103915                 }
103916             }
103917             ts.Debug.assert(lastNode === node || lastSubstitution === node);
103918         }
103919         /**
103920          * Skips trivia such as comments and white-space that can be optionally overridden by the source-map source
103921          */
103922         function skipSourceTrivia(source, pos) {
103923             return source.skipTrivia ? source.skipTrivia(pos) : ts.skipTrivia(source.text, pos);
103924         }
103925         /**
103926          * Emits a mapping.
103927          *
103928          * If the position is synthetic (undefined or a negative value), no mapping will be
103929          * created.
103930          *
103931          * @param pos The position.
103932          */
103933         function emitPos(pos) {
103934             if (sourceMapsDisabled || ts.positionIsSynthesized(pos) || isJsonSourceMapSource(sourceMapSource)) {
103935                 return;
103936             }
103937             var _a = ts.getLineAndCharacterOfPosition(sourceMapSource, pos), sourceLine = _a.line, sourceCharacter = _a.character;
103938             sourceMapGenerator.addMapping(writer.getLine(), writer.getColumn(), sourceMapSourceIndex, sourceLine, sourceCharacter, 
103939             /*nameIndex*/ undefined);
103940         }
103941         function emitSourcePos(source, pos) {
103942             if (source !== sourceMapSource) {
103943                 var savedSourceMapSource = sourceMapSource;
103944                 var savedSourceMapSourceIndex = sourceMapSourceIndex;
103945                 setSourceMapSource(source);
103946                 emitPos(pos);
103947                 resetSourceMapSource(savedSourceMapSource, savedSourceMapSourceIndex);
103948             }
103949             else {
103950                 emitPos(pos);
103951             }
103952         }
103953         /**
103954          * Emits a token of a node with possible leading and trailing source maps.
103955          *
103956          * @param node The node containing the token.
103957          * @param token The token to emit.
103958          * @param tokenStartPos The start pos of the token.
103959          * @param emitCallback The callback used to emit the token.
103960          */
103961         function emitTokenWithSourceMap(node, token, writer, tokenPos, emitCallback) {
103962             if (sourceMapsDisabled || node && ts.isInJsonFile(node)) {
103963                 return emitCallback(token, writer, tokenPos);
103964             }
103965             var emitNode = node && node.emitNode;
103966             var emitFlags = emitNode && emitNode.flags || 0 /* None */;
103967             var range = emitNode && emitNode.tokenSourceMapRanges && emitNode.tokenSourceMapRanges[token];
103968             var source = range && range.source || sourceMapSource;
103969             tokenPos = skipSourceTrivia(source, range ? range.pos : tokenPos);
103970             if ((emitFlags & 128 /* NoTokenLeadingSourceMaps */) === 0 && tokenPos >= 0) {
103971                 emitSourcePos(source, tokenPos);
103972             }
103973             tokenPos = emitCallback(token, writer, tokenPos);
103974             if (range)
103975                 tokenPos = range.end;
103976             if ((emitFlags & 256 /* NoTokenTrailingSourceMaps */) === 0 && tokenPos >= 0) {
103977                 emitSourcePos(source, tokenPos);
103978             }
103979             return tokenPos;
103980         }
103981         function setSourceMapSource(source) {
103982             if (sourceMapsDisabled) {
103983                 return;
103984             }
103985             sourceMapSource = source;
103986             if (source === mostRecentlyAddedSourceMapSource) {
103987                 // Fast path for when the new source map is the most recently added, in which case
103988                 // we use its captured index without going through the source map generator.
103989                 sourceMapSourceIndex = mostRecentlyAddedSourceMapSourceIndex;
103990                 return;
103991             }
103992             if (isJsonSourceMapSource(source)) {
103993                 return;
103994             }
103995             sourceMapSourceIndex = sourceMapGenerator.addSource(source.fileName);
103996             if (printerOptions.inlineSources) {
103997                 sourceMapGenerator.setSourceContent(sourceMapSourceIndex, source.text);
103998             }
103999             mostRecentlyAddedSourceMapSource = source;
104000             mostRecentlyAddedSourceMapSourceIndex = sourceMapSourceIndex;
104001         }
104002         function resetSourceMapSource(source, sourceIndex) {
104003             sourceMapSource = source;
104004             sourceMapSourceIndex = sourceIndex;
104005         }
104006         function isJsonSourceMapSource(sourceFile) {
104007             return ts.fileExtensionIs(sourceFile.fileName, ".json" /* Json */);
104008         }
104009     }
104010     ts.createPrinter = createPrinter;
104011     function createBracketsMap() {
104012         var brackets = [];
104013         brackets[1024 /* Braces */] = ["{", "}"];
104014         brackets[2048 /* Parenthesis */] = ["(", ")"];
104015         brackets[4096 /* AngleBrackets */] = ["<", ">"];
104016         brackets[8192 /* SquareBrackets */] = ["[", "]"];
104017         return brackets;
104018     }
104019     function getOpeningBracket(format) {
104020         return brackets[format & 15360 /* BracketsMask */][0];
104021     }
104022     function getClosingBracket(format) {
104023         return brackets[format & 15360 /* BracketsMask */][1];
104024     }
104025     // Flags enum to track count of temp variables and a few dedicated names
104026     var TempFlags;
104027     (function (TempFlags) {
104028         TempFlags[TempFlags["Auto"] = 0] = "Auto";
104029         TempFlags[TempFlags["CountMask"] = 268435455] = "CountMask";
104030         TempFlags[TempFlags["_i"] = 268435456] = "_i";
104031     })(TempFlags || (TempFlags = {}));
104032 })(ts || (ts = {}));
104033 /* @internal */
104034 var ts;
104035 (function (ts) {
104036     function createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames) {
104037         if (!host.getDirectories || !host.readDirectory) {
104038             return undefined;
104039         }
104040         var cachedReadDirectoryResult = new ts.Map();
104041         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
104042         return {
104043             useCaseSensitiveFileNames: useCaseSensitiveFileNames,
104044             fileExists: fileExists,
104045             readFile: function (path, encoding) { return host.readFile(path, encoding); },
104046             directoryExists: host.directoryExists && directoryExists,
104047             getDirectories: getDirectories,
104048             readDirectory: readDirectory,
104049             createDirectory: host.createDirectory && createDirectory,
104050             writeFile: host.writeFile && writeFile,
104051             addOrDeleteFileOrDirectory: addOrDeleteFileOrDirectory,
104052             addOrDeleteFile: addOrDeleteFile,
104053             clearCache: clearCache,
104054             realpath: host.realpath && realpath
104055         };
104056         function toPath(fileName) {
104057             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
104058         }
104059         function getCachedFileSystemEntries(rootDirPath) {
104060             return cachedReadDirectoryResult.get(ts.ensureTrailingDirectorySeparator(rootDirPath));
104061         }
104062         function getCachedFileSystemEntriesForBaseDir(path) {
104063             return getCachedFileSystemEntries(ts.getDirectoryPath(path));
104064         }
104065         function getBaseNameOfFileName(fileName) {
104066             return ts.getBaseFileName(ts.normalizePath(fileName));
104067         }
104068         function createCachedFileSystemEntries(rootDir, rootDirPath) {
104069             var resultFromHost = {
104070                 files: ts.map(host.readDirectory(rootDir, /*extensions*/ undefined, /*exclude*/ undefined, /*include*/ ["*.*"]), getBaseNameOfFileName) || [],
104071                 directories: host.getDirectories(rootDir) || []
104072             };
104073             cachedReadDirectoryResult.set(ts.ensureTrailingDirectorySeparator(rootDirPath), resultFromHost);
104074             return resultFromHost;
104075         }
104076         /**
104077          * If the readDirectory result was already cached, it returns that
104078          * Otherwise gets result from host and caches it.
104079          * The host request is done under try catch block to avoid caching incorrect result
104080          */
104081         function tryReadDirectory(rootDir, rootDirPath) {
104082             rootDirPath = ts.ensureTrailingDirectorySeparator(rootDirPath);
104083             var cachedResult = getCachedFileSystemEntries(rootDirPath);
104084             if (cachedResult) {
104085                 return cachedResult;
104086             }
104087             try {
104088                 return createCachedFileSystemEntries(rootDir, rootDirPath);
104089             }
104090             catch (_e) {
104091                 // If there is exception to read directories, dont cache the result and direct the calls to host
104092                 ts.Debug.assert(!cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(rootDirPath)));
104093                 return undefined;
104094             }
104095         }
104096         function fileNameEqual(name1, name2) {
104097             return getCanonicalFileName(name1) === getCanonicalFileName(name2);
104098         }
104099         function hasEntry(entries, name) {
104100             return ts.some(entries, function (file) { return fileNameEqual(file, name); });
104101         }
104102         function updateFileSystemEntry(entries, baseName, isValid) {
104103             if (hasEntry(entries, baseName)) {
104104                 if (!isValid) {
104105                     return ts.filterMutate(entries, function (entry) { return !fileNameEqual(entry, baseName); });
104106                 }
104107             }
104108             else if (isValid) {
104109                 return entries.push(baseName);
104110             }
104111         }
104112         function writeFile(fileName, data, writeByteOrderMark) {
104113             var path = toPath(fileName);
104114             var result = getCachedFileSystemEntriesForBaseDir(path);
104115             if (result) {
104116                 updateFilesOfFileSystemEntry(result, getBaseNameOfFileName(fileName), /*fileExists*/ true);
104117             }
104118             return host.writeFile(fileName, data, writeByteOrderMark);
104119         }
104120         function fileExists(fileName) {
104121             var path = toPath(fileName);
104122             var result = getCachedFileSystemEntriesForBaseDir(path);
104123             return result && hasEntry(result.files, getBaseNameOfFileName(fileName)) ||
104124                 host.fileExists(fileName);
104125         }
104126         function directoryExists(dirPath) {
104127             var path = toPath(dirPath);
104128             return cachedReadDirectoryResult.has(ts.ensureTrailingDirectorySeparator(path)) || host.directoryExists(dirPath);
104129         }
104130         function createDirectory(dirPath) {
104131             var path = toPath(dirPath);
104132             var result = getCachedFileSystemEntriesForBaseDir(path);
104133             var baseFileName = getBaseNameOfFileName(dirPath);
104134             if (result) {
104135                 updateFileSystemEntry(result.directories, baseFileName, /*isValid*/ true);
104136             }
104137             host.createDirectory(dirPath);
104138         }
104139         function getDirectories(rootDir) {
104140             var rootDirPath = toPath(rootDir);
104141             var result = tryReadDirectory(rootDir, rootDirPath);
104142             if (result) {
104143                 return result.directories.slice();
104144             }
104145             return host.getDirectories(rootDir);
104146         }
104147         function readDirectory(rootDir, extensions, excludes, includes, depth) {
104148             var rootDirPath = toPath(rootDir);
104149             var result = tryReadDirectory(rootDir, rootDirPath);
104150             if (result) {
104151                 return ts.matchFiles(rootDir, extensions, excludes, includes, useCaseSensitiveFileNames, currentDirectory, depth, getFileSystemEntries, realpath);
104152             }
104153             return host.readDirectory(rootDir, extensions, excludes, includes, depth);
104154             function getFileSystemEntries(dir) {
104155                 var path = toPath(dir);
104156                 if (path === rootDirPath) {
104157                     return result;
104158                 }
104159                 return tryReadDirectory(dir, path) || ts.emptyFileSystemEntries;
104160             }
104161         }
104162         function realpath(s) {
104163             return host.realpath ? host.realpath(s) : s;
104164         }
104165         function addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath) {
104166             var existingResult = getCachedFileSystemEntries(fileOrDirectoryPath);
104167             if (existingResult) {
104168                 // Just clear the cache for now
104169                 // For now just clear the cache, since this could mean that multiple level entries might need to be re-evaluated
104170                 clearCache();
104171                 return undefined;
104172             }
104173             var parentResult = getCachedFileSystemEntriesForBaseDir(fileOrDirectoryPath);
104174             if (!parentResult) {
104175                 return undefined;
104176             }
104177             // This was earlier a file (hence not in cached directory contents)
104178             // or we never cached the directory containing it
104179             if (!host.directoryExists) {
104180                 // Since host doesnt support directory exists, clear the cache as otherwise it might not be same
104181                 clearCache();
104182                 return undefined;
104183             }
104184             var baseName = getBaseNameOfFileName(fileOrDirectory);
104185             var fsQueryResult = {
104186                 fileExists: host.fileExists(fileOrDirectoryPath),
104187                 directoryExists: host.directoryExists(fileOrDirectoryPath)
104188             };
104189             if (fsQueryResult.directoryExists || hasEntry(parentResult.directories, baseName)) {
104190                 // Folder added or removed, clear the cache instead of updating the folder and its structure
104191                 clearCache();
104192             }
104193             else {
104194                 // No need to update the directory structure, just files
104195                 updateFilesOfFileSystemEntry(parentResult, baseName, fsQueryResult.fileExists);
104196             }
104197             return fsQueryResult;
104198         }
104199         function addOrDeleteFile(fileName, filePath, eventKind) {
104200             if (eventKind === ts.FileWatcherEventKind.Changed) {
104201                 return;
104202             }
104203             var parentResult = getCachedFileSystemEntriesForBaseDir(filePath);
104204             if (parentResult) {
104205                 updateFilesOfFileSystemEntry(parentResult, getBaseNameOfFileName(fileName), eventKind === ts.FileWatcherEventKind.Created);
104206             }
104207         }
104208         function updateFilesOfFileSystemEntry(parentResult, baseName, fileExists) {
104209             updateFileSystemEntry(parentResult.files, baseName, fileExists);
104210         }
104211         function clearCache() {
104212             cachedReadDirectoryResult.clear();
104213         }
104214     }
104215     ts.createCachedDirectoryStructureHost = createCachedDirectoryStructureHost;
104216     var ConfigFileProgramReloadLevel;
104217     (function (ConfigFileProgramReloadLevel) {
104218         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["None"] = 0] = "None";
104219         /** Update the file name list from the disk */
104220         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Partial"] = 1] = "Partial";
104221         /** Reload completely by re-reading contents of config file from disk and updating program */
104222         ConfigFileProgramReloadLevel[ConfigFileProgramReloadLevel["Full"] = 2] = "Full";
104223     })(ConfigFileProgramReloadLevel = ts.ConfigFileProgramReloadLevel || (ts.ConfigFileProgramReloadLevel = {}));
104224     /**
104225      * Updates the existing missing file watches with the new set of missing files after new program is created
104226      */
104227     function updateMissingFilePathsWatch(program, missingFileWatches, createMissingFileWatch) {
104228         var missingFilePaths = program.getMissingFilePaths();
104229         // TODO(rbuckton): Should be a `Set` but that requires changing the below code that uses `mutateMap`
104230         var newMissingFilePathMap = ts.arrayToMap(missingFilePaths, ts.identity, ts.returnTrue);
104231         // Update the missing file paths watcher
104232         ts.mutateMap(missingFileWatches, newMissingFilePathMap, {
104233             // Watch the missing files
104234             createNewValue: createMissingFileWatch,
104235             // Files that are no longer missing (e.g. because they are no longer required)
104236             // should no longer be watched.
104237             onDeleteValue: ts.closeFileWatcher
104238         });
104239     }
104240     ts.updateMissingFilePathsWatch = updateMissingFilePathsWatch;
104241     /**
104242      * Updates the existing wild card directory watches with the new set of wild card directories from the config file
104243      * after new program is created because the config file was reloaded or program was created first time from the config file
104244      * Note that there is no need to call this function when the program is updated with additional files without reloading config files,
104245      * as wildcard directories wont change unless reloading config file
104246      */
104247     function updateWatchingWildcardDirectories(existingWatchedForWildcards, wildcardDirectories, watchDirectory) {
104248         ts.mutateMap(existingWatchedForWildcards, wildcardDirectories, {
104249             // Create new watch and recursive info
104250             createNewValue: createWildcardDirectoryWatcher,
104251             // Close existing watch thats not needed any more
104252             onDeleteValue: closeFileWatcherOf,
104253             // Close existing watch that doesnt match in the flags
104254             onExistingValue: updateWildcardDirectoryWatcher
104255         });
104256         function createWildcardDirectoryWatcher(directory, flags) {
104257             // Create new watch and recursive info
104258             return {
104259                 watcher: watchDirectory(directory, flags),
104260                 flags: flags
104261             };
104262         }
104263         function updateWildcardDirectoryWatcher(existingWatcher, flags, directory) {
104264             // Watcher needs to be updated if the recursive flags dont match
104265             if (existingWatcher.flags === flags) {
104266                 return;
104267             }
104268             existingWatcher.watcher.close();
104269             existingWatchedForWildcards.set(directory, createWildcardDirectoryWatcher(directory, flags));
104270         }
104271     }
104272     ts.updateWatchingWildcardDirectories = updateWatchingWildcardDirectories;
104273     /* @internal */
104274     function isIgnoredFileFromWildCardWatching(_a) {
104275         var watchedDirPath = _a.watchedDirPath, fileOrDirectory = _a.fileOrDirectory, fileOrDirectoryPath = _a.fileOrDirectoryPath, configFileName = _a.configFileName, options = _a.options, configFileSpecs = _a.configFileSpecs, program = _a.program, extraFileExtensions = _a.extraFileExtensions, currentDirectory = _a.currentDirectory, useCaseSensitiveFileNames = _a.useCaseSensitiveFileNames, writeLog = _a.writeLog;
104276         var newPath = ts.removeIgnoredPath(fileOrDirectoryPath);
104277         if (!newPath) {
104278             writeLog("Project: " + configFileName + " Detected ignored path: " + fileOrDirectory);
104279             return true;
104280         }
104281         fileOrDirectoryPath = newPath;
104282         if (fileOrDirectoryPath === watchedDirPath)
104283             return false;
104284         // If the the added or created file or directory is not supported file name, ignore the file
104285         // But when watched directory is added/removed, we need to reload the file list
104286         if (ts.hasExtension(fileOrDirectoryPath) && !ts.isSupportedSourceFileName(fileOrDirectory, options, extraFileExtensions)) {
104287             writeLog("Project: " + configFileName + " Detected file add/remove of non supported extension: " + fileOrDirectory);
104288             return true;
104289         }
104290         if (ts.isExcludedFile(fileOrDirectory, configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), useCaseSensitiveFileNames, currentDirectory)) {
104291             writeLog("Project: " + configFileName + " Detected excluded file: " + fileOrDirectory);
104292             return true;
104293         }
104294         if (!program)
104295             return false;
104296         // We want to ignore emit file check if file is not going to be emitted next to source file
104297         // In that case we follow config file inclusion rules
104298         if (options.outFile || options.outDir)
104299             return false;
104300         // File if emitted next to input needs to be ignored
104301         if (ts.fileExtensionIs(fileOrDirectoryPath, ".d.ts" /* Dts */)) {
104302             // If its declaration directory: its not ignored if not excluded by config
104303             if (options.declarationDir)
104304                 return false;
104305         }
104306         else if (!ts.fileExtensionIsOneOf(fileOrDirectoryPath, ts.supportedJSExtensions)) {
104307             return false;
104308         }
104309         // just check if sourceFile with the name exists
104310         var filePathWithoutExtension = ts.removeFileExtension(fileOrDirectoryPath);
104311         var realProgram = isBuilderProgram(program) ? program.getProgramOrUndefined() : program;
104312         if (hasSourceFile((filePathWithoutExtension + ".ts" /* Ts */)) ||
104313             hasSourceFile((filePathWithoutExtension + ".tsx" /* Tsx */))) {
104314             writeLog("Project: " + configFileName + " Detected output file: " + fileOrDirectory);
104315             return true;
104316         }
104317         return false;
104318         function hasSourceFile(file) {
104319             return realProgram ?
104320                 !!realProgram.getSourceFileByPath(file) :
104321                 program.getState().fileInfos.has(file);
104322         }
104323     }
104324     ts.isIgnoredFileFromWildCardWatching = isIgnoredFileFromWildCardWatching;
104325     function isBuilderProgram(program) {
104326         return !!program.getState;
104327     }
104328     function isEmittedFileOfProgram(program, file) {
104329         if (!program) {
104330             return false;
104331         }
104332         return program.isEmittedFile(file);
104333     }
104334     ts.isEmittedFileOfProgram = isEmittedFileOfProgram;
104335     var WatchLogLevel;
104336     (function (WatchLogLevel) {
104337         WatchLogLevel[WatchLogLevel["None"] = 0] = "None";
104338         WatchLogLevel[WatchLogLevel["TriggerOnly"] = 1] = "TriggerOnly";
104339         WatchLogLevel[WatchLogLevel["Verbose"] = 2] = "Verbose";
104340     })(WatchLogLevel = ts.WatchLogLevel || (ts.WatchLogLevel = {}));
104341     function getWatchFactory(watchLogLevel, log, getDetailWatchInfo) {
104342         return getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory);
104343     }
104344     ts.getWatchFactory = getWatchFactory;
104345     function getWatchFactoryWith(watchLogLevel, log, getDetailWatchInfo, watchFile, watchDirectory) {
104346         var createFileWatcher = getCreateFileWatcher(watchLogLevel, watchFile);
104347         var createFilePathWatcher = watchLogLevel === WatchLogLevel.None ? watchFilePath : createFileWatcher;
104348         var createDirectoryWatcher = getCreateFileWatcher(watchLogLevel, watchDirectory);
104349         if (watchLogLevel === WatchLogLevel.Verbose && ts.sysLog === ts.noop) {
104350             ts.setSysLog(function (s) { return log(s); });
104351         }
104352         return {
104353             watchFile: function (host, file, callback, pollingInterval, options, detailInfo1, detailInfo2) {
104354                 return createFileWatcher(host, file, callback, pollingInterval, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
104355             },
104356             watchFilePath: function (host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2) {
104357                 return createFilePathWatcher(host, file, callback, pollingInterval, options, path, detailInfo1, detailInfo2, watchFile, log, "FileWatcher", getDetailWatchInfo);
104358             },
104359             watchDirectory: function (host, directory, callback, flags, options, detailInfo1, detailInfo2) {
104360                 return createDirectoryWatcher(host, directory, callback, flags, options, /*passThrough*/ undefined, detailInfo1, detailInfo2, watchDirectory, log, "DirectoryWatcher", getDetailWatchInfo);
104361             }
104362         };
104363     }
104364     function watchFile(host, file, callback, pollingInterval, options) {
104365         return host.watchFile(file, callback, pollingInterval, options);
104366     }
104367     function watchFilePath(host, file, callback, pollingInterval, options, path) {
104368         return watchFile(host, file, function (fileName, eventKind) { return callback(fileName, eventKind, path); }, pollingInterval, options);
104369     }
104370     function watchDirectory(host, directory, callback, flags, options) {
104371         return host.watchDirectory(directory, callback, (flags & 1 /* Recursive */) !== 0, options);
104372     }
104373     function getCreateFileWatcher(watchLogLevel, addWatch) {
104374         switch (watchLogLevel) {
104375             case WatchLogLevel.None:
104376                 return addWatch;
104377             case WatchLogLevel.TriggerOnly:
104378                 return createFileWatcherWithTriggerLogging;
104379             case WatchLogLevel.Verbose:
104380                 return addWatch === watchDirectory ? createDirectoryWatcherWithLogging : createFileWatcherWithLogging;
104381         }
104382     }
104383     function createFileWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
104384         log(watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
104385         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
104386         return {
104387             close: function () {
104388                 log(watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo));
104389                 watcher.close();
104390             }
104391         };
104392     }
104393     function createDirectoryWatcherWithLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
104394         var watchInfo = watchCaption + ":: Added:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
104395         log(watchInfo);
104396         var start = ts.timestamp();
104397         var watcher = createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo);
104398         var elapsed = ts.timestamp() - start;
104399         log("Elapsed:: " + elapsed + "ms " + watchInfo);
104400         return {
104401             close: function () {
104402                 var watchInfo = watchCaption + ":: Close:: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
104403                 log(watchInfo);
104404                 var start = ts.timestamp();
104405                 watcher.close();
104406                 var elapsed = ts.timestamp() - start;
104407                 log("Elapsed:: " + elapsed + "ms " + watchInfo);
104408             }
104409         };
104410     }
104411     function createFileWatcherWithTriggerLogging(host, file, cb, flags, options, passThrough, detailInfo1, detailInfo2, addWatch, log, watchCaption, getDetailWatchInfo) {
104412         return addWatch(host, file, function (fileName, cbOptional) {
104413             var triggerredInfo = watchCaption + ":: Triggered with " + fileName + " " + (cbOptional !== undefined ? cbOptional : "") + ":: " + getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo);
104414             log(triggerredInfo);
104415             var start = ts.timestamp();
104416             cb(fileName, cbOptional, passThrough);
104417             var elapsed = ts.timestamp() - start;
104418             log("Elapsed:: " + elapsed + "ms " + triggerredInfo);
104419         }, flags, options);
104420     }
104421     function getFallbackOptions(options) {
104422         var fallbackPolling = options === null || options === void 0 ? void 0 : options.fallbackPolling;
104423         return {
104424             watchFile: fallbackPolling !== undefined ?
104425                 fallbackPolling :
104426                 ts.WatchFileKind.PriorityPollingInterval
104427         };
104428     }
104429     ts.getFallbackOptions = getFallbackOptions;
104430     function getWatchInfo(file, flags, options, detailInfo1, detailInfo2, getDetailWatchInfo) {
104431         return "WatchInfo: " + file + " " + flags + " " + JSON.stringify(options) + " " + (getDetailWatchInfo ? getDetailWatchInfo(detailInfo1, detailInfo2) : detailInfo2 === undefined ? detailInfo1 : detailInfo1 + " " + detailInfo2);
104432     }
104433     function closeFileWatcherOf(objWithWatcher) {
104434         objWithWatcher.watcher.close();
104435     }
104436     ts.closeFileWatcherOf = closeFileWatcherOf;
104437 })(ts || (ts = {}));
104438 var ts;
104439 (function (ts) {
104440     function findConfigFile(searchPath, fileExists, configName) {
104441         if (configName === void 0) { configName = "tsconfig.json"; }
104442         return ts.forEachAncestorDirectory(searchPath, function (ancestor) {
104443             var fileName = ts.combinePaths(ancestor, configName);
104444             return fileExists(fileName) ? fileName : undefined;
104445         });
104446     }
104447     ts.findConfigFile = findConfigFile;
104448     function resolveTripleslashReference(moduleName, containingFile) {
104449         var basePath = ts.getDirectoryPath(containingFile);
104450         var referencedFileName = ts.isRootedDiskPath(moduleName) ? moduleName : ts.combinePaths(basePath, moduleName);
104451         return ts.normalizePath(referencedFileName);
104452     }
104453     ts.resolveTripleslashReference = resolveTripleslashReference;
104454     /* @internal */
104455     function computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName) {
104456         var commonPathComponents;
104457         var failed = ts.forEach(fileNames, function (sourceFile) {
104458             // Each file contributes into common source file path
104459             var sourcePathComponents = ts.getNormalizedPathComponents(sourceFile, currentDirectory);
104460             sourcePathComponents.pop(); // The base file name is not part of the common directory path
104461             if (!commonPathComponents) {
104462                 // first file
104463                 commonPathComponents = sourcePathComponents;
104464                 return;
104465             }
104466             var n = Math.min(commonPathComponents.length, sourcePathComponents.length);
104467             for (var i = 0; i < n; i++) {
104468                 if (getCanonicalFileName(commonPathComponents[i]) !== getCanonicalFileName(sourcePathComponents[i])) {
104469                     if (i === 0) {
104470                         // Failed to find any common path component
104471                         return true;
104472                     }
104473                     // New common path found that is 0 -> i-1
104474                     commonPathComponents.length = i;
104475                     break;
104476                 }
104477             }
104478             // If the sourcePathComponents was shorter than the commonPathComponents, truncate to the sourcePathComponents
104479             if (sourcePathComponents.length < commonPathComponents.length) {
104480                 commonPathComponents.length = sourcePathComponents.length;
104481             }
104482         });
104483         // A common path can not be found when paths span multiple drives on windows, for example
104484         if (failed) {
104485             return "";
104486         }
104487         if (!commonPathComponents) { // Can happen when all input files are .d.ts files
104488             return currentDirectory;
104489         }
104490         return ts.getPathFromPathComponents(commonPathComponents);
104491     }
104492     ts.computeCommonSourceDirectoryOfFilenames = computeCommonSourceDirectoryOfFilenames;
104493     function createCompilerHost(options, setParentNodes) {
104494         return createCompilerHostWorker(options, setParentNodes);
104495     }
104496     ts.createCompilerHost = createCompilerHost;
104497     /*@internal*/
104498     // TODO(shkamat): update this after reworking ts build API
104499     function createCompilerHostWorker(options, setParentNodes, system) {
104500         if (system === void 0) { system = ts.sys; }
104501         var existingDirectories = new ts.Map();
104502         var getCanonicalFileName = ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames);
104503         var computeHash = ts.maybeBind(system, system.createHash) || ts.generateDjb2Hash;
104504         function getSourceFile(fileName, languageVersion, onError) {
104505             var text;
104506             try {
104507                 ts.performance.mark("beforeIORead");
104508                 text = compilerHost.readFile(fileName);
104509                 ts.performance.mark("afterIORead");
104510                 ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
104511             }
104512             catch (e) {
104513                 if (onError) {
104514                     onError(e.message);
104515                 }
104516                 text = "";
104517             }
104518             return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion, setParentNodes) : undefined;
104519         }
104520         function directoryExists(directoryPath) {
104521             if (existingDirectories.has(directoryPath)) {
104522                 return true;
104523             }
104524             if ((compilerHost.directoryExists || system.directoryExists)(directoryPath)) {
104525                 existingDirectories.set(directoryPath, true);
104526                 return true;
104527             }
104528             return false;
104529         }
104530         function writeFile(fileName, data, writeByteOrderMark, onError) {
104531             try {
104532                 ts.performance.mark("beforeIOWrite");
104533                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
104534                 // the system.writeFile will do its own directory creation and
104535                 // the ensureDirectoriesExist call will always be redundant.
104536                 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); });
104537                 ts.performance.mark("afterIOWrite");
104538                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
104539             }
104540             catch (e) {
104541                 if (onError) {
104542                     onError(e.message);
104543                 }
104544             }
104545         }
104546         var outputFingerprints;
104547         function writeFileWorker(fileName, data, writeByteOrderMark) {
104548             if (!ts.isWatchSet(options) || !system.getModifiedTime) {
104549                 system.writeFile(fileName, data, writeByteOrderMark);
104550                 return;
104551             }
104552             if (!outputFingerprints) {
104553                 outputFingerprints = new ts.Map();
104554             }
104555             var hash = computeHash(data);
104556             var mtimeBefore = system.getModifiedTime(fileName);
104557             if (mtimeBefore) {
104558                 var fingerprint = outputFingerprints.get(fileName);
104559                 // If output has not been changed, and the file has no external modification
104560                 if (fingerprint &&
104561                     fingerprint.byteOrderMark === writeByteOrderMark &&
104562                     fingerprint.hash === hash &&
104563                     fingerprint.mtime.getTime() === mtimeBefore.getTime()) {
104564                     return;
104565                 }
104566             }
104567             system.writeFile(fileName, data, writeByteOrderMark);
104568             var mtimeAfter = system.getModifiedTime(fileName) || ts.missingFileModifiedTime;
104569             outputFingerprints.set(fileName, {
104570                 hash: hash,
104571                 byteOrderMark: writeByteOrderMark,
104572                 mtime: mtimeAfter
104573             });
104574         }
104575         function getDefaultLibLocation() {
104576             return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath()));
104577         }
104578         var newLine = ts.getNewLineCharacter(options, function () { return system.newLine; });
104579         var realpath = system.realpath && (function (path) { return system.realpath(path); });
104580         var compilerHost = {
104581             getSourceFile: getSourceFile,
104582             getDefaultLibLocation: getDefaultLibLocation,
104583             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
104584             writeFile: writeFile,
104585             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
104586             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
104587             getCanonicalFileName: getCanonicalFileName,
104588             getNewLine: function () { return newLine; },
104589             fileExists: function (fileName) { return system.fileExists(fileName); },
104590             readFile: function (fileName) { return system.readFile(fileName); },
104591             trace: function (s) { return system.write(s + newLine); },
104592             directoryExists: function (directoryName) { return system.directoryExists(directoryName); },
104593             getEnvironmentVariable: function (name) { return system.getEnvironmentVariable ? system.getEnvironmentVariable(name) : ""; },
104594             getDirectories: function (path) { return system.getDirectories(path); },
104595             realpath: realpath,
104596             readDirectory: function (path, extensions, include, exclude, depth) { return system.readDirectory(path, extensions, include, exclude, depth); },
104597             createDirectory: function (d) { return system.createDirectory(d); },
104598             createHash: ts.maybeBind(system, system.createHash)
104599         };
104600         return compilerHost;
104601     }
104602     ts.createCompilerHostWorker = createCompilerHostWorker;
104603     /*@internal*/
104604     function changeCompilerHostLikeToUseCache(host, toPath, getSourceFile) {
104605         var originalReadFile = host.readFile;
104606         var originalFileExists = host.fileExists;
104607         var originalDirectoryExists = host.directoryExists;
104608         var originalCreateDirectory = host.createDirectory;
104609         var originalWriteFile = host.writeFile;
104610         var readFileCache = new ts.Map();
104611         var fileExistsCache = new ts.Map();
104612         var directoryExistsCache = new ts.Map();
104613         var sourceFileCache = new ts.Map();
104614         var readFileWithCache = function (fileName) {
104615             var key = toPath(fileName);
104616             var value = readFileCache.get(key);
104617             if (value !== undefined)
104618                 return value !== false ? value : undefined;
104619             return setReadFileCache(key, fileName);
104620         };
104621         var setReadFileCache = function (key, fileName) {
104622             var newValue = originalReadFile.call(host, fileName);
104623             readFileCache.set(key, newValue !== undefined ? newValue : false);
104624             return newValue;
104625         };
104626         host.readFile = function (fileName) {
104627             var key = toPath(fileName);
104628             var value = readFileCache.get(key);
104629             if (value !== undefined)
104630                 return value !== false ? value : undefined; // could be .d.ts from output
104631             // Cache json or buildInfo
104632             if (!ts.fileExtensionIs(fileName, ".json" /* Json */) && !ts.isBuildInfoFile(fileName)) {
104633                 return originalReadFile.call(host, fileName);
104634             }
104635             return setReadFileCache(key, fileName);
104636         };
104637         var getSourceFileWithCache = getSourceFile ? function (fileName, languageVersion, onError, shouldCreateNewSourceFile) {
104638             var key = toPath(fileName);
104639             var value = sourceFileCache.get(key);
104640             if (value)
104641                 return value;
104642             var sourceFile = getSourceFile(fileName, languageVersion, onError, shouldCreateNewSourceFile);
104643             if (sourceFile && (ts.isDeclarationFileName(fileName) || ts.fileExtensionIs(fileName, ".json" /* Json */))) {
104644                 sourceFileCache.set(key, sourceFile);
104645             }
104646             return sourceFile;
104647         } : undefined;
104648         // fileExists for any kind of extension
104649         host.fileExists = function (fileName) {
104650             var key = toPath(fileName);
104651             var value = fileExistsCache.get(key);
104652             if (value !== undefined)
104653                 return value;
104654             var newValue = originalFileExists.call(host, fileName);
104655             fileExistsCache.set(key, !!newValue);
104656             return newValue;
104657         };
104658         if (originalWriteFile) {
104659             host.writeFile = function (fileName, data, writeByteOrderMark, onError, sourceFiles) {
104660                 var key = toPath(fileName);
104661                 fileExistsCache.delete(key);
104662                 var value = readFileCache.get(key);
104663                 if (value !== undefined && value !== data) {
104664                     readFileCache.delete(key);
104665                     sourceFileCache.delete(key);
104666                 }
104667                 else if (getSourceFileWithCache) {
104668                     var sourceFile = sourceFileCache.get(key);
104669                     if (sourceFile && sourceFile.text !== data) {
104670                         sourceFileCache.delete(key);
104671                     }
104672                 }
104673                 originalWriteFile.call(host, fileName, data, writeByteOrderMark, onError, sourceFiles);
104674             };
104675         }
104676         // directoryExists
104677         if (originalDirectoryExists && originalCreateDirectory) {
104678             host.directoryExists = function (directory) {
104679                 var key = toPath(directory);
104680                 var value = directoryExistsCache.get(key);
104681                 if (value !== undefined)
104682                     return value;
104683                 var newValue = originalDirectoryExists.call(host, directory);
104684                 directoryExistsCache.set(key, !!newValue);
104685                 return newValue;
104686             };
104687             host.createDirectory = function (directory) {
104688                 var key = toPath(directory);
104689                 directoryExistsCache.delete(key);
104690                 originalCreateDirectory.call(host, directory);
104691             };
104692         }
104693         return {
104694             originalReadFile: originalReadFile,
104695             originalFileExists: originalFileExists,
104696             originalDirectoryExists: originalDirectoryExists,
104697             originalCreateDirectory: originalCreateDirectory,
104698             originalWriteFile: originalWriteFile,
104699             getSourceFileWithCache: getSourceFileWithCache,
104700             readFileWithCache: readFileWithCache
104701         };
104702     }
104703     ts.changeCompilerHostLikeToUseCache = changeCompilerHostLikeToUseCache;
104704     function getPreEmitDiagnostics(program, sourceFile, cancellationToken) {
104705         var diagnostics;
104706         diagnostics = ts.addRange(diagnostics, program.getConfigFileParsingDiagnostics());
104707         diagnostics = ts.addRange(diagnostics, program.getOptionsDiagnostics(cancellationToken));
104708         diagnostics = ts.addRange(diagnostics, program.getSyntacticDiagnostics(sourceFile, cancellationToken));
104709         diagnostics = ts.addRange(diagnostics, program.getGlobalDiagnostics(cancellationToken));
104710         diagnostics = ts.addRange(diagnostics, program.getSemanticDiagnostics(sourceFile, cancellationToken));
104711         if (ts.getEmitDeclarations(program.getCompilerOptions())) {
104712             diagnostics = ts.addRange(diagnostics, program.getDeclarationDiagnostics(sourceFile, cancellationToken));
104713         }
104714         return ts.sortAndDeduplicateDiagnostics(diagnostics || ts.emptyArray);
104715     }
104716     ts.getPreEmitDiagnostics = getPreEmitDiagnostics;
104717     function formatDiagnostics(diagnostics, host) {
104718         var output = "";
104719         for (var _i = 0, diagnostics_3 = diagnostics; _i < diagnostics_3.length; _i++) {
104720             var diagnostic = diagnostics_3[_i];
104721             output += formatDiagnostic(diagnostic, host);
104722         }
104723         return output;
104724     }
104725     ts.formatDiagnostics = formatDiagnostics;
104726     function formatDiagnostic(diagnostic, host) {
104727         var errorMessage = ts.diagnosticCategoryName(diagnostic) + " TS" + diagnostic.code + ": " + flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine()) + host.getNewLine();
104728         if (diagnostic.file) {
104729             var _a = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start), line = _a.line, character = _a.character; // TODO: GH#18217
104730             var fileName = diagnostic.file.fileName;
104731             var relativeFileName = ts.convertToRelativePath(fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); });
104732             return relativeFileName + "(" + (line + 1) + "," + (character + 1) + "): " + errorMessage;
104733         }
104734         return errorMessage;
104735     }
104736     ts.formatDiagnostic = formatDiagnostic;
104737     /** @internal */
104738     var ForegroundColorEscapeSequences;
104739     (function (ForegroundColorEscapeSequences) {
104740         ForegroundColorEscapeSequences["Grey"] = "\u001B[90m";
104741         ForegroundColorEscapeSequences["Red"] = "\u001B[91m";
104742         ForegroundColorEscapeSequences["Yellow"] = "\u001B[93m";
104743         ForegroundColorEscapeSequences["Blue"] = "\u001B[94m";
104744         ForegroundColorEscapeSequences["Cyan"] = "\u001B[96m";
104745     })(ForegroundColorEscapeSequences = ts.ForegroundColorEscapeSequences || (ts.ForegroundColorEscapeSequences = {}));
104746     var gutterStyleSequence = "\u001b[7m";
104747     var gutterSeparator = " ";
104748     var resetEscapeSequence = "\u001b[0m";
104749     var ellipsis = "...";
104750     var halfIndent = "  ";
104751     var indent = "    ";
104752     function getCategoryFormat(category) {
104753         switch (category) {
104754             case ts.DiagnosticCategory.Error: return ForegroundColorEscapeSequences.Red;
104755             case ts.DiagnosticCategory.Warning: return ForegroundColorEscapeSequences.Yellow;
104756             case ts.DiagnosticCategory.Suggestion: return ts.Debug.fail("Should never get an Info diagnostic on the command line.");
104757             case ts.DiagnosticCategory.Message: return ForegroundColorEscapeSequences.Blue;
104758         }
104759     }
104760     /** @internal */
104761     function formatColorAndReset(text, formatStyle) {
104762         return formatStyle + text + resetEscapeSequence;
104763     }
104764     ts.formatColorAndReset = formatColorAndReset;
104765     function formatCodeSpan(file, start, length, indent, squiggleColor, host) {
104766         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character;
104767         var _b = ts.getLineAndCharacterOfPosition(file, start + length), lastLine = _b.line, lastLineChar = _b.character;
104768         var lastLineInFile = ts.getLineAndCharacterOfPosition(file, file.text.length).line;
104769         var hasMoreThanFiveLines = (lastLine - firstLine) >= 4;
104770         var gutterWidth = (lastLine + 1 + "").length;
104771         if (hasMoreThanFiveLines) {
104772             gutterWidth = Math.max(ellipsis.length, gutterWidth);
104773         }
104774         var context = "";
104775         for (var i = firstLine; i <= lastLine; i++) {
104776             context += host.getNewLine();
104777             // If the error spans over 5 lines, we'll only show the first 2 and last 2 lines,
104778             // so we'll skip ahead to the second-to-last line.
104779             if (hasMoreThanFiveLines && firstLine + 1 < i && i < lastLine - 1) {
104780                 context += indent + formatColorAndReset(ts.padLeft(ellipsis, gutterWidth), gutterStyleSequence) + gutterSeparator + host.getNewLine();
104781                 i = lastLine - 1;
104782             }
104783             var lineStart = ts.getPositionOfLineAndCharacter(file, i, 0);
104784             var lineEnd = i < lastLineInFile ? ts.getPositionOfLineAndCharacter(file, i + 1, 0) : file.text.length;
104785             var lineContent = file.text.slice(lineStart, lineEnd);
104786             lineContent = lineContent.replace(/\s+$/g, ""); // trim from end
104787             lineContent = lineContent.replace("\t", " "); // convert tabs to single spaces
104788             // Output the gutter and the actual contents of the line.
104789             context += indent + formatColorAndReset(ts.padLeft(i + 1 + "", gutterWidth), gutterStyleSequence) + gutterSeparator;
104790             context += lineContent + host.getNewLine();
104791             // Output the gutter and the error span for the line using tildes.
104792             context += indent + formatColorAndReset(ts.padLeft("", gutterWidth), gutterStyleSequence) + gutterSeparator;
104793             context += squiggleColor;
104794             if (i === firstLine) {
104795                 // If we're on the last line, then limit it to the last character of the last line.
104796                 // Otherwise, we'll just squiggle the rest of the line, giving 'slice' no end position.
104797                 var lastCharForLine = i === lastLine ? lastLineChar : undefined;
104798                 context += lineContent.slice(0, firstLineChar).replace(/\S/g, " ");
104799                 context += lineContent.slice(firstLineChar, lastCharForLine).replace(/./g, "~");
104800             }
104801             else if (i === lastLine) {
104802                 context += lineContent.slice(0, lastLineChar).replace(/./g, "~");
104803             }
104804             else {
104805                 // Squiggle the entire line.
104806                 context += lineContent.replace(/./g, "~");
104807             }
104808             context += resetEscapeSequence;
104809         }
104810         return context;
104811     }
104812     /* @internal */
104813     function formatLocation(file, start, host, color) {
104814         if (color === void 0) { color = formatColorAndReset; }
104815         var _a = ts.getLineAndCharacterOfPosition(file, start), firstLine = _a.line, firstLineChar = _a.character; // TODO: GH#18217
104816         var relativeFileName = host ? ts.convertToRelativePath(file.fileName, host.getCurrentDirectory(), function (fileName) { return host.getCanonicalFileName(fileName); }) : file.fileName;
104817         var output = "";
104818         output += color(relativeFileName, ForegroundColorEscapeSequences.Cyan);
104819         output += ":";
104820         output += color("" + (firstLine + 1), ForegroundColorEscapeSequences.Yellow);
104821         output += ":";
104822         output += color("" + (firstLineChar + 1), ForegroundColorEscapeSequences.Yellow);
104823         return output;
104824     }
104825     ts.formatLocation = formatLocation;
104826     function formatDiagnosticsWithColorAndContext(diagnostics, host) {
104827         var output = "";
104828         for (var _i = 0, diagnostics_4 = diagnostics; _i < diagnostics_4.length; _i++) {
104829             var diagnostic = diagnostics_4[_i];
104830             if (diagnostic.file) {
104831                 var file = diagnostic.file, start = diagnostic.start;
104832                 output += formatLocation(file, start, host); // TODO: GH#18217
104833                 output += " - ";
104834             }
104835             output += formatColorAndReset(ts.diagnosticCategoryName(diagnostic), getCategoryFormat(diagnostic.category));
104836             output += formatColorAndReset(" TS" + diagnostic.code + ": ", ForegroundColorEscapeSequences.Grey);
104837             output += flattenDiagnosticMessageText(diagnostic.messageText, host.getNewLine());
104838             if (diagnostic.file) {
104839                 output += host.getNewLine();
104840                 output += formatCodeSpan(diagnostic.file, diagnostic.start, diagnostic.length, "", getCategoryFormat(diagnostic.category), host); // TODO: GH#18217
104841                 if (diagnostic.relatedInformation) {
104842                     output += host.getNewLine();
104843                     for (var _a = 0, _b = diagnostic.relatedInformation; _a < _b.length; _a++) {
104844                         var _c = _b[_a], file = _c.file, start = _c.start, length_8 = _c.length, messageText = _c.messageText;
104845                         if (file) {
104846                             output += host.getNewLine();
104847                             output += halfIndent + formatLocation(file, start, host); // TODO: GH#18217
104848                             output += formatCodeSpan(file, start, length_8, indent, ForegroundColorEscapeSequences.Cyan, host); // TODO: GH#18217
104849                         }
104850                         output += host.getNewLine();
104851                         output += indent + flattenDiagnosticMessageText(messageText, host.getNewLine());
104852                     }
104853                 }
104854             }
104855             output += host.getNewLine();
104856         }
104857         return output;
104858     }
104859     ts.formatDiagnosticsWithColorAndContext = formatDiagnosticsWithColorAndContext;
104860     function flattenDiagnosticMessageText(diag, newLine, indent) {
104861         if (indent === void 0) { indent = 0; }
104862         if (ts.isString(diag)) {
104863             return diag;
104864         }
104865         else if (diag === undefined) {
104866             return "";
104867         }
104868         var result = "";
104869         if (indent) {
104870             result += newLine;
104871             for (var i = 0; i < indent; i++) {
104872                 result += "  ";
104873             }
104874         }
104875         result += diag.messageText;
104876         indent++;
104877         if (diag.next) {
104878             for (var _i = 0, _a = diag.next; _i < _a.length; _i++) {
104879                 var kid = _a[_i];
104880                 result += flattenDiagnosticMessageText(kid, newLine, indent);
104881             }
104882         }
104883         return result;
104884     }
104885     ts.flattenDiagnosticMessageText = flattenDiagnosticMessageText;
104886     /* @internal */
104887     function loadWithLocalCache(names, containingFile, redirectedReference, loader) {
104888         if (names.length === 0) {
104889             return [];
104890         }
104891         var resolutions = [];
104892         var cache = new ts.Map();
104893         for (var _i = 0, names_2 = names; _i < names_2.length; _i++) {
104894             var name = names_2[_i];
104895             var result = void 0;
104896             if (cache.has(name)) {
104897                 result = cache.get(name);
104898             }
104899             else {
104900                 cache.set(name, result = loader(name, containingFile, redirectedReference));
104901             }
104902             resolutions.push(result);
104903         }
104904         return resolutions;
104905     }
104906     ts.loadWithLocalCache = loadWithLocalCache;
104907     /* @internal */
104908     function forEachResolvedProjectReference(resolvedProjectReferences, cb) {
104909         return forEachProjectReference(/*projectReferences*/ undefined, resolvedProjectReferences, function (resolvedRef, parent) { return resolvedRef && cb(resolvedRef, parent); });
104910     }
104911     ts.forEachResolvedProjectReference = forEachResolvedProjectReference;
104912     function forEachProjectReference(projectReferences, resolvedProjectReferences, cbResolvedRef, cbRef) {
104913         var seenResolvedRefs;
104914         return worker(projectReferences, resolvedProjectReferences, /*parent*/ undefined);
104915         function worker(projectReferences, resolvedProjectReferences, parent) {
104916             // Visit project references first
104917             if (cbRef) {
104918                 var result = cbRef(projectReferences, parent);
104919                 if (result) {
104920                     return result;
104921                 }
104922             }
104923             return ts.forEach(resolvedProjectReferences, function (resolvedRef, index) {
104924                 if (resolvedRef && (seenResolvedRefs === null || seenResolvedRefs === void 0 ? void 0 : seenResolvedRefs.has(resolvedRef.sourceFile.path))) {
104925                     // ignore recursives
104926                     return undefined;
104927                 }
104928                 var result = cbResolvedRef(resolvedRef, parent, index);
104929                 if (result || !resolvedRef)
104930                     return result;
104931                 (seenResolvedRefs || (seenResolvedRefs = new ts.Set())).add(resolvedRef.sourceFile.path);
104932                 return worker(resolvedRef.commandLine.projectReferences, resolvedRef.references, resolvedRef);
104933             });
104934         }
104935     }
104936     /* @internal */
104937     ts.inferredTypesContainingFile = "__inferred type names__.ts";
104938     /**
104939      * Determines if program structure is upto date or needs to be recreated
104940      */
104941     /* @internal */
104942     function isProgramUptoDate(program, rootFileNames, newOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences) {
104943         // If we haven't created a program yet or have changed automatic type directives, then it is not up-to-date
104944         if (!program || (hasChangedAutomaticTypeDirectiveNames === null || hasChangedAutomaticTypeDirectiveNames === void 0 ? void 0 : hasChangedAutomaticTypeDirectiveNames())) {
104945             return false;
104946         }
104947         // If root file names don't match
104948         if (!ts.arrayIsEqualTo(program.getRootFileNames(), rootFileNames)) {
104949             return false;
104950         }
104951         var seenResolvedRefs;
104952         // If project references don't match
104953         if (!ts.arrayIsEqualTo(program.getProjectReferences(), projectReferences, projectReferenceUptoDate)) {
104954             return false;
104955         }
104956         // If any file is not up-to-date, then the whole program is not up-to-date
104957         if (program.getSourceFiles().some(sourceFileNotUptoDate)) {
104958             return false;
104959         }
104960         // If any of the missing file paths are now created
104961         if (program.getMissingFilePaths().some(fileExists)) {
104962             return false;
104963         }
104964         var currentOptions = program.getCompilerOptions();
104965         // If the compilation settings do no match, then the program is not up-to-date
104966         if (!ts.compareDataObjects(currentOptions, newOptions)) {
104967             return false;
104968         }
104969         // If everything matches but the text of config file is changed,
104970         // error locations can change for program options, so update the program
104971         if (currentOptions.configFile && newOptions.configFile) {
104972             return currentOptions.configFile.text === newOptions.configFile.text;
104973         }
104974         return true;
104975         function sourceFileNotUptoDate(sourceFile) {
104976             return !sourceFileVersionUptoDate(sourceFile) ||
104977                 hasInvalidatedResolution(sourceFile.path);
104978         }
104979         function sourceFileVersionUptoDate(sourceFile) {
104980             return sourceFile.version === getSourceVersion(sourceFile.resolvedPath, sourceFile.fileName);
104981         }
104982         function projectReferenceUptoDate(oldRef, newRef, index) {
104983             if (!ts.projectReferenceIsEqualTo(oldRef, newRef)) {
104984                 return false;
104985             }
104986             return resolvedProjectReferenceUptoDate(program.getResolvedProjectReferences()[index], oldRef);
104987         }
104988         function resolvedProjectReferenceUptoDate(oldResolvedRef, oldRef) {
104989             if (oldResolvedRef) {
104990                 if (ts.contains(seenResolvedRefs, oldResolvedRef)) {
104991                     // Assume true
104992                     return true;
104993                 }
104994                 // If sourceFile for the oldResolvedRef existed, check the version for uptodate
104995                 if (!sourceFileVersionUptoDate(oldResolvedRef.sourceFile)) {
104996                     return false;
104997                 }
104998                 // Add to seen before checking the referenced paths of this config file
104999                 (seenResolvedRefs || (seenResolvedRefs = [])).push(oldResolvedRef);
105000                 // If child project references are upto date, this project reference is uptodate
105001                 return !ts.forEach(oldResolvedRef.references, function (childResolvedRef, index) {
105002                     return !resolvedProjectReferenceUptoDate(childResolvedRef, oldResolvedRef.commandLine.projectReferences[index]);
105003                 });
105004             }
105005             // In old program, not able to resolve project reference path,
105006             // so if config file doesnt exist, it is uptodate.
105007             return !fileExists(resolveProjectReferencePath(oldRef));
105008         }
105009     }
105010     ts.isProgramUptoDate = isProgramUptoDate;
105011     function getConfigFileParsingDiagnostics(configFileParseResult) {
105012         return configFileParseResult.options.configFile ? __spreadArrays(configFileParseResult.options.configFile.parseDiagnostics, configFileParseResult.errors) :
105013             configFileParseResult.errors;
105014     }
105015     ts.getConfigFileParsingDiagnostics = getConfigFileParsingDiagnostics;
105016     /**
105017      * Determine if source file needs to be re-created even if its text hasn't changed
105018      */
105019     function shouldProgramCreateNewSourceFiles(program, newOptions) {
105020         if (!program)
105021             return false;
105022         // If any compiler options change, we can't reuse old source file even if version match
105023         // The change in options like these could result in change in syntax tree or `sourceFile.bindDiagnostics`.
105024         var oldOptions = program.getCompilerOptions();
105025         return !!ts.sourceFileAffectingCompilerOptions.some(function (option) {
105026             return !ts.isJsonEqual(ts.getCompilerOptionValue(oldOptions, option), ts.getCompilerOptionValue(newOptions, option));
105027         });
105028     }
105029     function createCreateProgramOptions(rootNames, options, host, oldProgram, configFileParsingDiagnostics) {
105030         return {
105031             rootNames: rootNames,
105032             options: options,
105033             host: host,
105034             oldProgram: oldProgram,
105035             configFileParsingDiagnostics: configFileParsingDiagnostics
105036         };
105037     }
105038     function createProgram(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) {
105039         var _a, _b;
105040         var createProgramOptions = ts.isArray(rootNamesOrOptions) ? createCreateProgramOptions(rootNamesOrOptions, _options, _host, _oldProgram, _configFileParsingDiagnostics) : rootNamesOrOptions; // TODO: GH#18217
105041         var rootNames = createProgramOptions.rootNames, options = createProgramOptions.options, configFileParsingDiagnostics = createProgramOptions.configFileParsingDiagnostics, projectReferences = createProgramOptions.projectReferences;
105042         var oldProgram = createProgramOptions.oldProgram;
105043         var processingDefaultLibFiles;
105044         var processingOtherFiles;
105045         var files;
105046         var symlinks;
105047         var commonSourceDirectory;
105048         var diagnosticsProducingTypeChecker;
105049         var noDiagnosticsTypeChecker;
105050         var classifiableNames;
105051         var ambientModuleNameToUnmodifiedFileName = new ts.Map();
105052         // Todo:: Use this to report why file was included in --extendedDiagnostics
105053         var refFileMap;
105054         var cachedBindAndCheckDiagnosticsForFile = {};
105055         var cachedDeclarationDiagnosticsForFile = {};
105056         var resolvedTypeReferenceDirectives = new ts.Map();
105057         var fileProcessingDiagnostics = ts.createDiagnosticCollection();
105058         // The below settings are to track if a .js file should be add to the program if loaded via searching under node_modules.
105059         // This works as imported modules are discovered recursively in a depth first manner, specifically:
105060         // - For each root file, findSourceFile is called.
105061         // - This calls processImportedModules for each module imported in the source file.
105062         // - This calls resolveModuleNames, and then calls findSourceFile for each resolved module.
105063         // As all these operations happen - and are nested - within the createProgram call, they close over the below variables.
105064         // The current resolution depth is tracked by incrementing/decrementing as the depth first search progresses.
105065         var maxNodeModuleJsDepth = typeof options.maxNodeModuleJsDepth === "number" ? options.maxNodeModuleJsDepth : 0;
105066         var currentNodeModulesDepth = 0;
105067         // If a module has some of its imports skipped due to being at the depth limit under node_modules, then track
105068         // this, as it may be imported at a shallower depth later, and then it will need its skipped imports processed.
105069         var modulesWithElidedImports = new ts.Map();
105070         // Track source files that are source files found by searching under node_modules, as these shouldn't be compiled.
105071         var sourceFilesFoundSearchingNodeModules = new ts.Map();
105072         var tracingData = ["program" /* Program */, "createProgram"];
105073         ts.tracing.begin.apply(ts.tracing, tracingData);
105074         ts.performance.mark("beforeProgram");
105075         var host = createProgramOptions.host || createCompilerHost(options);
105076         var configParsingHost = parseConfigHostFromCompilerHostLike(host);
105077         var skipDefaultLib = options.noLib;
105078         var getDefaultLibraryFileName = ts.memoize(function () { return host.getDefaultLibFileName(options); });
105079         var defaultLibraryPath = host.getDefaultLibLocation ? host.getDefaultLibLocation() : ts.getDirectoryPath(getDefaultLibraryFileName());
105080         var programDiagnostics = ts.createDiagnosticCollection();
105081         var currentDirectory = host.getCurrentDirectory();
105082         var supportedExtensions = ts.getSupportedExtensions(options);
105083         var supportedExtensionsWithJsonIfResolveJsonModule = ts.getSuppoertedExtensionsWithJsonIfResolveJsonModule(options, supportedExtensions);
105084         // Map storing if there is emit blocking diagnostics for given input
105085         var hasEmitBlockingDiagnostics = new ts.Map();
105086         var _compilerOptionsObjectLiteralSyntax;
105087         var moduleResolutionCache;
105088         var actualResolveModuleNamesWorker;
105089         var hasInvalidatedResolution = host.hasInvalidatedResolution || ts.returnFalse;
105090         if (host.resolveModuleNames) {
105091             actualResolveModuleNamesWorker = function (moduleNames, containingFile, reusedNames, redirectedReference) { return host.resolveModuleNames(ts.Debug.checkEachDefined(moduleNames), containingFile, reusedNames, redirectedReference, options).map(function (resolved) {
105092                 // An older host may have omitted extension, in which case we should infer it from the file extension of resolvedFileName.
105093                 if (!resolved || resolved.extension !== undefined) {
105094                     return resolved;
105095                 }
105096                 var withExtension = ts.clone(resolved);
105097                 withExtension.extension = ts.extensionFromPath(resolved.resolvedFileName);
105098                 return withExtension;
105099             }); };
105100         }
105101         else {
105102             moduleResolutionCache = ts.createModuleResolutionCache(currentDirectory, function (x) { return host.getCanonicalFileName(x); }, options);
105103             var loader_1 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, options, host, moduleResolutionCache, redirectedReference).resolvedModule; }; // TODO: GH#18217
105104             actualResolveModuleNamesWorker = function (moduleNames, containingFile, _reusedNames, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_1); };
105105         }
105106         var actualResolveTypeReferenceDirectiveNamesWorker;
105107         if (host.resolveTypeReferenceDirectives) {
105108             actualResolveTypeReferenceDirectiveNamesWorker = function (typeDirectiveNames, containingFile, redirectedReference) { return host.resolveTypeReferenceDirectives(ts.Debug.checkEachDefined(typeDirectiveNames), containingFile, redirectedReference, options); };
105109         }
105110         else {
105111             var loader_2 = function (typesRef, containingFile, redirectedReference) { return ts.resolveTypeReferenceDirective(typesRef, containingFile, options, host, redirectedReference).resolvedTypeReferenceDirective; }; // TODO: GH#18217
105112             actualResolveTypeReferenceDirectiveNamesWorker = function (typeReferenceDirectiveNames, containingFile, redirectedReference) { return loadWithLocalCache(ts.Debug.checkEachDefined(typeReferenceDirectiveNames), containingFile, redirectedReference, loader_2); };
105113         }
105114         // Map from a stringified PackageId to the source file with that id.
105115         // Only one source file may have a given packageId. Others become redirects (see createRedirectSourceFile).
105116         // `packageIdToSourceFile` is only used while building the program, while `sourceFileToPackageName` and `isSourceFileTargetOfRedirect` are kept around.
105117         var packageIdToSourceFile = new ts.Map();
105118         // Maps from a SourceFile's `.path` to the name of the package it was imported with.
105119         var sourceFileToPackageName = new ts.Map();
105120         // Key is a file name. Value is the (non-empty, or undefined) list of files that redirect to it.
105121         var redirectTargetsMap = ts.createMultiMap();
105122         /**
105123          * map with
105124          * - SourceFile if present
105125          * - false if sourceFile missing for source of project reference redirect
105126          * - undefined otherwise
105127          */
105128         var filesByName = new ts.Map();
105129         var missingFilePaths;
105130         // stores 'filename -> file association' ignoring case
105131         // used to track cases when two file names differ only in casing
105132         var filesByNameIgnoreCase = host.useCaseSensitiveFileNames() ? new ts.Map() : undefined;
105133         // A parallel array to projectReferences storing the results of reading in the referenced tsconfig files
105134         var resolvedProjectReferences;
105135         var projectReferenceRedirects;
105136         var mapFromFileToProjectReferenceRedirects;
105137         var mapFromToProjectReferenceRedirectSource;
105138         var useSourceOfProjectReferenceRedirect = !!((_a = host.useSourceOfProjectReferenceRedirect) === null || _a === void 0 ? void 0 : _a.call(host)) &&
105139             !options.disableSourceOfProjectReferenceRedirect;
105140         var _c = updateHostForUseSourceOfProjectReferenceRedirect({
105141             compilerHost: host,
105142             getSymlinkCache: getSymlinkCache,
105143             useSourceOfProjectReferenceRedirect: useSourceOfProjectReferenceRedirect,
105144             toPath: toPath,
105145             getResolvedProjectReferences: getResolvedProjectReferences,
105146             getSourceOfProjectReferenceRedirect: getSourceOfProjectReferenceRedirect,
105147             forEachResolvedProjectReference: forEachResolvedProjectReference
105148         }), onProgramCreateComplete = _c.onProgramCreateComplete, fileExists = _c.fileExists, directoryExists = _c.directoryExists;
105149         ts.tracing.push("program" /* Program */, "shouldProgramCreateNewSourceFiles", { hasOldProgram: !!oldProgram });
105150         var shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
105151         ts.tracing.pop();
105152         // We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
105153         // `structuralIsReused`, which would be a TDZ violation if it was not set in advance to `undefined`.
105154         var structureIsReused;
105155         ts.tracing.push("program" /* Program */, "tryReuseStructureFromOldProgram", {});
105156         structureIsReused = tryReuseStructureFromOldProgram(); // eslint-disable-line prefer-const
105157         ts.tracing.pop();
105158         if (structureIsReused !== 2 /* Completely */) {
105159             processingDefaultLibFiles = [];
105160             processingOtherFiles = [];
105161             if (projectReferences) {
105162                 if (!resolvedProjectReferences) {
105163                     resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
105164                 }
105165                 if (rootNames.length) {
105166                     for (var _i = 0, resolvedProjectReferences_1 = resolvedProjectReferences; _i < resolvedProjectReferences_1.length; _i++) {
105167                         var parsedRef = resolvedProjectReferences_1[_i];
105168                         if (!parsedRef)
105169                             continue;
105170                         var out = ts.outFile(parsedRef.commandLine.options);
105171                         if (useSourceOfProjectReferenceRedirect) {
105172                             if (out || ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
105173                                 for (var _d = 0, _e = parsedRef.commandLine.fileNames; _d < _e.length; _d++) {
105174                                     var fileName = _e[_d];
105175                                     processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
105176                                 }
105177                             }
105178                         }
105179                         else {
105180                             if (out) {
105181                                 processSourceFile(ts.changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
105182                             }
105183                             else if (ts.getEmitModuleKind(parsedRef.commandLine.options) === ts.ModuleKind.None) {
105184                                 for (var _f = 0, _g = parsedRef.commandLine.fileNames; _f < _g.length; _f++) {
105185                                     var fileName = _g[_f];
105186                                     if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
105187                                         processSourceFile(ts.getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
105188                                     }
105189                                 }
105190                             }
105191                         }
105192                     }
105193                 }
105194             }
105195             ts.tracing.push("program" /* Program */, "processRootFiles", { count: rootNames.length });
105196             ts.forEach(rootNames, function (name) { return processRootFile(name, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false); });
105197             ts.tracing.pop();
105198             // load type declarations specified via 'types' argument or implicitly from types/ and node_modules/@types folders
105199             var typeReferences = rootNames.length ? ts.getAutomaticTypeDirectiveNames(options, host) : ts.emptyArray;
105200             if (typeReferences.length) {
105201                 ts.tracing.push("program" /* Program */, "processTypeReferences", { count: typeReferences.length });
105202                 // This containingFilename needs to match with the one used in managed-side
105203                 var containingDirectory = options.configFilePath ? ts.getDirectoryPath(options.configFilePath) : host.getCurrentDirectory();
105204                 var containingFilename = ts.combinePaths(containingDirectory, ts.inferredTypesContainingFile);
105205                 var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeReferences, containingFilename);
105206                 for (var i = 0; i < typeReferences.length; i++) {
105207                     processTypeReferenceDirective(typeReferences[i], resolutions[i]);
105208                 }
105209                 ts.tracing.pop();
105210             }
105211             // Do not process the default library if:
105212             //  - The '--noLib' flag is used.
105213             //  - A 'no-default-lib' reference comment is encountered in
105214             //      processing the root files.
105215             if (rootNames.length && !skipDefaultLib) {
105216                 // If '--lib' is not specified, include default library file according to '--target'
105217                 // otherwise, using options specified in '--lib' instead of '--target' default library file
105218                 var defaultLibraryFileName = getDefaultLibraryFileName();
105219                 if (!options.lib && defaultLibraryFileName) {
105220                     processRootFile(defaultLibraryFileName, /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
105221                 }
105222                 else {
105223                     ts.forEach(options.lib, function (libFileName) {
105224                         processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ false);
105225                     });
105226                 }
105227             }
105228             missingFilePaths = ts.arrayFrom(ts.mapDefinedIterator(filesByName.entries(), function (_a) {
105229                 var path = _a[0], file = _a[1];
105230                 return file === undefined ? path : undefined;
105231             }));
105232             files = ts.stableSort(processingDefaultLibFiles, compareDefaultLibFiles).concat(processingOtherFiles);
105233             processingDefaultLibFiles = undefined;
105234             processingOtherFiles = undefined;
105235         }
105236         ts.Debug.assert(!!missingFilePaths);
105237         // Release any files we have acquired in the old program but are
105238         // not part of the new program.
105239         if (oldProgram && host.onReleaseOldSourceFile) {
105240             var oldSourceFiles = oldProgram.getSourceFiles();
105241             for (var _h = 0, oldSourceFiles_1 = oldSourceFiles; _h < oldSourceFiles_1.length; _h++) {
105242                 var oldSourceFile = oldSourceFiles_1[_h];
105243                 var newFile = getSourceFileByPath(oldSourceFile.resolvedPath);
105244                 if (shouldCreateNewSourceFile || !newFile ||
105245                     // old file wasnt redirect but new file is
105246                     (oldSourceFile.resolvedPath === oldSourceFile.path && newFile.resolvedPath !== oldSourceFile.path)) {
105247                     host.onReleaseOldSourceFile(oldSourceFile, oldProgram.getCompilerOptions(), !!getSourceFileByPath(oldSourceFile.path));
105248                 }
105249             }
105250             oldProgram.forEachResolvedProjectReference(function (resolvedProjectReference) {
105251                 if (!getResolvedProjectReferenceByPath(resolvedProjectReference.sourceFile.path)) {
105252                     host.onReleaseOldSourceFile(resolvedProjectReference.sourceFile, oldProgram.getCompilerOptions(), /*hasSourceFileByPath*/ false);
105253                 }
105254             });
105255         }
105256         // unconditionally set oldProgram to undefined to prevent it from being captured in closure
105257         oldProgram = undefined;
105258         var program = {
105259             getRootFileNames: function () { return rootNames; },
105260             getSourceFile: getSourceFile,
105261             getSourceFileByPath: getSourceFileByPath,
105262             getSourceFiles: function () { return files; },
105263             getMissingFilePaths: function () { return missingFilePaths; },
105264             getRefFileMap: function () { return refFileMap; },
105265             getFilesByNameMap: function () { return filesByName; },
105266             getCompilerOptions: function () { return options; },
105267             getSyntacticDiagnostics: getSyntacticDiagnostics,
105268             getOptionsDiagnostics: getOptionsDiagnostics,
105269             getGlobalDiagnostics: getGlobalDiagnostics,
105270             getSemanticDiagnostics: getSemanticDiagnostics,
105271             getCachedSemanticDiagnostics: getCachedSemanticDiagnostics,
105272             getSuggestionDiagnostics: getSuggestionDiagnostics,
105273             getDeclarationDiagnostics: getDeclarationDiagnostics,
105274             getBindAndCheckDiagnostics: getBindAndCheckDiagnostics,
105275             getProgramDiagnostics: getProgramDiagnostics,
105276             getTypeChecker: getTypeChecker,
105277             getClassifiableNames: getClassifiableNames,
105278             getDiagnosticsProducingTypeChecker: getDiagnosticsProducingTypeChecker,
105279             getCommonSourceDirectory: getCommonSourceDirectory,
105280             emit: emit,
105281             getCurrentDirectory: function () { return currentDirectory; },
105282             getNodeCount: function () { return getDiagnosticsProducingTypeChecker().getNodeCount(); },
105283             getIdentifierCount: function () { return getDiagnosticsProducingTypeChecker().getIdentifierCount(); },
105284             getSymbolCount: function () { return getDiagnosticsProducingTypeChecker().getSymbolCount(); },
105285             getTypeCatalog: function () { return getDiagnosticsProducingTypeChecker().getTypeCatalog(); },
105286             getTypeCount: function () { return getDiagnosticsProducingTypeChecker().getTypeCount(); },
105287             getInstantiationCount: function () { return getDiagnosticsProducingTypeChecker().getInstantiationCount(); },
105288             getRelationCacheSizes: function () { return getDiagnosticsProducingTypeChecker().getRelationCacheSizes(); },
105289             getFileProcessingDiagnostics: function () { return fileProcessingDiagnostics; },
105290             getResolvedTypeReferenceDirectives: function () { return resolvedTypeReferenceDirectives; },
105291             isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
105292             isSourceFileDefaultLibrary: isSourceFileDefaultLibrary,
105293             dropDiagnosticsProducingTypeChecker: dropDiagnosticsProducingTypeChecker,
105294             getSourceFileFromReference: getSourceFileFromReference,
105295             getLibFileFromReference: getLibFileFromReference,
105296             sourceFileToPackageName: sourceFileToPackageName,
105297             redirectTargetsMap: redirectTargetsMap,
105298             isEmittedFile: isEmittedFile,
105299             getConfigFileParsingDiagnostics: getConfigFileParsingDiagnostics,
105300             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
105301             getProjectReferences: getProjectReferences,
105302             getResolvedProjectReferences: getResolvedProjectReferences,
105303             getProjectReferenceRedirect: getProjectReferenceRedirect,
105304             getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
105305             getResolvedProjectReferenceByPath: getResolvedProjectReferenceByPath,
105306             forEachResolvedProjectReference: forEachResolvedProjectReference,
105307             isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
105308             emitBuildInfo: emitBuildInfo,
105309             fileExists: fileExists,
105310             directoryExists: directoryExists,
105311             getSymlinkCache: getSymlinkCache,
105312             realpath: (_b = host.realpath) === null || _b === void 0 ? void 0 : _b.bind(host),
105313             useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
105314             structureIsReused: structureIsReused,
105315         };
105316         onProgramCreateComplete();
105317         verifyCompilerOptions();
105318         ts.performance.mark("afterProgram");
105319         ts.performance.measure("Program", "beforeProgram", "afterProgram");
105320         ts.tracing.end.apply(ts.tracing, tracingData);
105321         return program;
105322         function resolveModuleNamesWorker(moduleNames, containingFile, reusedNames) {
105323             if (!moduleNames.length)
105324                 return ts.emptyArray;
105325             var containingFileName = ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory);
105326             var redirectedReference = getRedirectReferenceForResolution(containingFile);
105327             ts.tracing.push("program" /* Program */, "resolveModuleNamesWorker", { containingFileName: containingFileName });
105328             ts.performance.mark("beforeResolveModule");
105329             var result = actualResolveModuleNamesWorker(moduleNames, containingFileName, reusedNames, redirectedReference);
105330             ts.performance.mark("afterResolveModule");
105331             ts.performance.measure("ResolveModule", "beforeResolveModule", "afterResolveModule");
105332             ts.tracing.pop();
105333             return result;
105334         }
105335         function resolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFile) {
105336             if (!typeDirectiveNames.length)
105337                 return [];
105338             var containingFileName = !ts.isString(containingFile) ? ts.getNormalizedAbsolutePath(containingFile.originalFileName, currentDirectory) : containingFile;
105339             var redirectedReference = !ts.isString(containingFile) ? getRedirectReferenceForResolution(containingFile) : undefined;
105340             ts.tracing.push("program" /* Program */, "resolveTypeReferenceDirectiveNamesWorker", { containingFileName: containingFileName });
105341             ts.performance.mark("beforeResolveTypeReference");
105342             var result = actualResolveTypeReferenceDirectiveNamesWorker(typeDirectiveNames, containingFileName, redirectedReference);
105343             ts.performance.mark("afterResolveTypeReference");
105344             ts.performance.measure("ResolveTypeReference", "beforeResolveTypeReference", "afterResolveTypeReference");
105345             ts.tracing.pop();
105346             return result;
105347         }
105348         function getRedirectReferenceForResolution(file) {
105349             var redirect = getResolvedProjectReferenceToRedirect(file.originalFileName);
105350             if (redirect || !ts.fileExtensionIs(file.originalFileName, ".d.ts" /* Dts */))
105351                 return redirect;
105352             // The originalFileName could not be actual source file name if file found was d.ts from referecned project
105353             // So in this case try to look up if this is output from referenced project, if it is use the redirected project in that case
105354             var resultFromDts = getRedirectReferenceForResolutionFromSourceOfProject(file.originalFileName, file.path);
105355             if (resultFromDts)
105356                 return resultFromDts;
105357             // If preserveSymlinks is true, module resolution wont jump the symlink
105358             // but the resolved real path may be the .d.ts from project reference
105359             // Note:: Currently we try the real path only if the
105360             // file is from node_modules to avoid having to run real path on all file paths
105361             if (!host.realpath || !options.preserveSymlinks || !ts.stringContains(file.originalFileName, ts.nodeModulesPathPart))
105362                 return undefined;
105363             var realDeclarationFileName = host.realpath(file.originalFileName);
105364             var realDeclarationPath = toPath(realDeclarationFileName);
105365             return realDeclarationPath === file.path ? undefined : getRedirectReferenceForResolutionFromSourceOfProject(realDeclarationFileName, realDeclarationPath);
105366         }
105367         function getRedirectReferenceForResolutionFromSourceOfProject(fileName, filePath) {
105368             var source = getSourceOfProjectReferenceRedirect(fileName);
105369             if (ts.isString(source))
105370                 return getResolvedProjectReferenceToRedirect(source);
105371             if (!source)
105372                 return undefined;
105373             // Output of .d.ts file so return resolved ref that matches the out file name
105374             return forEachResolvedProjectReference(function (resolvedRef) {
105375                 var out = ts.outFile(resolvedRef.commandLine.options);
105376                 if (!out)
105377                     return undefined;
105378                 return toPath(out) === filePath ? resolvedRef : undefined;
105379             });
105380         }
105381         function compareDefaultLibFiles(a, b) {
105382             return ts.compareValues(getDefaultLibFilePriority(a), getDefaultLibFilePriority(b));
105383         }
105384         function getDefaultLibFilePriority(a) {
105385             if (ts.containsPath(defaultLibraryPath, a.fileName, /*ignoreCase*/ false)) {
105386                 var basename = ts.getBaseFileName(a.fileName);
105387                 if (basename === "lib.d.ts" || basename === "lib.es6.d.ts")
105388                     return 0;
105389                 var name = ts.removeSuffix(ts.removePrefix(basename, "lib."), ".d.ts");
105390                 var index = ts.libs.indexOf(name);
105391                 if (index !== -1)
105392                     return index + 1;
105393             }
105394             return ts.libs.length + 2;
105395         }
105396         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
105397             return moduleResolutionCache && ts.resolveModuleNameFromCache(moduleName, containingFile, moduleResolutionCache);
105398         }
105399         function toPath(fileName) {
105400             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
105401         }
105402         function getCommonSourceDirectory() {
105403             if (commonSourceDirectory === undefined) {
105404                 var emittedFiles = ts.filter(files, function (file) { return ts.sourceFileMayBeEmitted(file, program); });
105405                 if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
105406                     // If a rootDir is specified use it as the commonSourceDirectory
105407                     commonSourceDirectory = ts.getNormalizedAbsolutePath(options.rootDir, currentDirectory);
105408                 }
105409                 else if (options.composite && options.configFilePath) {
105410                     // Project compilations never infer their root from the input source paths
105411                     commonSourceDirectory = ts.getDirectoryPath(ts.normalizeSlashes(options.configFilePath));
105412                     checkSourceFilesBelongToPath(emittedFiles, commonSourceDirectory);
105413                 }
105414                 else {
105415                     commonSourceDirectory = computeCommonSourceDirectory(emittedFiles);
105416                 }
105417                 if (commonSourceDirectory && commonSourceDirectory[commonSourceDirectory.length - 1] !== ts.directorySeparator) {
105418                     // Make sure directory path ends with directory separator so this string can directly
105419                     // used to replace with "" to get the relative path of the source file and the relative path doesn't
105420                     // start with / making it rooted path
105421                     commonSourceDirectory += ts.directorySeparator;
105422                 }
105423             }
105424             return commonSourceDirectory;
105425         }
105426         function getClassifiableNames() {
105427             var _a;
105428             if (!classifiableNames) {
105429                 // Initialize a checker so that all our files are bound.
105430                 getTypeChecker();
105431                 classifiableNames = new ts.Set();
105432                 for (var _i = 0, files_2 = files; _i < files_2.length; _i++) {
105433                     var sourceFile = files_2[_i];
105434                     (_a = sourceFile.classifiableNames) === null || _a === void 0 ? void 0 : _a.forEach(function (value) { return classifiableNames.add(value); });
105435                 }
105436             }
105437             return classifiableNames;
105438         }
105439         function resolveModuleNamesReusingOldState(moduleNames, file) {
105440             if (structureIsReused === 0 /* Not */ && !file.ambientModuleNames.length) {
105441                 // If the old program state does not permit reusing resolutions and `file` does not contain locally defined ambient modules,
105442                 // the best we can do is fallback to the default logic.
105443                 return resolveModuleNamesWorker(moduleNames, file, /*reusedNames*/ undefined);
105444             }
105445             var oldSourceFile = oldProgram && oldProgram.getSourceFile(file.fileName);
105446             if (oldSourceFile !== file && file.resolvedModules) {
105447                 // `file` was created for the new program.
105448                 //
105449                 // We only set `file.resolvedModules` via work from the current function,
105450                 // so it is defined iff we already called the current function on `file`.
105451                 // That call happened no later than the creation of the `file` object,
105452                 // which per above occurred during the current program creation.
105453                 // Since we assume the filesystem does not change during program creation,
105454                 // it is safe to reuse resolutions from the earlier call.
105455                 var result_14 = [];
105456                 for (var _i = 0, moduleNames_1 = moduleNames; _i < moduleNames_1.length; _i++) {
105457                     var moduleName = moduleNames_1[_i];
105458                     var resolvedModule = file.resolvedModules.get(moduleName);
105459                     result_14.push(resolvedModule);
105460                 }
105461                 return result_14;
105462             }
105463             // At this point, we know at least one of the following hold:
105464             // - file has local declarations for ambient modules
105465             // - old program state is available
105466             // With this information, we can infer some module resolutions without performing resolution.
105467             /** An ordered list of module names for which we cannot recover the resolution. */
105468             var unknownModuleNames;
105469             /**
105470              * The indexing of elements in this list matches that of `moduleNames`.
105471              *
105472              * Before combining results, result[i] is in one of the following states:
105473              * * undefined: needs to be recomputed,
105474              * * predictedToResolveToAmbientModuleMarker: known to be an ambient module.
105475              * Needs to be reset to undefined before returning,
105476              * * ResolvedModuleFull instance: can be reused.
105477              */
105478             var result;
105479             var reusedNames;
105480             /** A transient placeholder used to mark predicted resolution in the result list. */
105481             var predictedToResolveToAmbientModuleMarker = {};
105482             for (var i = 0; i < moduleNames.length; i++) {
105483                 var moduleName = moduleNames[i];
105484                 // If the source file is unchanged and doesnt have invalidated resolution, reuse the module resolutions
105485                 if (file === oldSourceFile && !hasInvalidatedResolution(oldSourceFile.path)) {
105486                     var oldResolvedModule = ts.getResolvedModule(oldSourceFile, moduleName);
105487                     if (oldResolvedModule) {
105488                         if (ts.isTraceEnabled(options, host)) {
105489                             ts.trace(host, ts.Diagnostics.Reusing_resolution_of_module_0_to_file_1_from_old_program, moduleName, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory));
105490                         }
105491                         (result || (result = new Array(moduleNames.length)))[i] = oldResolvedModule;
105492                         (reusedNames || (reusedNames = [])).push(moduleName);
105493                         continue;
105494                     }
105495                 }
105496                 // We know moduleName resolves to an ambient module provided that moduleName:
105497                 // - is in the list of ambient modules locally declared in the current source file.
105498                 // - resolved to an ambient module in the old program whose declaration is in an unmodified file
105499                 //   (so the same module declaration will land in the new program)
105500                 var resolvesToAmbientModuleInNonModifiedFile = false;
105501                 if (ts.contains(file.ambientModuleNames, moduleName)) {
105502                     resolvesToAmbientModuleInNonModifiedFile = true;
105503                     if (ts.isTraceEnabled(options, host)) {
105504                         ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_locally_declared_ambient_module_in_file_1, moduleName, ts.getNormalizedAbsolutePath(file.originalFileName, currentDirectory));
105505                     }
105506                 }
105507                 else {
105508                     resolvesToAmbientModuleInNonModifiedFile = moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName);
105509                 }
105510                 if (resolvesToAmbientModuleInNonModifiedFile) {
105511                     (result || (result = new Array(moduleNames.length)))[i] = predictedToResolveToAmbientModuleMarker;
105512                 }
105513                 else {
105514                     // Resolution failed in the old program, or resolved to an ambient module for which we can't reuse the result.
105515                     (unknownModuleNames || (unknownModuleNames = [])).push(moduleName);
105516                 }
105517             }
105518             var resolutions = unknownModuleNames && unknownModuleNames.length
105519                 ? resolveModuleNamesWorker(unknownModuleNames, file, reusedNames)
105520                 : ts.emptyArray;
105521             // Combine results of resolutions and predicted results
105522             if (!result) {
105523                 // There were no unresolved/ambient resolutions.
105524                 ts.Debug.assert(resolutions.length === moduleNames.length);
105525                 return resolutions;
105526             }
105527             var j = 0;
105528             for (var i = 0; i < result.length; i++) {
105529                 if (result[i]) {
105530                     // `result[i]` is either a `ResolvedModuleFull` or a marker.
105531                     // If it is the former, we can leave it as is.
105532                     if (result[i] === predictedToResolveToAmbientModuleMarker) {
105533                         result[i] = undefined; // TODO: GH#18217
105534                     }
105535                 }
105536                 else {
105537                     result[i] = resolutions[j];
105538                     j++;
105539                 }
105540             }
105541             ts.Debug.assert(j === resolutions.length);
105542             return result;
105543             // If we change our policy of rechecking failed lookups on each program create,
105544             // we should adjust the value returned here.
105545             function moduleNameResolvesToAmbientModuleInNonModifiedFile(moduleName) {
105546                 var resolutionToFile = ts.getResolvedModule(oldSourceFile, moduleName);
105547                 var resolvedFile = resolutionToFile && oldProgram.getSourceFile(resolutionToFile.resolvedFileName);
105548                 if (resolutionToFile && resolvedFile) {
105549                     // In the old program, we resolved to an ambient module that was in the same
105550                     //   place as we expected to find an actual module file.
105551                     // We actually need to return 'false' here even though this seems like a 'true' case
105552                     //   because the normal module resolution algorithm will find this anyway.
105553                     return false;
105554                 }
105555                 // at least one of declarations should come from non-modified source file
105556                 var unmodifiedFile = ambientModuleNameToUnmodifiedFileName.get(moduleName);
105557                 if (!unmodifiedFile) {
105558                     return false;
105559                 }
105560                 if (ts.isTraceEnabled(options, host)) {
105561                     ts.trace(host, ts.Diagnostics.Module_0_was_resolved_as_ambient_module_declared_in_1_since_this_file_was_not_modified, moduleName, unmodifiedFile);
105562                 }
105563                 return true;
105564             }
105565         }
105566         function canReuseProjectReferences() {
105567             return !forEachProjectReference(oldProgram.getProjectReferences(), oldProgram.getResolvedProjectReferences(), function (oldResolvedRef, parent, index) {
105568                 var newRef = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
105569                 var newResolvedRef = parseProjectReferenceConfigFile(newRef);
105570                 if (oldResolvedRef) {
105571                     // Resolved project reference has gone missing or changed
105572                     return !newResolvedRef || newResolvedRef.sourceFile !== oldResolvedRef.sourceFile;
105573                 }
105574                 else {
105575                     // A previously-unresolved reference may be resolved now
105576                     return newResolvedRef !== undefined;
105577                 }
105578             }, function (oldProjectReferences, parent) {
105579                 // If array of references is changed, we cant resue old program
105580                 var newReferences = parent ? getResolvedProjectReferenceByPath(parent.sourceFile.path).commandLine.projectReferences : projectReferences;
105581                 return !ts.arrayIsEqualTo(oldProjectReferences, newReferences, ts.projectReferenceIsEqualTo);
105582             });
105583         }
105584         function tryReuseStructureFromOldProgram() {
105585             var _a;
105586             if (!oldProgram) {
105587                 return 0 /* Not */;
105588             }
105589             // check properties that can affect structure of the program or module resolution strategy
105590             // if any of these properties has changed - structure cannot be reused
105591             var oldOptions = oldProgram.getCompilerOptions();
105592             if (ts.changesAffectModuleResolution(oldOptions, options)) {
105593                 return 0 /* Not */;
105594             }
105595             // there is an old program, check if we can reuse its structure
105596             var oldRootNames = oldProgram.getRootFileNames();
105597             if (!ts.arrayIsEqualTo(oldRootNames, rootNames)) {
105598                 return 0 /* Not */;
105599             }
105600             if (!ts.arrayIsEqualTo(options.types, oldOptions.types)) {
105601                 return 0 /* Not */;
105602             }
105603             // Check if any referenced project tsconfig files are different
105604             if (!canReuseProjectReferences()) {
105605                 return 0 /* Not */;
105606             }
105607             if (projectReferences) {
105608                 resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
105609             }
105610             // check if program source files has changed in the way that can affect structure of the program
105611             var newSourceFiles = [];
105612             var modifiedSourceFiles = [];
105613             structureIsReused = 2 /* Completely */;
105614             // If the missing file paths are now present, it can change the progam structure,
105615             // and hence cant reuse the structure.
105616             // This is same as how we dont reuse the structure if one of the file from old program is now missing
105617             if (oldProgram.getMissingFilePaths().some(function (missingFilePath) { return host.fileExists(missingFilePath); })) {
105618                 return 0 /* Not */;
105619             }
105620             var oldSourceFiles = oldProgram.getSourceFiles();
105621             var SeenPackageName;
105622             (function (SeenPackageName) {
105623                 SeenPackageName[SeenPackageName["Exists"] = 0] = "Exists";
105624                 SeenPackageName[SeenPackageName["Modified"] = 1] = "Modified";
105625             })(SeenPackageName || (SeenPackageName = {}));
105626             var seenPackageNames = new ts.Map();
105627             for (var _i = 0, oldSourceFiles_2 = oldSourceFiles; _i < oldSourceFiles_2.length; _i++) {
105628                 var oldSourceFile = oldSourceFiles_2[_i];
105629                 var newSourceFile = host.getSourceFileByPath
105630                     ? host.getSourceFileByPath(oldSourceFile.fileName, oldSourceFile.resolvedPath, options.target, /*onError*/ undefined, shouldCreateNewSourceFile)
105631                     : host.getSourceFile(oldSourceFile.fileName, options.target, /*onError*/ undefined, shouldCreateNewSourceFile); // TODO: GH#18217
105632                 if (!newSourceFile) {
105633                     return 0 /* Not */;
105634                 }
105635                 ts.Debug.assert(!newSourceFile.redirectInfo, "Host should not return a redirect source file from `getSourceFile`");
105636                 var fileChanged = void 0;
105637                 if (oldSourceFile.redirectInfo) {
105638                     // We got `newSourceFile` by path, so it is actually for the unredirected file.
105639                     // This lets us know if the unredirected file has changed. If it has we should break the redirect.
105640                     if (newSourceFile !== oldSourceFile.redirectInfo.unredirected) {
105641                         // Underlying file has changed. Might not redirect anymore. Must rebuild program.
105642                         return 0 /* Not */;
105643                     }
105644                     fileChanged = false;
105645                     newSourceFile = oldSourceFile; // Use the redirect.
105646                 }
105647                 else if (oldProgram.redirectTargetsMap.has(oldSourceFile.path)) {
105648                     // If a redirected-to source file changes, the redirect may be broken.
105649                     if (newSourceFile !== oldSourceFile) {
105650                         return 0 /* Not */;
105651                     }
105652                     fileChanged = false;
105653                 }
105654                 else {
105655                     fileChanged = newSourceFile !== oldSourceFile;
105656                 }
105657                 // Since the project references havent changed, its right to set originalFileName and resolvedPath here
105658                 newSourceFile.path = oldSourceFile.path;
105659                 newSourceFile.originalFileName = oldSourceFile.originalFileName;
105660                 newSourceFile.resolvedPath = oldSourceFile.resolvedPath;
105661                 newSourceFile.fileName = oldSourceFile.fileName;
105662                 var packageName = oldProgram.sourceFileToPackageName.get(oldSourceFile.path);
105663                 if (packageName !== undefined) {
105664                     // If there are 2 different source files for the same package name and at least one of them changes,
105665                     // they might become redirects. So we must rebuild the program.
105666                     var prevKind = seenPackageNames.get(packageName);
105667                     var newKind = fileChanged ? 1 /* Modified */ : 0 /* Exists */;
105668                     if ((prevKind !== undefined && newKind === 1 /* Modified */) || prevKind === 1 /* Modified */) {
105669                         return 0 /* Not */;
105670                     }
105671                     seenPackageNames.set(packageName, newKind);
105672                 }
105673                 if (fileChanged) {
105674                     // The `newSourceFile` object was created for the new program.
105675                     if (!ts.arrayIsEqualTo(oldSourceFile.libReferenceDirectives, newSourceFile.libReferenceDirectives, fileReferenceIsEqualTo)) {
105676                         // 'lib' references has changed. Matches behavior in changesAffectModuleResolution
105677                         return 0 /* Not */;
105678                     }
105679                     if (oldSourceFile.hasNoDefaultLib !== newSourceFile.hasNoDefaultLib) {
105680                         // value of no-default-lib has changed
105681                         // this will affect if default library is injected into the list of files
105682                         structureIsReused = 1 /* SafeModules */;
105683                     }
105684                     // check tripleslash references
105685                     if (!ts.arrayIsEqualTo(oldSourceFile.referencedFiles, newSourceFile.referencedFiles, fileReferenceIsEqualTo)) {
105686                         // tripleslash references has changed
105687                         structureIsReused = 1 /* SafeModules */;
105688                     }
105689                     // check imports and module augmentations
105690                     collectExternalModuleReferences(newSourceFile);
105691                     if (!ts.arrayIsEqualTo(oldSourceFile.imports, newSourceFile.imports, moduleNameIsEqualTo)) {
105692                         // imports has changed
105693                         structureIsReused = 1 /* SafeModules */;
105694                     }
105695                     if (!ts.arrayIsEqualTo(oldSourceFile.moduleAugmentations, newSourceFile.moduleAugmentations, moduleNameIsEqualTo)) {
105696                         // moduleAugmentations has changed
105697                         structureIsReused = 1 /* SafeModules */;
105698                     }
105699                     if ((oldSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */) !== (newSourceFile.flags & 3145728 /* PermanentlySetIncrementalFlags */)) {
105700                         // dynamicImport has changed
105701                         structureIsReused = 1 /* SafeModules */;
105702                     }
105703                     if (!ts.arrayIsEqualTo(oldSourceFile.typeReferenceDirectives, newSourceFile.typeReferenceDirectives, fileReferenceIsEqualTo)) {
105704                         // 'types' references has changed
105705                         structureIsReused = 1 /* SafeModules */;
105706                     }
105707                     // tentatively approve the file
105708                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
105709                 }
105710                 else if (hasInvalidatedResolution(oldSourceFile.path)) {
105711                     // 'module/types' references could have changed
105712                     structureIsReused = 1 /* SafeModules */;
105713                     // add file to the modified list so that we will resolve it later
105714                     modifiedSourceFiles.push({ oldFile: oldSourceFile, newFile: newSourceFile });
105715                 }
105716                 // if file has passed all checks it should be safe to reuse it
105717                 newSourceFiles.push(newSourceFile);
105718             }
105719             if (structureIsReused !== 2 /* Completely */) {
105720                 return structureIsReused;
105721             }
105722             var modifiedFiles = modifiedSourceFiles.map(function (f) { return f.oldFile; });
105723             for (var _b = 0, oldSourceFiles_3 = oldSourceFiles; _b < oldSourceFiles_3.length; _b++) {
105724                 var oldFile = oldSourceFiles_3[_b];
105725                 if (!ts.contains(modifiedFiles, oldFile)) {
105726                     for (var _c = 0, _d = oldFile.ambientModuleNames; _c < _d.length; _c++) {
105727                         var moduleName = _d[_c];
105728                         ambientModuleNameToUnmodifiedFileName.set(moduleName, oldFile.fileName);
105729                     }
105730                 }
105731             }
105732             // try to verify results of module resolution
105733             for (var _e = 0, modifiedSourceFiles_1 = modifiedSourceFiles; _e < modifiedSourceFiles_1.length; _e++) {
105734                 var _f = modifiedSourceFiles_1[_e], oldSourceFile = _f.oldFile, newSourceFile = _f.newFile;
105735                 var moduleNames = getModuleNames(newSourceFile);
105736                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, newSourceFile);
105737                 // ensure that module resolution results are still correct
105738                 var resolutionsChanged = ts.hasChangesInResolutions(moduleNames, resolutions, oldSourceFile.resolvedModules, ts.moduleResolutionIsEqualTo);
105739                 if (resolutionsChanged) {
105740                     structureIsReused = 1 /* SafeModules */;
105741                     newSourceFile.resolvedModules = ts.zipToMap(moduleNames, resolutions);
105742                 }
105743                 else {
105744                     newSourceFile.resolvedModules = oldSourceFile.resolvedModules;
105745                 }
105746                 // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
105747                 var typesReferenceDirectives = ts.map(newSourceFile.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
105748                 var typeReferenceResolutions = resolveTypeReferenceDirectiveNamesWorker(typesReferenceDirectives, newSourceFile);
105749                 // ensure that types resolutions are still correct
105750                 var typeReferenceEesolutionsChanged = ts.hasChangesInResolutions(typesReferenceDirectives, typeReferenceResolutions, oldSourceFile.resolvedTypeReferenceDirectiveNames, ts.typeDirectiveIsEqualTo);
105751                 if (typeReferenceEesolutionsChanged) {
105752                     structureIsReused = 1 /* SafeModules */;
105753                     newSourceFile.resolvedTypeReferenceDirectiveNames = ts.zipToMap(typesReferenceDirectives, typeReferenceResolutions);
105754                 }
105755                 else {
105756                     newSourceFile.resolvedTypeReferenceDirectiveNames = oldSourceFile.resolvedTypeReferenceDirectiveNames;
105757                 }
105758             }
105759             if (structureIsReused !== 2 /* Completely */) {
105760                 return structureIsReused;
105761             }
105762             if ((_a = host.hasChangedAutomaticTypeDirectiveNames) === null || _a === void 0 ? void 0 : _a.call(host)) {
105763                 return 1 /* SafeModules */;
105764             }
105765             missingFilePaths = oldProgram.getMissingFilePaths();
105766             refFileMap = oldProgram.getRefFileMap();
105767             // update fileName -> file mapping
105768             ts.Debug.assert(newSourceFiles.length === oldProgram.getSourceFiles().length);
105769             for (var _g = 0, newSourceFiles_1 = newSourceFiles; _g < newSourceFiles_1.length; _g++) {
105770                 var newSourceFile = newSourceFiles_1[_g];
105771                 filesByName.set(newSourceFile.path, newSourceFile);
105772             }
105773             var oldFilesByNameMap = oldProgram.getFilesByNameMap();
105774             oldFilesByNameMap.forEach(function (oldFile, path) {
105775                 if (!oldFile) {
105776                     filesByName.set(path, oldFile);
105777                     return;
105778                 }
105779                 if (oldFile.path === path) {
105780                     // Set the file as found during node modules search if it was found that way in old progra,
105781                     if (oldProgram.isSourceFileFromExternalLibrary(oldFile)) {
105782                         sourceFilesFoundSearchingNodeModules.set(oldFile.path, true);
105783                     }
105784                     return;
105785                 }
105786                 filesByName.set(path, filesByName.get(oldFile.path));
105787             });
105788             files = newSourceFiles;
105789             fileProcessingDiagnostics = oldProgram.getFileProcessingDiagnostics();
105790             for (var _h = 0, modifiedSourceFiles_2 = modifiedSourceFiles; _h < modifiedSourceFiles_2.length; _h++) {
105791                 var modifiedFile = modifiedSourceFiles_2[_h];
105792                 fileProcessingDiagnostics.reattachFileDiagnostics(modifiedFile.newFile);
105793             }
105794             resolvedTypeReferenceDirectives = oldProgram.getResolvedTypeReferenceDirectives();
105795             sourceFileToPackageName = oldProgram.sourceFileToPackageName;
105796             redirectTargetsMap = oldProgram.redirectTargetsMap;
105797             return 2 /* Completely */;
105798         }
105799         function getEmitHost(writeFileCallback) {
105800             return {
105801                 getPrependNodes: getPrependNodes,
105802                 getCanonicalFileName: getCanonicalFileName,
105803                 getCommonSourceDirectory: program.getCommonSourceDirectory,
105804                 getCompilerOptions: program.getCompilerOptions,
105805                 getCurrentDirectory: function () { return currentDirectory; },
105806                 getNewLine: function () { return host.getNewLine(); },
105807                 getSourceFile: program.getSourceFile,
105808                 getSourceFileByPath: program.getSourceFileByPath,
105809                 getSourceFiles: program.getSourceFiles,
105810                 getLibFileFromReference: program.getLibFileFromReference,
105811                 isSourceFileFromExternalLibrary: isSourceFileFromExternalLibrary,
105812                 getResolvedProjectReferenceToRedirect: getResolvedProjectReferenceToRedirect,
105813                 getProjectReferenceRedirect: getProjectReferenceRedirect,
105814                 isSourceOfProjectReferenceRedirect: isSourceOfProjectReferenceRedirect,
105815                 getSymlinkCache: getSymlinkCache,
105816                 writeFile: writeFileCallback || (function (fileName, data, writeByteOrderMark, onError, sourceFiles) { return host.writeFile(fileName, data, writeByteOrderMark, onError, sourceFiles); }),
105817                 isEmitBlocked: isEmitBlocked,
105818                 readFile: function (f) { return host.readFile(f); },
105819                 fileExists: function (f) {
105820                     // Use local caches
105821                     var path = toPath(f);
105822                     if (getSourceFileByPath(path))
105823                         return true;
105824                     if (ts.contains(missingFilePaths, path))
105825                         return false;
105826                     // Before falling back to the host
105827                     return host.fileExists(f);
105828                 },
105829                 useCaseSensitiveFileNames: function () { return host.useCaseSensitiveFileNames(); },
105830                 getProgramBuildInfo: function () { return program.getProgramBuildInfo && program.getProgramBuildInfo(); },
105831                 getSourceFileFromReference: function (file, ref) { return program.getSourceFileFromReference(file, ref); },
105832                 redirectTargetsMap: redirectTargetsMap,
105833             };
105834         }
105835         function emitBuildInfo(writeFileCallback) {
105836             ts.Debug.assert(!ts.outFile(options));
105837             var tracingData = ["emit" /* Emit */, "emitBuildInfo"];
105838             ts.tracing.begin.apply(ts.tracing, tracingData);
105839             ts.performance.mark("beforeEmit");
105840             var emitResult = ts.emitFiles(ts.notImplementedResolver, getEmitHost(writeFileCallback), 
105841             /*targetSourceFile*/ undefined, 
105842             /*transformers*/ ts.noTransformers, 
105843             /*emitOnlyDtsFiles*/ false, 
105844             /*onlyBuildInfo*/ true);
105845             ts.performance.mark("afterEmit");
105846             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
105847             ts.tracing.end.apply(ts.tracing, tracingData);
105848             return emitResult;
105849         }
105850         function getResolvedProjectReferences() {
105851             return resolvedProjectReferences;
105852         }
105853         function getProjectReferences() {
105854             return projectReferences;
105855         }
105856         function getPrependNodes() {
105857             return createPrependNodes(projectReferences, function (_ref, index) { var _a; return (_a = resolvedProjectReferences[index]) === null || _a === void 0 ? void 0 : _a.commandLine; }, function (fileName) {
105858                 var path = toPath(fileName);
105859                 var sourceFile = getSourceFileByPath(path);
105860                 return sourceFile ? sourceFile.text : filesByName.has(path) ? undefined : host.readFile(path);
105861             });
105862         }
105863         function isSourceFileFromExternalLibrary(file) {
105864             return !!sourceFilesFoundSearchingNodeModules.get(file.path);
105865         }
105866         function isSourceFileDefaultLibrary(file) {
105867             if (file.hasNoDefaultLib) {
105868                 return true;
105869             }
105870             if (!options.noLib) {
105871                 return false;
105872             }
105873             // If '--lib' is not specified, include default library file according to '--target'
105874             // otherwise, using options specified in '--lib' instead of '--target' default library file
105875             var equalityComparer = host.useCaseSensitiveFileNames() ? ts.equateStringsCaseSensitive : ts.equateStringsCaseInsensitive;
105876             if (!options.lib) {
105877                 return equalityComparer(file.fileName, getDefaultLibraryFileName());
105878             }
105879             else {
105880                 return ts.some(options.lib, function (libFileName) { return equalityComparer(file.fileName, ts.combinePaths(defaultLibraryPath, libFileName)); });
105881             }
105882         }
105883         function getDiagnosticsProducingTypeChecker() {
105884             return diagnosticsProducingTypeChecker || (diagnosticsProducingTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ true));
105885         }
105886         function dropDiagnosticsProducingTypeChecker() {
105887             diagnosticsProducingTypeChecker = undefined;
105888         }
105889         function getTypeChecker() {
105890             return noDiagnosticsTypeChecker || (noDiagnosticsTypeChecker = ts.createTypeChecker(program, /*produceDiagnostics:*/ false));
105891         }
105892         function emit(sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit) {
105893             var tracingData = ["emit" /* Emit */, "emit", { path: sourceFile === null || sourceFile === void 0 ? void 0 : sourceFile.path }];
105894             ts.tracing.begin.apply(ts.tracing, tracingData);
105895             var result = runWithCancellationToken(function () { return emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, transformers, forceDtsEmit); });
105896             ts.tracing.end.apply(ts.tracing, tracingData);
105897             return result;
105898         }
105899         function isEmitBlocked(emitFileName) {
105900             return hasEmitBlockingDiagnostics.has(toPath(emitFileName));
105901         }
105902         function emitWorker(program, sourceFile, writeFileCallback, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit) {
105903             if (!forceDtsEmit) {
105904                 var result = handleNoEmitOptions(program, sourceFile, writeFileCallback, cancellationToken);
105905                 if (result)
105906                     return result;
105907             }
105908             // Create the emit resolver outside of the "emitTime" tracking code below.  That way
105909             // any cost associated with it (like type checking) are appropriate associated with
105910             // the type-checking counter.
105911             //
105912             // If the -out option is specified, we should not pass the source file to getEmitResolver.
105913             // This is because in the -out scenario all files need to be emitted, and therefore all
105914             // files need to be type checked. And the way to specify that all files need to be type
105915             // checked is to not pass the file to getEmitResolver.
105916             var emitResolver = getDiagnosticsProducingTypeChecker().getEmitResolver(ts.outFile(options) ? undefined : sourceFile, cancellationToken);
105917             ts.performance.mark("beforeEmit");
105918             var emitResult = ts.emitFiles(emitResolver, getEmitHost(writeFileCallback), sourceFile, ts.getTransformers(options, customTransformers, emitOnlyDtsFiles), emitOnlyDtsFiles, 
105919             /*onlyBuildInfo*/ false, forceDtsEmit);
105920             ts.performance.mark("afterEmit");
105921             ts.performance.measure("Emit", "beforeEmit", "afterEmit");
105922             return emitResult;
105923         }
105924         function getSourceFile(fileName) {
105925             return getSourceFileByPath(toPath(fileName));
105926         }
105927         function getSourceFileByPath(path) {
105928             return filesByName.get(path) || undefined;
105929         }
105930         function getDiagnosticsHelper(sourceFile, getDiagnostics, cancellationToken) {
105931             if (sourceFile) {
105932                 return getDiagnostics(sourceFile, cancellationToken);
105933             }
105934             return ts.sortAndDeduplicateDiagnostics(ts.flatMap(program.getSourceFiles(), function (sourceFile) {
105935                 if (cancellationToken) {
105936                     cancellationToken.throwIfCancellationRequested();
105937                 }
105938                 return getDiagnostics(sourceFile, cancellationToken);
105939             }));
105940         }
105941         function getSyntacticDiagnostics(sourceFile, cancellationToken) {
105942             return getDiagnosticsHelper(sourceFile, getSyntacticDiagnosticsForFile, cancellationToken);
105943         }
105944         function getSemanticDiagnostics(sourceFile, cancellationToken) {
105945             return getDiagnosticsHelper(sourceFile, getSemanticDiagnosticsForFile, cancellationToken);
105946         }
105947         function getCachedSemanticDiagnostics(sourceFile) {
105948             var _a;
105949             return sourceFile
105950                 ? (_a = cachedBindAndCheckDiagnosticsForFile.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path) : cachedBindAndCheckDiagnosticsForFile.allDiagnostics;
105951         }
105952         function getBindAndCheckDiagnostics(sourceFile, cancellationToken) {
105953             return getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken);
105954         }
105955         function getProgramDiagnostics(sourceFile) {
105956             if (ts.skipTypeChecking(sourceFile, options, program)) {
105957                 return ts.emptyArray;
105958             }
105959             var fileProcessingDiagnosticsInFile = fileProcessingDiagnostics.getDiagnostics(sourceFile.fileName);
105960             var programDiagnosticsInFile = programDiagnostics.getDiagnostics(sourceFile.fileName);
105961             return getMergedProgramDiagnostics(sourceFile, fileProcessingDiagnosticsInFile, programDiagnosticsInFile);
105962         }
105963         function getMergedProgramDiagnostics(sourceFile) {
105964             var _a;
105965             var allDiagnostics = [];
105966             for (var _i = 1; _i < arguments.length; _i++) {
105967                 allDiagnostics[_i - 1] = arguments[_i];
105968             }
105969             var flatDiagnostics = ts.flatten(allDiagnostics);
105970             if (!((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
105971                 return flatDiagnostics;
105972             }
105973             return getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics).diagnostics;
105974         }
105975         function getDeclarationDiagnostics(sourceFile, cancellationToken) {
105976             var options = program.getCompilerOptions();
105977             // collect diagnostics from the program only once if either no source file was specified or out/outFile is set (bundled emit)
105978             if (!sourceFile || ts.outFile(options)) {
105979                 return getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
105980             }
105981             else {
105982                 return getDiagnosticsHelper(sourceFile, getDeclarationDiagnosticsForFile, cancellationToken);
105983             }
105984         }
105985         function getSyntacticDiagnosticsForFile(sourceFile) {
105986             // For JavaScript files, we report semantic errors for using TypeScript-only
105987             // constructs from within a JavaScript file as syntactic errors.
105988             if (ts.isSourceFileJS(sourceFile)) {
105989                 if (!sourceFile.additionalSyntacticDiagnostics) {
105990                     sourceFile.additionalSyntacticDiagnostics = getJSSyntacticDiagnosticsForFile(sourceFile);
105991                 }
105992                 return ts.concatenate(sourceFile.additionalSyntacticDiagnostics, sourceFile.parseDiagnostics);
105993             }
105994             return sourceFile.parseDiagnostics;
105995         }
105996         function runWithCancellationToken(func) {
105997             try {
105998                 return func();
105999             }
106000             catch (e) {
106001                 if (e instanceof ts.OperationCanceledException) {
106002                     // We were canceled while performing the operation.  Because our type checker
106003                     // might be a bad state, we need to throw it away.
106004                     //
106005                     // Note: we are overly aggressive here.  We do not actually *have* to throw away
106006                     // the "noDiagnosticsTypeChecker".  However, for simplicity, i'd like to keep
106007                     // the lifetimes of these two TypeCheckers the same.  Also, we generally only
106008                     // cancel when the user has made a change anyways.  And, in that case, we (the
106009                     // program instance) will get thrown away anyways.  So trying to keep one of
106010                     // these type checkers alive doesn't serve much purpose.
106011                     noDiagnosticsTypeChecker = undefined;
106012                     diagnosticsProducingTypeChecker = undefined;
106013                 }
106014                 throw e;
106015             }
106016         }
106017         function getSemanticDiagnosticsForFile(sourceFile, cancellationToken) {
106018             return ts.concatenate(filterSemanticDiagnotics(getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken), options), getProgramDiagnostics(sourceFile));
106019         }
106020         function getBindAndCheckDiagnosticsForFile(sourceFile, cancellationToken) {
106021             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedBindAndCheckDiagnosticsForFile, getBindAndCheckDiagnosticsForFileNoCache);
106022         }
106023         function getBindAndCheckDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
106024             return runWithCancellationToken(function () {
106025                 if (ts.skipTypeChecking(sourceFile, options, program)) {
106026                     return ts.emptyArray;
106027                 }
106028                 var typeChecker = getDiagnosticsProducingTypeChecker();
106029                 ts.Debug.assert(!!sourceFile.bindDiagnostics);
106030                 var isCheckJs = ts.isCheckJsEnabledForFile(sourceFile, options);
106031                 var isTsNoCheck = !!sourceFile.checkJsDirective && sourceFile.checkJsDirective.enabled === false;
106032                 // By default, only type-check .ts, .tsx, 'Deferred' and 'External' files (external files are added by plugins)
106033                 var includeBindAndCheckDiagnostics = !isTsNoCheck && (sourceFile.scriptKind === 3 /* TS */ || sourceFile.scriptKind === 4 /* TSX */ ||
106034                     sourceFile.scriptKind === 5 /* External */ || isCheckJs || sourceFile.scriptKind === 7 /* Deferred */);
106035                 var bindDiagnostics = includeBindAndCheckDiagnostics ? sourceFile.bindDiagnostics : ts.emptyArray;
106036                 var checkDiagnostics = includeBindAndCheckDiagnostics ? typeChecker.getDiagnostics(sourceFile, cancellationToken) : ts.emptyArray;
106037                 return getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics, bindDiagnostics, checkDiagnostics, isCheckJs ? sourceFile.jsDocDiagnostics : undefined);
106038             });
106039         }
106040         function getMergedBindAndCheckDiagnostics(sourceFile, includeBindAndCheckDiagnostics) {
106041             var _a;
106042             var allDiagnostics = [];
106043             for (var _i = 2; _i < arguments.length; _i++) {
106044                 allDiagnostics[_i - 2] = arguments[_i];
106045             }
106046             var flatDiagnostics = ts.flatten(allDiagnostics);
106047             if (!includeBindAndCheckDiagnostics || !((_a = sourceFile.commentDirectives) === null || _a === void 0 ? void 0 : _a.length)) {
106048                 return flatDiagnostics;
106049             }
106050             var _b = getDiagnosticsWithPrecedingDirectives(sourceFile, sourceFile.commentDirectives, flatDiagnostics), diagnostics = _b.diagnostics, directives = _b.directives;
106051             for (var _c = 0, _d = directives.getUnusedExpectations(); _c < _d.length; _c++) {
106052                 var errorExpectation = _d[_c];
106053                 diagnostics.push(ts.createDiagnosticForRange(sourceFile, errorExpectation.range, ts.Diagnostics.Unused_ts_expect_error_directive));
106054             }
106055             return diagnostics;
106056         }
106057         /**
106058          * Creates a map of comment directives along with the diagnostics immediately preceded by one of them.
106059          * Comments that match to any of those diagnostics are marked as used.
106060          */
106061         function getDiagnosticsWithPrecedingDirectives(sourceFile, commentDirectives, flatDiagnostics) {
106062             // Diagnostics are only reported if there is no comment directive preceding them
106063             // This will modify the directives map by marking "used" ones with a corresponding diagnostic
106064             var directives = ts.createCommentDirectivesMap(sourceFile, commentDirectives);
106065             var diagnostics = flatDiagnostics.filter(function (diagnostic) { return markPrecedingCommentDirectiveLine(diagnostic, directives) === -1; });
106066             return { diagnostics: diagnostics, directives: directives };
106067         }
106068         function getSuggestionDiagnostics(sourceFile, cancellationToken) {
106069             return runWithCancellationToken(function () {
106070                 return getDiagnosticsProducingTypeChecker().getSuggestionDiagnostics(sourceFile, cancellationToken);
106071             });
106072         }
106073         /**
106074          * @returns The line index marked as preceding the diagnostic, or -1 if none was.
106075          */
106076         function markPrecedingCommentDirectiveLine(diagnostic, directives) {
106077             var file = diagnostic.file, start = diagnostic.start;
106078             if (!file) {
106079                 return -1;
106080             }
106081             // Start out with the line just before the text
106082             var lineStarts = ts.getLineStarts(file);
106083             var line = ts.computeLineAndCharacterOfPosition(lineStarts, start).line - 1; // TODO: GH#18217
106084             while (line >= 0) {
106085                 // As soon as that line is known to have a comment directive, use that
106086                 if (directives.markUsed(line)) {
106087                     return line;
106088                 }
106089                 // Stop searching if the line is not empty and not a comment
106090                 var lineText = file.text.slice(lineStarts[line], lineStarts[line + 1]).trim();
106091                 if (lineText !== "" && !/^(\s*)\/\/(.*)$/.test(lineText)) {
106092                     return -1;
106093                 }
106094                 line--;
106095             }
106096             return -1;
106097         }
106098         function getJSSyntacticDiagnosticsForFile(sourceFile) {
106099             return runWithCancellationToken(function () {
106100                 var diagnostics = [];
106101                 walk(sourceFile, sourceFile);
106102                 ts.forEachChildRecursively(sourceFile, walk, walkArray);
106103                 return diagnostics;
106104                 function walk(node, parent) {
106105                     // Return directly from the case if the given node doesnt want to visit each child
106106                     // Otherwise break to visit each child
106107                     switch (parent.kind) {
106108                         case 160 /* Parameter */:
106109                         case 163 /* PropertyDeclaration */:
106110                         case 165 /* MethodDeclaration */:
106111                             if (parent.questionToken === node) {
106112                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, "?"));
106113                                 return "skip";
106114                             }
106115                         // falls through
106116                         case 164 /* MethodSignature */:
106117                         case 166 /* Constructor */:
106118                         case 167 /* GetAccessor */:
106119                         case 168 /* SetAccessor */:
106120                         case 208 /* FunctionExpression */:
106121                         case 251 /* FunctionDeclaration */:
106122                         case 209 /* ArrowFunction */:
106123                         case 249 /* VariableDeclaration */:
106124                             // type annotation
106125                             if (parent.type === node) {
106126                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_annotations_can_only_be_used_in_TypeScript_files));
106127                                 return "skip";
106128                             }
106129                     }
106130                     switch (node.kind) {
106131                         case 262 /* ImportClause */:
106132                             if (node.isTypeOnly) {
106133                                 diagnostics.push(createDiagnosticForNode(parent, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "import type"));
106134                                 return "skip";
106135                             }
106136                             break;
106137                         case 267 /* ExportDeclaration */:
106138                             if (node.isTypeOnly) {
106139                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, "export type"));
106140                                 return "skip";
106141                             }
106142                             break;
106143                         case 260 /* ImportEqualsDeclaration */:
106144                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.import_can_only_be_used_in_TypeScript_files));
106145                             return "skip";
106146                         case 266 /* ExportAssignment */:
106147                             if (node.isExportEquals) {
106148                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.export_can_only_be_used_in_TypeScript_files));
106149                                 return "skip";
106150                             }
106151                             break;
106152                         case 286 /* HeritageClause */:
106153                             var heritageClause = node;
106154                             if (heritageClause.token === 116 /* ImplementsKeyword */) {
106155                                 diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.implements_clauses_can_only_be_used_in_TypeScript_files));
106156                                 return "skip";
106157                             }
106158                             break;
106159                         case 253 /* InterfaceDeclaration */:
106160                             var interfaceKeyword = ts.tokenToString(117 /* InterfaceKeyword */);
106161                             ts.Debug.assertIsDefined(interfaceKeyword);
106162                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, interfaceKeyword));
106163                             return "skip";
106164                         case 256 /* ModuleDeclaration */:
106165                             var moduleKeyword = node.flags & 16 /* Namespace */ ? ts.tokenToString(140 /* NamespaceKeyword */) : ts.tokenToString(139 /* ModuleKeyword */);
106166                             ts.Debug.assertIsDefined(moduleKeyword);
106167                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, moduleKeyword));
106168                             return "skip";
106169                         case 254 /* TypeAliasDeclaration */:
106170                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Type_aliases_can_only_be_used_in_TypeScript_files));
106171                             return "skip";
106172                         case 255 /* EnumDeclaration */:
106173                             var enumKeyword = ts.Debug.checkDefined(ts.tokenToString(91 /* EnumKeyword */));
106174                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics._0_declarations_can_only_be_used_in_TypeScript_files, enumKeyword));
106175                             return "skip";
106176                         case 225 /* NonNullExpression */:
106177                             diagnostics.push(createDiagnosticForNode(node, ts.Diagnostics.Non_null_assertions_can_only_be_used_in_TypeScript_files));
106178                             return "skip";
106179                         case 224 /* AsExpression */:
106180                             diagnostics.push(createDiagnosticForNode(node.type, ts.Diagnostics.Type_assertion_expressions_can_only_be_used_in_TypeScript_files));
106181                             return "skip";
106182                         case 206 /* TypeAssertionExpression */:
106183                             ts.Debug.fail(); // Won't parse these in a JS file anyway, as they are interpreted as JSX.
106184                     }
106185                 }
106186                 function walkArray(nodes, parent) {
106187                     if (parent.decorators === nodes && !options.experimentalDecorators) {
106188                         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));
106189                     }
106190                     switch (parent.kind) {
106191                         case 252 /* ClassDeclaration */:
106192                         case 221 /* ClassExpression */:
106193                         case 165 /* MethodDeclaration */:
106194                         case 166 /* Constructor */:
106195                         case 167 /* GetAccessor */:
106196                         case 168 /* SetAccessor */:
106197                         case 208 /* FunctionExpression */:
106198                         case 251 /* FunctionDeclaration */:
106199                         case 209 /* ArrowFunction */:
106200                             // Check type parameters
106201                             if (nodes === parent.typeParameters) {
106202                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_parameter_declarations_can_only_be_used_in_TypeScript_files));
106203                                 return "skip";
106204                             }
106205                         // falls through
106206                         case 232 /* VariableStatement */:
106207                             // Check modifiers
106208                             if (nodes === parent.modifiers) {
106209                                 checkModifiers(parent.modifiers, parent.kind === 232 /* VariableStatement */);
106210                                 return "skip";
106211                             }
106212                             break;
106213                         case 163 /* PropertyDeclaration */:
106214                             // Check modifiers of property declaration
106215                             if (nodes === parent.modifiers) {
106216                                 for (var _i = 0, _a = nodes; _i < _a.length; _i++) {
106217                                     var modifier = _a[_i];
106218                                     if (modifier.kind !== 123 /* StaticKeyword */) {
106219                                         diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
106220                                     }
106221                                 }
106222                                 return "skip";
106223                             }
106224                             break;
106225                         case 160 /* Parameter */:
106226                             // Check modifiers of parameter declaration
106227                             if (nodes === parent.modifiers) {
106228                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Parameter_modifiers_can_only_be_used_in_TypeScript_files));
106229                                 return "skip";
106230                             }
106231                             break;
106232                         case 203 /* CallExpression */:
106233                         case 204 /* NewExpression */:
106234                         case 223 /* ExpressionWithTypeArguments */:
106235                         case 274 /* JsxSelfClosingElement */:
106236                         case 275 /* JsxOpeningElement */:
106237                         case 205 /* TaggedTemplateExpression */:
106238                             // Check type arguments
106239                             if (nodes === parent.typeArguments) {
106240                                 diagnostics.push(createDiagnosticForNodeArray(nodes, ts.Diagnostics.Type_arguments_can_only_be_used_in_TypeScript_files));
106241                                 return "skip";
106242                             }
106243                             break;
106244                     }
106245                 }
106246                 function checkModifiers(modifiers, isConstValid) {
106247                     for (var _i = 0, modifiers_2 = modifiers; _i < modifiers_2.length; _i++) {
106248                         var modifier = modifiers_2[_i];
106249                         switch (modifier.kind) {
106250                             case 84 /* ConstKeyword */:
106251                                 if (isConstValid) {
106252                                     continue;
106253                                 }
106254                             // to report error,
106255                             // falls through
106256                             case 122 /* PublicKeyword */:
106257                             case 120 /* PrivateKeyword */:
106258                             case 121 /* ProtectedKeyword */:
106259                             case 142 /* ReadonlyKeyword */:
106260                             case 133 /* DeclareKeyword */:
106261                             case 125 /* AbstractKeyword */:
106262                                 diagnostics.push(createDiagnosticForNode(modifier, ts.Diagnostics.The_0_modifier_can_only_be_used_in_TypeScript_files, ts.tokenToString(modifier.kind)));
106263                                 break;
106264                             // These are all legal modifiers.
106265                             case 123 /* StaticKeyword */:
106266                             case 92 /* ExportKeyword */:
106267                             case 87 /* DefaultKeyword */:
106268                         }
106269                     }
106270                 }
106271                 function createDiagnosticForNodeArray(nodes, message, arg0, arg1, arg2) {
106272                     var start = nodes.pos;
106273                     return ts.createFileDiagnostic(sourceFile, start, nodes.end - start, message, arg0, arg1, arg2);
106274                 }
106275                 // Since these are syntactic diagnostics, parent might not have been set
106276                 // this means the sourceFile cannot be infered from the node
106277                 function createDiagnosticForNode(node, message, arg0, arg1, arg2) {
106278                     return ts.createDiagnosticForNodeInSourceFile(sourceFile, node, message, arg0, arg1, arg2);
106279                 }
106280             });
106281         }
106282         function getDeclarationDiagnosticsWorker(sourceFile, cancellationToken) {
106283             return getAndCacheDiagnostics(sourceFile, cancellationToken, cachedDeclarationDiagnosticsForFile, getDeclarationDiagnosticsForFileNoCache);
106284         }
106285         function getDeclarationDiagnosticsForFileNoCache(sourceFile, cancellationToken) {
106286             return runWithCancellationToken(function () {
106287                 var resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
106288                 // Don't actually write any files since we're just getting diagnostics.
106289                 return ts.getDeclarationDiagnostics(getEmitHost(ts.noop), resolver, sourceFile) || ts.emptyArray;
106290             });
106291         }
106292         function getAndCacheDiagnostics(sourceFile, cancellationToken, cache, getDiagnostics) {
106293             var _a;
106294             var cachedResult = sourceFile
106295                 ? (_a = cache.perFile) === null || _a === void 0 ? void 0 : _a.get(sourceFile.path) : cache.allDiagnostics;
106296             if (cachedResult) {
106297                 return cachedResult;
106298             }
106299             var result = getDiagnostics(sourceFile, cancellationToken);
106300             if (sourceFile) {
106301                 (cache.perFile || (cache.perFile = new ts.Map())).set(sourceFile.path, result);
106302             }
106303             else {
106304                 cache.allDiagnostics = result;
106305             }
106306             return result;
106307         }
106308         function getDeclarationDiagnosticsForFile(sourceFile, cancellationToken) {
106309             return sourceFile.isDeclarationFile ? [] : getDeclarationDiagnosticsWorker(sourceFile, cancellationToken);
106310         }
106311         function getOptionsDiagnostics() {
106312             return ts.sortAndDeduplicateDiagnostics(ts.concatenate(fileProcessingDiagnostics.getGlobalDiagnostics(), ts.concatenate(programDiagnostics.getGlobalDiagnostics(), getOptionsDiagnosticsOfConfigFile())));
106313         }
106314         function getOptionsDiagnosticsOfConfigFile() {
106315             if (!options.configFile) {
106316                 return ts.emptyArray;
106317             }
106318             var diagnostics = programDiagnostics.getDiagnostics(options.configFile.fileName);
106319             forEachResolvedProjectReference(function (resolvedRef) {
106320                 diagnostics = ts.concatenate(diagnostics, programDiagnostics.getDiagnostics(resolvedRef.sourceFile.fileName));
106321             });
106322             return diagnostics;
106323         }
106324         function getGlobalDiagnostics() {
106325             return rootNames.length ? ts.sortAndDeduplicateDiagnostics(getDiagnosticsProducingTypeChecker().getGlobalDiagnostics().slice()) : ts.emptyArray;
106326         }
106327         function getConfigFileParsingDiagnostics() {
106328             return configFileParsingDiagnostics || ts.emptyArray;
106329         }
106330         function processRootFile(fileName, isDefaultLib, ignoreNoDefaultLib) {
106331             processSourceFile(ts.normalizePath(fileName), isDefaultLib, ignoreNoDefaultLib, /*packageId*/ undefined);
106332         }
106333         function fileReferenceIsEqualTo(a, b) {
106334             return a.fileName === b.fileName;
106335         }
106336         function moduleNameIsEqualTo(a, b) {
106337             return a.kind === 78 /* Identifier */
106338                 ? b.kind === 78 /* Identifier */ && a.escapedText === b.escapedText
106339                 : b.kind === 10 /* StringLiteral */ && a.text === b.text;
106340         }
106341         function createSyntheticImport(text, file) {
106342             var externalHelpersModuleReference = ts.factory.createStringLiteral(text);
106343             var importDecl = ts.factory.createImportDeclaration(/*decorators*/ undefined, /*modifiers*/ undefined, /*importClause*/ undefined, externalHelpersModuleReference);
106344             ts.addEmitFlags(importDecl, 67108864 /* NeverApplyImportHelper */);
106345             ts.setParent(externalHelpersModuleReference, importDecl);
106346             ts.setParent(importDecl, file);
106347             // explicitly unset the synthesized flag on these declarations so the checker API will answer questions about them
106348             // (which is required to build the dependency graph for incremental emit)
106349             externalHelpersModuleReference.flags &= ~8 /* Synthesized */;
106350             importDecl.flags &= ~8 /* Synthesized */;
106351             return externalHelpersModuleReference;
106352         }
106353         function collectExternalModuleReferences(file) {
106354             if (file.imports) {
106355                 return;
106356             }
106357             var isJavaScriptFile = ts.isSourceFileJS(file);
106358             var isExternalModuleFile = ts.isExternalModule(file);
106359             // file.imports may not be undefined if there exists dynamic import
106360             var imports;
106361             var moduleAugmentations;
106362             var ambientModules;
106363             // If we are importing helpers, we need to add a synthetic reference to resolve the
106364             // helpers library.
106365             if ((options.isolatedModules || isExternalModuleFile)
106366                 && !file.isDeclarationFile) {
106367                 if (options.importHelpers) {
106368                     // synthesize 'import "tslib"' declaration
106369                     imports = [createSyntheticImport(ts.externalHelpersModuleNameText, file)];
106370                 }
106371                 var jsxImport = ts.getJSXRuntimeImport(ts.getJSXImplicitImportBase(options, file), options);
106372                 if (jsxImport) {
106373                     // synthesize `import "base/jsx-runtime"` declaration
106374                     (imports || (imports = [])).push(createSyntheticImport(jsxImport, file));
106375                 }
106376             }
106377             for (var _i = 0, _a = file.statements; _i < _a.length; _i++) {
106378                 var node = _a[_i];
106379                 collectModuleReferences(node, /*inAmbientModule*/ false);
106380             }
106381             if ((file.flags & 1048576 /* PossiblyContainsDynamicImport */) || isJavaScriptFile) {
106382                 collectDynamicImportOrRequireCalls(file);
106383             }
106384             file.imports = imports || ts.emptyArray;
106385             file.moduleAugmentations = moduleAugmentations || ts.emptyArray;
106386             file.ambientModuleNames = ambientModules || ts.emptyArray;
106387             return;
106388             function collectModuleReferences(node, inAmbientModule) {
106389                 if (ts.isAnyImportOrReExport(node)) {
106390                     var moduleNameExpr = ts.getExternalModuleName(node);
106391                     // TypeScript 1.0 spec (April 2014): 12.1.6
106392                     // An ExternalImportDeclaration in an AmbientExternalModuleDeclaration may reference other external modules
106393                     // only through top - level external module names. Relative external module names are not permitted.
106394                     if (moduleNameExpr && ts.isStringLiteral(moduleNameExpr) && moduleNameExpr.text && (!inAmbientModule || !ts.isExternalModuleNameRelative(moduleNameExpr.text))) {
106395                         imports = ts.append(imports, moduleNameExpr);
106396                     }
106397                 }
106398                 else if (ts.isModuleDeclaration(node)) {
106399                     if (ts.isAmbientModule(node) && (inAmbientModule || ts.hasSyntacticModifier(node, 2 /* Ambient */) || file.isDeclarationFile)) {
106400                         var nameText = ts.getTextOfIdentifierOrLiteral(node.name);
106401                         // Ambient module declarations can be interpreted as augmentations for some existing external modules.
106402                         // This will happen in two cases:
106403                         // - if current file is external module then module augmentation is a ambient module declaration defined in the top level scope
106404                         // - if current file is not external module then module augmentation is an ambient module declaration with non-relative module name
106405                         //   immediately nested in top level ambient module declaration .
106406                         if (isExternalModuleFile || (inAmbientModule && !ts.isExternalModuleNameRelative(nameText))) {
106407                             (moduleAugmentations || (moduleAugmentations = [])).push(node.name);
106408                         }
106409                         else if (!inAmbientModule) {
106410                             if (file.isDeclarationFile) {
106411                                 // for global .d.ts files record name of ambient module
106412                                 (ambientModules || (ambientModules = [])).push(nameText);
106413                             }
106414                             // An AmbientExternalModuleDeclaration declares an external module.
106415                             // This type of declaration is permitted only in the global module.
106416                             // The StringLiteral must specify a top - level external module name.
106417                             // Relative external module names are not permitted
106418                             // NOTE: body of ambient module is always a module block, if it exists
106419                             var body = node.body;
106420                             if (body) {
106421                                 for (var _i = 0, _a = body.statements; _i < _a.length; _i++) {
106422                                     var statement = _a[_i];
106423                                     collectModuleReferences(statement, /*inAmbientModule*/ true);
106424                                 }
106425                             }
106426                         }
106427                     }
106428                 }
106429             }
106430             function collectDynamicImportOrRequireCalls(file) {
106431                 var r = /import|require/g;
106432                 while (r.exec(file.text) !== null) { // eslint-disable-line no-null/no-null
106433                     var node = getNodeAtPosition(file, r.lastIndex);
106434                     if (isJavaScriptFile && ts.isRequireCall(node, /*checkArgumentIsStringLiteralLike*/ true)) {
106435                         imports = ts.append(imports, node.arguments[0]);
106436                     }
106437                     // we have to check the argument list has length of 1. We will still have to process these even though we have parsing error.
106438                     else if (ts.isImportCall(node) && node.arguments.length === 1 && ts.isStringLiteralLike(node.arguments[0])) {
106439                         imports = ts.append(imports, node.arguments[0]);
106440                     }
106441                     else if (ts.isLiteralImportTypeNode(node)) {
106442                         imports = ts.append(imports, node.argument.literal);
106443                     }
106444                 }
106445             }
106446             /** Returns a token if position is in [start-of-leading-trivia, end), includes JSDoc only in JS files */
106447             function getNodeAtPosition(sourceFile, position) {
106448                 var current = sourceFile;
106449                 var getContainingChild = function (child) {
106450                     if (child.pos <= position && (position < child.end || (position === child.end && (child.kind === 1 /* EndOfFileToken */)))) {
106451                         return child;
106452                     }
106453                 };
106454                 while (true) {
106455                     var child = isJavaScriptFile && ts.hasJSDocNodes(current) && ts.forEach(current.jsDoc, getContainingChild) || ts.forEachChild(current, getContainingChild);
106456                     if (!child) {
106457                         return current;
106458                     }
106459                     current = child;
106460                 }
106461             }
106462         }
106463         function getLibFileFromReference(ref) {
106464             var libName = ts.toFileNameLowerCase(ref.fileName);
106465             var libFileName = ts.libMap.get(libName);
106466             if (libFileName) {
106467                 return getSourceFile(ts.combinePaths(defaultLibraryPath, libFileName));
106468             }
106469         }
106470         /** This should have similar behavior to 'processSourceFile' without diagnostics or mutation. */
106471         function getSourceFileFromReference(referencingFile, ref) {
106472             return getSourceFileFromReferenceWorker(resolveTripleslashReference(ref.fileName, referencingFile.fileName), function (fileName) { return filesByName.get(toPath(fileName)) || undefined; });
106473         }
106474         function getSourceFileFromReferenceWorker(fileName, getSourceFile, fail, refFile) {
106475             if (ts.hasExtension(fileName)) {
106476                 var canonicalFileName_1 = host.getCanonicalFileName(fileName);
106477                 if (!options.allowNonTsExtensions && !ts.forEach(supportedExtensionsWithJsonIfResolveJsonModule, function (extension) { return ts.fileExtensionIs(canonicalFileName_1, extension); })) {
106478                     if (fail) {
106479                         if (ts.hasJSFileExtension(canonicalFileName_1)) {
106480                             fail(ts.Diagnostics.File_0_is_a_JavaScript_file_Did_you_mean_to_enable_the_allowJs_option, fileName);
106481                         }
106482                         else {
106483                             fail(ts.Diagnostics.File_0_has_an_unsupported_extension_The_only_supported_extensions_are_1, fileName, "'" + supportedExtensions.join("', '") + "'");
106484                         }
106485                     }
106486                     return undefined;
106487                 }
106488                 var sourceFile = getSourceFile(fileName);
106489                 if (fail) {
106490                     if (!sourceFile) {
106491                         var redirect = getProjectReferenceRedirect(fileName);
106492                         if (redirect) {
106493                             fail(ts.Diagnostics.Output_file_0_has_not_been_built_from_source_file_1, redirect, fileName);
106494                         }
106495                         else {
106496                             fail(ts.Diagnostics.File_0_not_found, fileName);
106497                         }
106498                     }
106499                     else if (refFile && canonicalFileName_1 === host.getCanonicalFileName(refFile.fileName)) {
106500                         fail(ts.Diagnostics.A_file_cannot_have_a_reference_to_itself);
106501                     }
106502                 }
106503                 return sourceFile;
106504             }
106505             else {
106506                 var sourceFileNoExtension = options.allowNonTsExtensions && getSourceFile(fileName);
106507                 if (sourceFileNoExtension)
106508                     return sourceFileNoExtension;
106509                 if (fail && options.allowNonTsExtensions) {
106510                     fail(ts.Diagnostics.File_0_not_found, fileName);
106511                     return undefined;
106512                 }
106513                 var sourceFileWithAddedExtension = ts.forEach(supportedExtensions, function (extension) { return getSourceFile(fileName + extension); });
106514                 if (fail && !sourceFileWithAddedExtension)
106515                     fail(ts.Diagnostics.Could_not_resolve_the_path_0_with_the_extensions_Colon_1, fileName, "'" + supportedExtensions.join("', '") + "'");
106516                 return sourceFileWithAddedExtension;
106517             }
106518         }
106519         /** This has side effects through `findSourceFile`. */
106520         function processSourceFile(fileName, isDefaultLib, ignoreNoDefaultLib, packageId, refFile) {
106521             getSourceFileFromReferenceWorker(fileName, function (fileName) { return findSourceFile(fileName, toPath(fileName), isDefaultLib, ignoreNoDefaultLib, refFile, packageId); }, // TODO: GH#18217
106522             function (diagnostic) {
106523                 var args = [];
106524                 for (var _i = 1; _i < arguments.length; _i++) {
106525                     args[_i - 1] = arguments[_i];
106526                 }
106527                 return fileProcessingDiagnostics.add(createRefFileDiagnostic.apply(void 0, __spreadArrays([refFile, diagnostic], args)));
106528             }, refFile && refFile.file);
106529         }
106530         function reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile) {
106531             var refs = !refFile ? refFileMap && refFileMap.get(existingFile.path) : undefined;
106532             var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile.fileName; });
106533             fileProcessingDiagnostics.add(refToReportErrorOn ?
106534                 createFileDiagnosticAtReference(refToReportErrorOn, ts.Diagnostics.Already_included_file_name_0_differs_from_file_name_1_only_in_casing, existingFile.fileName, fileName) :
106535                 createRefFileDiagnostic(refFile, ts.Diagnostics.File_name_0_differs_from_already_included_file_name_1_only_in_casing, fileName, existingFile.fileName));
106536         }
106537         function createRedirectSourceFile(redirectTarget, unredirected, fileName, path, resolvedPath, originalFileName) {
106538             var redirect = Object.create(redirectTarget);
106539             redirect.fileName = fileName;
106540             redirect.path = path;
106541             redirect.resolvedPath = resolvedPath;
106542             redirect.originalFileName = originalFileName;
106543             redirect.redirectInfo = { redirectTarget: redirectTarget, unredirected: unredirected };
106544             sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
106545             Object.defineProperties(redirect, {
106546                 id: {
106547                     get: function () { return this.redirectInfo.redirectTarget.id; },
106548                     set: function (value) { this.redirectInfo.redirectTarget.id = value; },
106549                 },
106550                 symbol: {
106551                     get: function () { return this.redirectInfo.redirectTarget.symbol; },
106552                     set: function (value) { this.redirectInfo.redirectTarget.symbol = value; },
106553                 },
106554             });
106555             return redirect;
106556         }
106557         // Get source file from normalized fileName
106558         function findSourceFile(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
106559             ts.tracing.push("program" /* Program */, "findSourceFile", {
106560                 fileName: fileName,
106561                 isDefaultLib: isDefaultLib || undefined,
106562                 refKind: refFile ? ts.RefFileKind[refFile.kind] : undefined,
106563             });
106564             var result = findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId);
106565             ts.tracing.pop();
106566             return result;
106567         }
106568         function findSourceFileWorker(fileName, path, isDefaultLib, ignoreNoDefaultLib, refFile, packageId) {
106569             if (useSourceOfProjectReferenceRedirect) {
106570                 var source = getSourceOfProjectReferenceRedirect(fileName);
106571                 // If preserveSymlinks is true, module resolution wont jump the symlink
106572                 // but the resolved real path may be the .d.ts from project reference
106573                 // Note:: Currently we try the real path only if the
106574                 // file is from node_modules to avoid having to run real path on all file paths
106575                 if (!source &&
106576                     host.realpath &&
106577                     options.preserveSymlinks &&
106578                     ts.isDeclarationFileName(fileName) &&
106579                     ts.stringContains(fileName, ts.nodeModulesPathPart)) {
106580                     var realPath = host.realpath(fileName);
106581                     if (realPath !== fileName)
106582                         source = getSourceOfProjectReferenceRedirect(realPath);
106583                 }
106584                 if (source) {
106585                     var file_1 = ts.isString(source) ?
106586                         findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
106587                         undefined;
106588                     if (file_1)
106589                         addFileToFilesByName(file_1, path, /*redirectedPath*/ undefined);
106590                     return file_1;
106591                 }
106592             }
106593             var originalFileName = fileName;
106594             if (filesByName.has(path)) {
106595                 var file_2 = filesByName.get(path);
106596                 addFileToRefFileMap(fileName, file_2 || undefined, refFile);
106597                 // try to check if we've already seen this file but with a different casing in path
106598                 // NOTE: this only makes sense for case-insensitive file systems, and only on files which are not redirected
106599                 if (file_2 && options.forceConsistentCasingInFileNames) {
106600                     var checkedName = file_2.fileName;
106601                     var isRedirect = toPath(checkedName) !== toPath(fileName);
106602                     if (isRedirect) {
106603                         fileName = getProjectReferenceRedirect(fileName) || fileName;
106604                     }
106605                     // Check if it differs only in drive letters its ok to ignore that error:
106606                     var checkedAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(checkedName, currentDirectory);
106607                     var inputAbsolutePath = ts.getNormalizedAbsolutePathWithoutRoot(fileName, currentDirectory);
106608                     if (checkedAbsolutePath !== inputAbsolutePath) {
106609                         reportFileNamesDifferOnlyInCasingError(fileName, file_2, refFile);
106610                     }
106611                 }
106612                 // If the file was previously found via a node_modules search, but is now being processed as a root file,
106613                 // then everything it sucks in may also be marked incorrectly, and needs to be checked again.
106614                 if (file_2 && sourceFilesFoundSearchingNodeModules.get(file_2.path) && currentNodeModulesDepth === 0) {
106615                     sourceFilesFoundSearchingNodeModules.set(file_2.path, false);
106616                     if (!options.noResolve) {
106617                         processReferencedFiles(file_2, isDefaultLib);
106618                         processTypeReferenceDirectives(file_2);
106619                     }
106620                     if (!options.noLib) {
106621                         processLibReferenceDirectives(file_2);
106622                     }
106623                     modulesWithElidedImports.set(file_2.path, false);
106624                     processImportedModules(file_2);
106625                 }
106626                 // See if we need to reprocess the imports due to prior skipped imports
106627                 else if (file_2 && modulesWithElidedImports.get(file_2.path)) {
106628                     if (currentNodeModulesDepth < maxNodeModuleJsDepth) {
106629                         modulesWithElidedImports.set(file_2.path, false);
106630                         processImportedModules(file_2);
106631                     }
106632                 }
106633                 return file_2 || undefined;
106634             }
106635             var redirectedPath;
106636             if (refFile && !useSourceOfProjectReferenceRedirect) {
106637                 var redirectProject = getProjectReferenceRedirectProject(fileName);
106638                 if (redirectProject) {
106639                     if (ts.outFile(redirectProject.commandLine.options)) {
106640                         // Shouldnt create many to 1 mapping file in --out scenario
106641                         return undefined;
106642                     }
106643                     var redirect = getProjectReferenceOutputName(redirectProject, fileName);
106644                     fileName = redirect;
106645                     // Once we start redirecting to a file, we can potentially come back to it
106646                     // via a back-reference from another file in the .d.ts folder. If that happens we'll
106647                     // end up trying to add it to the program *again* because we were tracking it via its
106648                     // original (un-redirected) name. So we have to map both the original path and the redirected path
106649                     // to the source file we're about to find/create
106650                     redirectedPath = toPath(redirect);
106651                 }
106652             }
106653             // We haven't looked for this file, do so now and cache result
106654             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);
106655             if (packageId) {
106656                 var packageIdKey = ts.packageIdToString(packageId);
106657                 var fileFromPackageId = packageIdToSourceFile.get(packageIdKey);
106658                 if (fileFromPackageId) {
106659                     // Some other SourceFile already exists with this package name and version.
106660                     // Instead of creating a duplicate, just redirect to the existing one.
106661                     var dupFile = createRedirectSourceFile(fileFromPackageId, file, fileName, path, toPath(fileName), originalFileName); // TODO: GH#18217
106662                     redirectTargetsMap.add(fileFromPackageId.path, fileName);
106663                     addFileToFilesByName(dupFile, path, redirectedPath);
106664                     sourceFileToPackageName.set(path, packageId.name);
106665                     processingOtherFiles.push(dupFile);
106666                     return dupFile;
106667                 }
106668                 else if (file) {
106669                     // This is the first source file to have this packageId.
106670                     packageIdToSourceFile.set(packageIdKey, file);
106671                     sourceFileToPackageName.set(path, packageId.name);
106672                 }
106673             }
106674             addFileToFilesByName(file, path, redirectedPath);
106675             if (file) {
106676                 sourceFilesFoundSearchingNodeModules.set(path, currentNodeModulesDepth > 0);
106677                 file.fileName = fileName; // Ensure that source file has same name as what we were looking for
106678                 file.path = path;
106679                 file.resolvedPath = toPath(fileName);
106680                 file.originalFileName = originalFileName;
106681                 addFileToRefFileMap(fileName, file, refFile);
106682                 if (host.useCaseSensitiveFileNames()) {
106683                     var pathLowerCase = ts.toFileNameLowerCase(path);
106684                     // for case-sensitive file systems check if we've already seen some file with similar filename ignoring case
106685                     var existingFile = filesByNameIgnoreCase.get(pathLowerCase);
106686                     if (existingFile) {
106687                         reportFileNamesDifferOnlyInCasingError(fileName, existingFile, refFile);
106688                     }
106689                     else {
106690                         filesByNameIgnoreCase.set(pathLowerCase, file);
106691                     }
106692                 }
106693                 skipDefaultLib = skipDefaultLib || (file.hasNoDefaultLib && !ignoreNoDefaultLib);
106694                 if (!options.noResolve) {
106695                     processReferencedFiles(file, isDefaultLib);
106696                     processTypeReferenceDirectives(file);
106697                 }
106698                 if (!options.noLib) {
106699                     processLibReferenceDirectives(file);
106700                 }
106701                 // always process imported modules to record module name resolutions
106702                 processImportedModules(file);
106703                 if (isDefaultLib) {
106704                     processingDefaultLibFiles.push(file);
106705                 }
106706                 else {
106707                     processingOtherFiles.push(file);
106708                 }
106709             }
106710             return file;
106711         }
106712         function addFileToRefFileMap(referencedFileName, file, refFile) {
106713             if (refFile && file) {
106714                 (refFileMap || (refFileMap = ts.createMultiMap())).add(file.path, {
106715                     referencedFileName: referencedFileName,
106716                     kind: refFile.kind,
106717                     index: refFile.index,
106718                     file: refFile.file.path
106719                 });
106720             }
106721         }
106722         function addFileToFilesByName(file, path, redirectedPath) {
106723             if (redirectedPath) {
106724                 filesByName.set(redirectedPath, file);
106725                 filesByName.set(path, file || false);
106726             }
106727             else {
106728                 filesByName.set(path, file);
106729             }
106730         }
106731         function getProjectReferenceRedirect(fileName) {
106732             var referencedProject = getProjectReferenceRedirectProject(fileName);
106733             return referencedProject && getProjectReferenceOutputName(referencedProject, fileName);
106734         }
106735         function getProjectReferenceRedirectProject(fileName) {
106736             // Ignore dts or any json files
106737             if (!resolvedProjectReferences || !resolvedProjectReferences.length || ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) || ts.fileExtensionIs(fileName, ".json" /* Json */)) {
106738                 return undefined;
106739             }
106740             // If this file is produced by a referenced project, we need to rewrite it to
106741             // look in the output folder of the referenced project rather than the input
106742             return getResolvedProjectReferenceToRedirect(fileName);
106743         }
106744         function getProjectReferenceOutputName(referencedProject, fileName) {
106745             var out = ts.outFile(referencedProject.commandLine.options);
106746             return out ?
106747                 ts.changeExtension(out, ".d.ts" /* Dts */) :
106748                 ts.getOutputDeclarationFileName(fileName, referencedProject.commandLine, !host.useCaseSensitiveFileNames());
106749         }
106750         /**
106751          * Get the referenced project if the file is input file from that reference project
106752          */
106753         function getResolvedProjectReferenceToRedirect(fileName) {
106754             if (mapFromFileToProjectReferenceRedirects === undefined) {
106755                 mapFromFileToProjectReferenceRedirects = new ts.Map();
106756                 forEachResolvedProjectReference(function (referencedProject) {
106757                     // not input file from the referenced project, ignore
106758                     if (toPath(options.configFilePath) !== referencedProject.sourceFile.path) {
106759                         referencedProject.commandLine.fileNames.forEach(function (f) {
106760                             return mapFromFileToProjectReferenceRedirects.set(toPath(f), referencedProject.sourceFile.path);
106761                         });
106762                     }
106763                 });
106764             }
106765             var referencedProjectPath = mapFromFileToProjectReferenceRedirects.get(toPath(fileName));
106766             return referencedProjectPath && getResolvedProjectReferenceByPath(referencedProjectPath);
106767         }
106768         function forEachResolvedProjectReference(cb) {
106769             return ts.forEachResolvedProjectReference(resolvedProjectReferences, cb);
106770         }
106771         function getSourceOfProjectReferenceRedirect(file) {
106772             if (!ts.isDeclarationFileName(file))
106773                 return undefined;
106774             if (mapFromToProjectReferenceRedirectSource === undefined) {
106775                 mapFromToProjectReferenceRedirectSource = new ts.Map();
106776                 forEachResolvedProjectReference(function (resolvedRef) {
106777                     var out = ts.outFile(resolvedRef.commandLine.options);
106778                     if (out) {
106779                         // Dont know which source file it means so return true?
106780                         var outputDts = ts.changeExtension(out, ".d.ts" /* Dts */);
106781                         mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), true);
106782                     }
106783                     else {
106784                         ts.forEach(resolvedRef.commandLine.fileNames, function (fileName) {
106785                             if (!ts.fileExtensionIs(fileName, ".d.ts" /* Dts */) && !ts.fileExtensionIs(fileName, ".json" /* Json */)) {
106786                                 var outputDts = ts.getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
106787                                 mapFromToProjectReferenceRedirectSource.set(toPath(outputDts), fileName);
106788                             }
106789                         });
106790                     }
106791                 });
106792             }
106793             return mapFromToProjectReferenceRedirectSource.get(toPath(file));
106794         }
106795         function isSourceOfProjectReferenceRedirect(fileName) {
106796             return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
106797         }
106798         function getResolvedProjectReferenceByPath(projectReferencePath) {
106799             if (!projectReferenceRedirects) {
106800                 return undefined;
106801             }
106802             return projectReferenceRedirects.get(projectReferencePath) || undefined;
106803         }
106804         function processReferencedFiles(file, isDefaultLib) {
106805             ts.forEach(file.referencedFiles, function (ref, index) {
106806                 var referencedFileName = resolveTripleslashReference(ref.fileName, file.fileName);
106807                 processSourceFile(referencedFileName, isDefaultLib, 
106808                 /*ignoreNoDefaultLib*/ false, 
106809                 /*packageId*/ undefined, {
106810                     kind: ts.RefFileKind.ReferenceFile,
106811                     index: index,
106812                     file: file,
106813                     pos: ref.pos,
106814                     end: ref.end
106815                 });
106816             });
106817         }
106818         function processTypeReferenceDirectives(file) {
106819             // We lower-case all type references because npm automatically lowercases all packages. See GH#9824.
106820             var typeDirectives = ts.map(file.typeReferenceDirectives, function (ref) { return ts.toFileNameLowerCase(ref.fileName); });
106821             if (!typeDirectives) {
106822                 return;
106823             }
106824             var resolutions = resolveTypeReferenceDirectiveNamesWorker(typeDirectives, file);
106825             for (var i = 0; i < typeDirectives.length; i++) {
106826                 var ref = file.typeReferenceDirectives[i];
106827                 var resolvedTypeReferenceDirective = resolutions[i];
106828                 // store resolved type directive on the file
106829                 var fileName = ts.toFileNameLowerCase(ref.fileName);
106830                 ts.setResolvedTypeReferenceDirective(file, fileName, resolvedTypeReferenceDirective);
106831                 processTypeReferenceDirective(fileName, resolvedTypeReferenceDirective, {
106832                     kind: ts.RefFileKind.TypeReferenceDirective,
106833                     index: i,
106834                     file: file,
106835                     pos: ref.pos,
106836                     end: ref.end
106837                 });
106838             }
106839         }
106840         function processTypeReferenceDirective(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
106841             ts.tracing.push("program" /* Program */, "processTypeReferenceDirective", { directive: typeReferenceDirective, hasResolved: !!resolveModuleNamesReusingOldState, refKind: refFile === null || refFile === void 0 ? void 0 : refFile.kind, refPath: refFile === null || refFile === void 0 ? void 0 : refFile.file.path });
106842             processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, refFile);
106843             ts.tracing.pop();
106844         }
106845         function processTypeReferenceDirectiveWorker(typeReferenceDirective, resolvedTypeReferenceDirective, refFile) {
106846             // If we already found this library as a primary reference - nothing to do
106847             var previousResolution = resolvedTypeReferenceDirectives.get(typeReferenceDirective);
106848             if (previousResolution && previousResolution.primary) {
106849                 return;
106850             }
106851             var saveResolution = true;
106852             if (resolvedTypeReferenceDirective) {
106853                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
106854                     currentNodeModulesDepth++;
106855                 if (resolvedTypeReferenceDirective.primary) {
106856                     // resolved from the primary path
106857                     processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile); // TODO: GH#18217
106858                 }
106859                 else {
106860                     // If we already resolved to this file, it must have been a secondary reference. Check file contents
106861                     // for sameness and possibly issue an error
106862                     if (previousResolution) {
106863                         // Don't bother reading the file again if it's the same file.
106864                         if (resolvedTypeReferenceDirective.resolvedFileName !== previousResolution.resolvedFileName) {
106865                             var otherFileText = host.readFile(resolvedTypeReferenceDirective.resolvedFileName);
106866                             var existingFile_1 = getSourceFile(previousResolution.resolvedFileName);
106867                             if (otherFileText !== existingFile_1.text) {
106868                                 // Try looking up ref for original file
106869                                 var refs = !refFile ? refFileMap && refFileMap.get(existingFile_1.path) : undefined;
106870                                 var refToReportErrorOn = refs && ts.find(refs, function (ref) { return ref.referencedFileName === existingFile_1.fileName; });
106871                                 fileProcessingDiagnostics.add(refToReportErrorOn ?
106872                                     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) :
106873                                     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));
106874                             }
106875                         }
106876                         // don't overwrite previous resolution result
106877                         saveResolution = false;
106878                     }
106879                     else {
106880                         // First resolution of this library
106881                         processSourceFile(resolvedTypeReferenceDirective.resolvedFileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, resolvedTypeReferenceDirective.packageId, refFile);
106882                     }
106883                 }
106884                 if (resolvedTypeReferenceDirective.isExternalLibraryImport)
106885                     currentNodeModulesDepth--;
106886             }
106887             else {
106888                 fileProcessingDiagnostics.add(createRefFileDiagnostic(refFile, ts.Diagnostics.Cannot_find_type_definition_file_for_0, typeReferenceDirective));
106889             }
106890             if (saveResolution) {
106891                 resolvedTypeReferenceDirectives.set(typeReferenceDirective, resolvedTypeReferenceDirective);
106892             }
106893         }
106894         function processLibReferenceDirectives(file) {
106895             ts.forEach(file.libReferenceDirectives, function (libReference) {
106896                 var libName = ts.toFileNameLowerCase(libReference.fileName);
106897                 var libFileName = ts.libMap.get(libName);
106898                 if (libFileName) {
106899                     // we ignore any 'no-default-lib' reference set on this file.
106900                     processRootFile(ts.combinePaths(defaultLibraryPath, libFileName), /*isDefaultLib*/ true, /*ignoreNoDefaultLib*/ true);
106901                 }
106902                 else {
106903                     var unqualifiedLibName = ts.removeSuffix(ts.removePrefix(libName, "lib."), ".d.ts");
106904                     var suggestion = ts.getSpellingSuggestion(unqualifiedLibName, ts.libs, ts.identity);
106905                     var message = suggestion ? ts.Diagnostics.Cannot_find_lib_definition_for_0_Did_you_mean_1 : ts.Diagnostics.Cannot_find_lib_definition_for_0;
106906                     fileProcessingDiagnostics.add(ts.createFileDiagnostic(file, libReference.pos, libReference.end - libReference.pos, message, libName, suggestion));
106907                 }
106908             });
106909         }
106910         function createRefFileDiagnostic(refFile, message) {
106911             var args = [];
106912             for (var _i = 2; _i < arguments.length; _i++) {
106913                 args[_i - 2] = arguments[_i];
106914             }
106915             if (!refFile) {
106916                 return ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args));
106917             }
106918             else {
106919                 return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile.file, refFile.pos, refFile.end - refFile.pos, message], args));
106920             }
106921         }
106922         function getCanonicalFileName(fileName) {
106923             return host.getCanonicalFileName(fileName);
106924         }
106925         function processImportedModules(file) {
106926             collectExternalModuleReferences(file);
106927             if (file.imports.length || file.moduleAugmentations.length) {
106928                 // Because global augmentation doesn't have string literal name, we can check for global augmentation as such.
106929                 var moduleNames = getModuleNames(file);
106930                 var resolutions = resolveModuleNamesReusingOldState(moduleNames, file);
106931                 ts.Debug.assert(resolutions.length === moduleNames.length);
106932                 for (var i = 0; i < moduleNames.length; i++) {
106933                     var resolution = resolutions[i];
106934                     ts.setResolvedModule(file, moduleNames[i], resolution);
106935                     if (!resolution) {
106936                         continue;
106937                     }
106938                     var isFromNodeModulesSearch = resolution.isExternalLibraryImport;
106939                     var isJsFile = !ts.resolutionExtensionIsTSOrJson(resolution.extension);
106940                     var isJsFileFromNodeModules = isFromNodeModulesSearch && isJsFile;
106941                     var resolvedFileName = resolution.resolvedFileName;
106942                     if (isFromNodeModulesSearch) {
106943                         currentNodeModulesDepth++;
106944                     }
106945                     // add file to program only if:
106946                     // - resolution was successful
106947                     // - noResolve is falsy
106948                     // - module name comes from the list of imports
106949                     // - it's not a top level JavaScript module that exceeded the search max
106950                     var elideImport = isJsFileFromNodeModules && currentNodeModulesDepth > maxNodeModuleJsDepth;
106951                     // Don't add the file if it has a bad extension (e.g. 'tsx' if we don't have '--allowJs')
106952                     // This may still end up being an untyped module -- the file won't be included but imports will be allowed.
106953                     var shouldAddFile = resolvedFileName
106954                         && !getResolutionDiagnostic(options, resolution)
106955                         && !options.noResolve
106956                         && i < file.imports.length
106957                         && !elideImport
106958                         && !(isJsFile && !ts.getAllowJSCompilerOption(options))
106959                         && (ts.isInJSFile(file.imports[i]) || !(file.imports[i].flags & 4194304 /* JSDoc */));
106960                     if (elideImport) {
106961                         modulesWithElidedImports.set(file.path, true);
106962                     }
106963                     else if (shouldAddFile) {
106964                         var path = toPath(resolvedFileName);
106965                         var pos = ts.skipTrivia(file.text, file.imports[i].pos);
106966                         findSourceFile(resolvedFileName, path, 
106967                         /*isDefaultLib*/ false, 
106968                         /*ignoreNoDefaultLib*/ false, {
106969                             kind: ts.RefFileKind.Import,
106970                             index: i,
106971                             file: file,
106972                             pos: pos,
106973                             end: file.imports[i].end
106974                         }, resolution.packageId);
106975                     }
106976                     if (isFromNodeModulesSearch) {
106977                         currentNodeModulesDepth--;
106978                     }
106979                 }
106980             }
106981             else {
106982                 // no imports - drop cached module resolutions
106983                 file.resolvedModules = undefined;
106984             }
106985         }
106986         function computeCommonSourceDirectory(sourceFiles) {
106987             var fileNames = ts.mapDefined(sourceFiles, function (file) { return file.isDeclarationFile ? undefined : file.fileName; });
106988             return computeCommonSourceDirectoryOfFilenames(fileNames, currentDirectory, getCanonicalFileName);
106989         }
106990         function checkSourceFilesBelongToPath(sourceFiles, rootDirectory) {
106991             var allFilesBelongToPath = true;
106992             var absoluteRootDirectoryPath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(rootDirectory, currentDirectory));
106993             var rootPaths;
106994             for (var _i = 0, sourceFiles_2 = sourceFiles; _i < sourceFiles_2.length; _i++) {
106995                 var sourceFile = sourceFiles_2[_i];
106996                 if (!sourceFile.isDeclarationFile) {
106997                     var absoluteSourceFilePath = host.getCanonicalFileName(ts.getNormalizedAbsolutePath(sourceFile.fileName, currentDirectory));
106998                     if (absoluteSourceFilePath.indexOf(absoluteRootDirectoryPath) !== 0) {
106999                         if (!rootPaths)
107000                             rootPaths = new ts.Set(rootNames.map(toPath));
107001                         addProgramDiagnosticAtRefPath(sourceFile, rootPaths, ts.Diagnostics.File_0_is_not_under_rootDir_1_rootDir_is_expected_to_contain_all_source_files, sourceFile.fileName, rootDirectory);
107002                         allFilesBelongToPath = false;
107003                     }
107004                 }
107005             }
107006             return allFilesBelongToPath;
107007         }
107008         function parseProjectReferenceConfigFile(ref) {
107009             if (!projectReferenceRedirects) {
107010                 projectReferenceRedirects = new ts.Map();
107011             }
107012             // The actual filename (i.e. add "/tsconfig.json" if necessary)
107013             var refPath = resolveProjectReferencePath(ref);
107014             var sourceFilePath = toPath(refPath);
107015             var fromCache = projectReferenceRedirects.get(sourceFilePath);
107016             if (fromCache !== undefined) {
107017                 return fromCache || undefined;
107018             }
107019             var commandLine;
107020             var sourceFile;
107021             if (host.getParsedCommandLine) {
107022                 commandLine = host.getParsedCommandLine(refPath);
107023                 if (!commandLine) {
107024                     addFileToFilesByName(/*sourceFile*/ undefined, sourceFilePath, /*redirectedPath*/ undefined);
107025                     projectReferenceRedirects.set(sourceFilePath, false);
107026                     return undefined;
107027                 }
107028                 sourceFile = ts.Debug.checkDefined(commandLine.options.configFile);
107029                 ts.Debug.assert(!sourceFile.path || sourceFile.path === sourceFilePath);
107030                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
107031             }
107032             else {
107033                 // An absolute path pointing to the containing directory of the config file
107034                 var basePath = ts.getNormalizedAbsolutePath(ts.getDirectoryPath(refPath), host.getCurrentDirectory());
107035                 sourceFile = host.getSourceFile(refPath, 100 /* JSON */);
107036                 addFileToFilesByName(sourceFile, sourceFilePath, /*redirectedPath*/ undefined);
107037                 if (sourceFile === undefined) {
107038                     projectReferenceRedirects.set(sourceFilePath, false);
107039                     return undefined;
107040                 }
107041                 commandLine = ts.parseJsonSourceFileConfigFileContent(sourceFile, configParsingHost, basePath, /*existingOptions*/ undefined, refPath);
107042             }
107043             sourceFile.fileName = refPath;
107044             sourceFile.path = sourceFilePath;
107045             sourceFile.resolvedPath = sourceFilePath;
107046             sourceFile.originalFileName = refPath;
107047             var resolvedRef = { commandLine: commandLine, sourceFile: sourceFile };
107048             projectReferenceRedirects.set(sourceFilePath, resolvedRef);
107049             if (commandLine.projectReferences) {
107050                 resolvedRef.references = commandLine.projectReferences.map(parseProjectReferenceConfigFile);
107051             }
107052             return resolvedRef;
107053         }
107054         function verifyCompilerOptions() {
107055             if (options.strictPropertyInitialization && !ts.getStrictOptionValue(options, "strictNullChecks")) {
107056                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "strictPropertyInitialization", "strictNullChecks");
107057             }
107058             if (options.isolatedModules) {
107059                 if (options.out) {
107060                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "isolatedModules");
107061                 }
107062                 if (options.outFile) {
107063                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "outFile", "isolatedModules");
107064                 }
107065             }
107066             if (options.inlineSourceMap) {
107067                 if (options.sourceMap) {
107068                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "sourceMap", "inlineSourceMap");
107069                 }
107070                 if (options.mapRoot) {
107071                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "mapRoot", "inlineSourceMap");
107072                 }
107073             }
107074             if (options.composite) {
107075                 if (options.declaration === false) {
107076                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_declaration_emit, "declaration");
107077                 }
107078                 if (options.incremental === false) {
107079                     createDiagnosticForOptionName(ts.Diagnostics.Composite_projects_may_not_disable_incremental_compilation, "declaration");
107080                 }
107081             }
107082             var outputFile = ts.outFile(options);
107083             if (options.tsBuildInfoFile) {
107084                 if (!ts.isIncrementalCompilation(options)) {
107085                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "tsBuildInfoFile", "incremental", "composite");
107086                 }
107087             }
107088             else if (options.incremental && !outputFile && !options.configFilePath) {
107089                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_incremental_can_only_be_specified_using_tsconfig_emitting_to_single_file_or_when_option_tsBuildInfoFile_is_specified));
107090             }
107091             verifyProjectReferences();
107092             // List of collected files is complete; validate exhautiveness if this is a project with a file list
107093             if (options.composite) {
107094                 var rootPaths = new ts.Set(rootNames.map(toPath));
107095                 for (var _i = 0, files_3 = files; _i < files_3.length; _i++) {
107096                     var file = files_3[_i];
107097                     // Ignore file that is not emitted
107098                     if (ts.sourceFileMayBeEmitted(file, program) && !rootPaths.has(file.path)) {
107099                         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 || "");
107100                     }
107101                 }
107102             }
107103             if (options.paths) {
107104                 for (var key in options.paths) {
107105                     if (!ts.hasProperty(options.paths, key)) {
107106                         continue;
107107                     }
107108                     if (!ts.hasZeroOrOneAsteriskCharacter(key)) {
107109                         createDiagnosticForOptionPaths(/*onKey*/ true, key, ts.Diagnostics.Pattern_0_can_have_at_most_one_Asterisk_character, key);
107110                     }
107111                     if (ts.isArray(options.paths[key])) {
107112                         var len = options.paths[key].length;
107113                         if (len === 0) {
107114                             createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_shouldn_t_be_an_empty_array, key);
107115                         }
107116                         for (var i = 0; i < len; i++) {
107117                             var subst = options.paths[key][i];
107118                             var typeOfSubst = typeof subst;
107119                             if (typeOfSubst === "string") {
107120                                 if (!ts.hasZeroOrOneAsteriskCharacter(subst)) {
107121                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_in_pattern_1_can_have_at_most_one_Asterisk_character, subst, key);
107122                                 }
107123                                 if (!options.baseUrl && !ts.pathIsRelative(subst) && !ts.pathIsAbsolute(subst)) {
107124                                     createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Non_relative_paths_are_not_allowed_when_baseUrl_is_not_set_Did_you_forget_a_leading_Slash);
107125                                 }
107126                             }
107127                             else {
107128                                 createDiagnosticForOptionPathKeyValue(key, i, ts.Diagnostics.Substitution_0_for_pattern_1_has_incorrect_type_expected_string_got_2, subst, key, typeOfSubst);
107129                             }
107130                         }
107131                     }
107132                     else {
107133                         createDiagnosticForOptionPaths(/*onKey*/ false, key, ts.Diagnostics.Substitutions_for_pattern_0_should_be_an_array, key);
107134                     }
107135                 }
107136             }
107137             if (!options.sourceMap && !options.inlineSourceMap) {
107138                 if (options.inlineSources) {
107139                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "inlineSources");
107140                 }
107141                 if (options.sourceRoot) {
107142                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_can_only_be_used_when_either_option_inlineSourceMap_or_option_sourceMap_is_provided, "sourceRoot");
107143                 }
107144             }
107145             if (options.out && options.outFile) {
107146                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "out", "outFile");
107147             }
107148             if (options.mapRoot && !(options.sourceMap || options.declarationMap)) {
107149                 // Error to specify --mapRoot without --sourcemap
107150                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "mapRoot", "sourceMap", "declarationMap");
107151             }
107152             if (options.declarationDir) {
107153                 if (!ts.getEmitDeclarations(options)) {
107154                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationDir", "declaration", "composite");
107155                 }
107156                 if (outputFile) {
107157                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "declarationDir", options.out ? "out" : "outFile");
107158                 }
107159             }
107160             if (options.declarationMap && !ts.getEmitDeclarations(options)) {
107161                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "declarationMap", "declaration", "composite");
107162             }
107163             if (options.lib && options.noLib) {
107164                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "lib", "noLib");
107165             }
107166             if (options.noImplicitUseStrict && ts.getStrictOptionValue(options, "alwaysStrict")) {
107167                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "noImplicitUseStrict", "alwaysStrict");
107168             }
107169             var languageVersion = options.target || 0 /* ES3 */;
107170             var firstNonAmbientExternalModuleSourceFile = ts.find(files, function (f) { return ts.isExternalModule(f) && !f.isDeclarationFile; });
107171             if (options.isolatedModules) {
107172                 if (options.module === ts.ModuleKind.None && languageVersion < 2 /* ES2015 */) {
107173                     createDiagnosticForOptionName(ts.Diagnostics.Option_isolatedModules_can_only_be_used_when_either_option_module_is_provided_or_option_target_is_ES2015_or_higher, "isolatedModules", "target");
107174                 }
107175                 var firstNonExternalModuleSourceFile = ts.find(files, function (f) { return !ts.isExternalModule(f) && !ts.isSourceFileJS(f) && !f.isDeclarationFile && f.scriptKind !== 6 /* JSON */; });
107176                 if (firstNonExternalModuleSourceFile) {
107177                     var span = ts.getErrorSpanForNode(firstNonExternalModuleSourceFile, firstNonExternalModuleSourceFile);
107178                     programDiagnostics.add(ts.createFileDiagnostic(firstNonExternalModuleSourceFile, span.start, span.length, ts.Diagnostics._0_cannot_be_compiled_under_isolatedModules_because_it_is_considered_a_global_script_file_Add_an_import_export_or_an_empty_export_statement_to_make_it_a_module, ts.getBaseFileName(firstNonExternalModuleSourceFile.fileName)));
107179                 }
107180             }
107181             else if (firstNonAmbientExternalModuleSourceFile && languageVersion < 2 /* ES2015 */ && options.module === ts.ModuleKind.None) {
107182                 // We cannot use createDiagnosticFromNode because nodes do not have parents yet
107183                 var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
107184                 programDiagnostics.add(ts.createFileDiagnostic(firstNonAmbientExternalModuleSourceFile, span.start, span.length, ts.Diagnostics.Cannot_use_imports_exports_or_module_augmentations_when_module_is_none));
107185             }
107186             // Cannot specify module gen that isn't amd or system with --out
107187             if (outputFile && !options.emitDeclarationOnly) {
107188                 if (options.module && !(options.module === ts.ModuleKind.AMD || options.module === ts.ModuleKind.System)) {
107189                     createDiagnosticForOptionName(ts.Diagnostics.Only_amd_and_system_modules_are_supported_alongside_0, options.out ? "out" : "outFile", "module");
107190                 }
107191                 else if (options.module === undefined && firstNonAmbientExternalModuleSourceFile) {
107192                     var span = ts.getErrorSpanForNode(firstNonAmbientExternalModuleSourceFile, firstNonAmbientExternalModuleSourceFile.externalModuleIndicator);
107193                     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"));
107194                 }
107195             }
107196             if (options.resolveJsonModule) {
107197                 if (ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs) {
107198                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_cannot_be_specified_without_node_module_resolution_strategy, "resolveJsonModule");
107199                 }
107200                 // Any emit other than common js, amd, es2015 or esnext is error
107201                 else if (!ts.hasJsonModuleEmitEnabled(options)) {
107202                     createDiagnosticForOptionName(ts.Diagnostics.Option_resolveJsonModule_can_only_be_specified_when_module_code_generation_is_commonjs_amd_es2015_or_esNext, "resolveJsonModule", "module");
107203                 }
107204             }
107205             // there has to be common source directory if user specified --outdir || --sourceRoot
107206             // if user specified --mapRoot, there needs to be common source directory if there would be multiple files being emitted
107207             if (options.outDir || // there is --outDir specified
107208                 options.sourceRoot || // there is --sourceRoot specified
107209                 options.mapRoot) { // there is --mapRoot specified
107210                 // Precalculate and cache the common source directory
107211                 var dir = getCommonSourceDirectory();
107212                 // 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
107213                 if (options.outDir && dir === "" && files.some(function (file) { return ts.getRootLength(file.fileName) > 1; })) {
107214                     createDiagnosticForOptionName(ts.Diagnostics.Cannot_find_the_common_subdirectory_path_for_the_input_files, "outDir");
107215                 }
107216             }
107217             if (options.useDefineForClassFields && languageVersion === 0 /* ES3 */) {
107218                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_target_is_ES3, "useDefineForClassFields");
107219             }
107220             if (options.checkJs && !ts.getAllowJSCompilerOption(options)) {
107221                 programDiagnostics.add(ts.createCompilerDiagnostic(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "checkJs", "allowJs"));
107222             }
107223             if (options.emitDeclarationOnly) {
107224                 if (!ts.getEmitDeclarations(options)) {
107225                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1_or_option_2, "emitDeclarationOnly", "declaration", "composite");
107226                 }
107227                 if (options.noEmit) {
107228                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "emitDeclarationOnly", "noEmit");
107229                 }
107230             }
107231             if (options.emitDecoratorMetadata &&
107232                 !options.experimentalDecorators) {
107233                 createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "emitDecoratorMetadata", "experimentalDecorators");
107234             }
107235             if (options.jsxFactory) {
107236                 if (options.reactNamespace) {
107237                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_with_option_1, "reactNamespace", "jsxFactory");
107238                 }
107239                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
107240                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFactory", ts.inverseJsxOptionMap.get("" + options.jsx));
107241                 }
107242                 if (!ts.parseIsolatedEntityName(options.jsxFactory, languageVersion)) {
107243                     createOptionValueDiagnostic("jsxFactory", ts.Diagnostics.Invalid_value_for_jsxFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFactory);
107244                 }
107245             }
107246             else if (options.reactNamespace && !ts.isIdentifierText(options.reactNamespace, languageVersion)) {
107247                 createOptionValueDiagnostic("reactNamespace", ts.Diagnostics.Invalid_value_for_reactNamespace_0_is_not_a_valid_identifier, options.reactNamespace);
107248             }
107249             if (options.jsxFragmentFactory) {
107250                 if (!options.jsxFactory) {
107251                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_without_specifying_option_1, "jsxFragmentFactory", "jsxFactory");
107252                 }
107253                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
107254                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxFragmentFactory", ts.inverseJsxOptionMap.get("" + options.jsx));
107255                 }
107256                 if (!ts.parseIsolatedEntityName(options.jsxFragmentFactory, languageVersion)) {
107257                     createOptionValueDiagnostic("jsxFragmentFactory", ts.Diagnostics.Invalid_value_for_jsxFragmentFactory_0_is_not_a_valid_identifier_or_qualified_name, options.jsxFragmentFactory);
107258                 }
107259             }
107260             if (options.reactNamespace) {
107261                 if (options.jsx === 4 /* ReactJSX */ || options.jsx === 5 /* ReactJSXDev */) {
107262                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "reactNamespace", ts.inverseJsxOptionMap.get("" + options.jsx));
107263                 }
107264             }
107265             if (options.jsxImportSource) {
107266                 if (options.jsx === 2 /* React */) {
107267                     createDiagnosticForOptionName(ts.Diagnostics.Option_0_cannot_be_specified_when_option_jsx_is_1, "jsxImportSource", ts.inverseJsxOptionMap.get("" + options.jsx));
107268                 }
107269             }
107270             // If the emit is enabled make sure that every output file is unique and not overwriting any of the input files
107271             if (!options.noEmit && !options.suppressOutputPathCheck) {
107272                 var emitHost = getEmitHost();
107273                 var emitFilesSeen_1 = new ts.Set();
107274                 ts.forEachEmittedFile(emitHost, function (emitFileNames) {
107275                     if (!options.emitDeclarationOnly) {
107276                         verifyEmitFilePath(emitFileNames.jsFilePath, emitFilesSeen_1);
107277                     }
107278                     verifyEmitFilePath(emitFileNames.declarationFilePath, emitFilesSeen_1);
107279                 });
107280             }
107281             // Verify that all the emit files are unique and don't overwrite input files
107282             function verifyEmitFilePath(emitFileName, emitFilesSeen) {
107283                 if (emitFileName) {
107284                     var emitFilePath = toPath(emitFileName);
107285                     // Report error if the output overwrites input file
107286                     if (filesByName.has(emitFilePath)) {
107287                         var chain = void 0;
107288                         if (!options.configFilePath) {
107289                             // The program is from either an inferred project or an external project
107290                             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);
107291                         }
107292                         chain = ts.chainDiagnosticMessages(chain, ts.Diagnostics.Cannot_write_file_0_because_it_would_overwrite_input_file, emitFileName);
107293                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnosticFromMessageChain(chain));
107294                     }
107295                     var emitFileKey = !host.useCaseSensitiveFileNames() ? ts.toFileNameLowerCase(emitFilePath) : emitFilePath;
107296                     // Report error if multiple files write into same file
107297                     if (emitFilesSeen.has(emitFileKey)) {
107298                         // Already seen the same emit file - report error
107299                         blockEmittingOfFile(emitFileName, ts.createCompilerDiagnostic(ts.Diagnostics.Cannot_write_file_0_because_it_would_be_overwritten_by_multiple_input_files, emitFileName));
107300                     }
107301                     else {
107302                         emitFilesSeen.add(emitFileKey);
107303                     }
107304                 }
107305             }
107306         }
107307         function createFileDiagnosticAtReference(refPathToReportErrorOn, message) {
107308             var _a, _b;
107309             var args = [];
107310             for (var _i = 2; _i < arguments.length; _i++) {
107311                 args[_i - 2] = arguments[_i];
107312             }
107313             var refFile = ts.Debug.checkDefined(getSourceFileByPath(refPathToReportErrorOn.file));
107314             var kind = refPathToReportErrorOn.kind, index = refPathToReportErrorOn.index;
107315             var pos, end;
107316             switch (kind) {
107317                 case ts.RefFileKind.Import:
107318                     pos = ts.skipTrivia(refFile.text, refFile.imports[index].pos);
107319                     end = refFile.imports[index].end;
107320                     break;
107321                 case ts.RefFileKind.ReferenceFile:
107322                     (_a = refFile.referencedFiles[index], pos = _a.pos, end = _a.end);
107323                     break;
107324                 case ts.RefFileKind.TypeReferenceDirective:
107325                     (_b = refFile.typeReferenceDirectives[index], pos = _b.pos, end = _b.end);
107326                     break;
107327                 default:
107328                     return ts.Debug.assertNever(kind);
107329             }
107330             return ts.createFileDiagnostic.apply(void 0, __spreadArrays([refFile, pos, end - pos, message], args));
107331         }
107332         function addProgramDiagnosticAtRefPath(file, rootPaths, message) {
107333             var args = [];
107334             for (var _i = 3; _i < arguments.length; _i++) {
107335                 args[_i - 3] = arguments[_i];
107336             }
107337             var refPaths = refFileMap === null || refFileMap === void 0 ? void 0 : refFileMap.get(file.path);
107338             var refPathToReportErrorOn = ts.forEach(refPaths, function (refPath) { return rootPaths.has(refPath.file) ? refPath : undefined; }) ||
107339                 ts.elementAt(refPaths, 0);
107340             programDiagnostics.add(refPathToReportErrorOn ? createFileDiagnosticAtReference.apply(void 0, __spreadArrays([refPathToReportErrorOn, message], args)) : ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
107341         }
107342         function verifyProjectReferences() {
107343             var buildInfoPath = !options.suppressOutputPathCheck ? ts.getTsBuildInfoEmitOutputFilePath(options) : undefined;
107344             forEachProjectReference(projectReferences, resolvedProjectReferences, function (resolvedRef, parent, index) {
107345                 var ref = (parent ? parent.commandLine.projectReferences : projectReferences)[index];
107346                 var parentFile = parent && parent.sourceFile;
107347                 if (!resolvedRef) {
107348                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.File_0_not_found, ref.path);
107349                     return;
107350                 }
107351                 var options = resolvedRef.commandLine.options;
107352                 if (!options.composite || options.noEmit) {
107353                     // ok to not have composite if the current program is container only
107354                     var inputs = parent ? parent.commandLine.fileNames : rootNames;
107355                     if (inputs.length) {
107356                         if (!options.composite)
107357                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_must_have_setting_composite_Colon_true, ref.path);
107358                         if (options.noEmit)
107359                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Referenced_project_0_may_not_disable_emit, ref.path);
107360                     }
107361                 }
107362                 if (ref.prepend) {
107363                     var out = ts.outFile(options);
107364                     if (out) {
107365                         if (!host.fileExists(out)) {
107366                             createDiagnosticForReference(parentFile, index, ts.Diagnostics.Output_file_0_from_project_1_does_not_exist, out, ref.path);
107367                         }
107368                     }
107369                     else {
107370                         createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_prepend_project_0_because_it_does_not_have_outFile_set, ref.path);
107371                     }
107372                 }
107373                 if (!parent && buildInfoPath && buildInfoPath === ts.getTsBuildInfoEmitOutputFilePath(options)) {
107374                     createDiagnosticForReference(parentFile, index, ts.Diagnostics.Cannot_write_file_0_because_it_will_overwrite_tsbuildinfo_file_generated_by_referenced_project_1, buildInfoPath, ref.path);
107375                     hasEmitBlockingDiagnostics.set(toPath(buildInfoPath), true);
107376                 }
107377             });
107378         }
107379         function createDiagnosticForOptionPathKeyValue(key, valueIndex, message, arg0, arg1, arg2) {
107380             var needCompilerDiagnostic = true;
107381             var pathsSyntax = getOptionPathsSyntax();
107382             for (var _i = 0, pathsSyntax_1 = pathsSyntax; _i < pathsSyntax_1.length; _i++) {
107383                 var pathProp = pathsSyntax_1[_i];
107384                 if (ts.isObjectLiteralExpression(pathProp.initializer)) {
107385                     for (var _a = 0, _b = ts.getPropertyAssignment(pathProp.initializer, key); _a < _b.length; _a++) {
107386                         var keyProps = _b[_a];
107387                         var initializer = keyProps.initializer;
107388                         if (ts.isArrayLiteralExpression(initializer) && initializer.elements.length > valueIndex) {
107389                             programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, initializer.elements[valueIndex], message, arg0, arg1, arg2));
107390                             needCompilerDiagnostic = false;
107391                         }
107392                     }
107393                 }
107394             }
107395             if (needCompilerDiagnostic) {
107396                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
107397             }
107398         }
107399         function createDiagnosticForOptionPaths(onKey, key, message, arg0) {
107400             var needCompilerDiagnostic = true;
107401             var pathsSyntax = getOptionPathsSyntax();
107402             for (var _i = 0, pathsSyntax_2 = pathsSyntax; _i < pathsSyntax_2.length; _i++) {
107403                 var pathProp = pathsSyntax_2[_i];
107404                 if (ts.isObjectLiteralExpression(pathProp.initializer) &&
107405                     createOptionDiagnosticInObjectLiteralSyntax(pathProp.initializer, onKey, key, /*key2*/ undefined, message, arg0)) {
107406                     needCompilerDiagnostic = false;
107407                 }
107408             }
107409             if (needCompilerDiagnostic) {
107410                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0));
107411             }
107412         }
107413         function getOptionsSyntaxByName(name) {
107414             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
107415             if (compilerOptionsObjectLiteralSyntax) {
107416                 return ts.getPropertyAssignment(compilerOptionsObjectLiteralSyntax, name);
107417             }
107418             return undefined;
107419         }
107420         function getOptionPathsSyntax() {
107421             return getOptionsSyntaxByName("paths") || ts.emptyArray;
107422         }
107423         function createDiagnosticForOptionName(message, option1, option2, option3) {
107424             createDiagnosticForOption(/*onKey*/ true, option1, option2, message, option1, option2, option3);
107425         }
107426         function createOptionValueDiagnostic(option1, message, arg0) {
107427             createDiagnosticForOption(/*onKey*/ false, option1, /*option2*/ undefined, message, arg0);
107428         }
107429         function createDiagnosticForReference(sourceFile, index, message, arg0, arg1) {
107430             var referencesSyntax = ts.firstDefined(ts.getTsConfigPropArray(sourceFile || options.configFile, "references"), function (property) { return ts.isArrayLiteralExpression(property.initializer) ? property.initializer : undefined; });
107431             if (referencesSyntax && referencesSyntax.elements.length > index) {
107432                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(sourceFile || options.configFile, referencesSyntax.elements[index], message, arg0, arg1));
107433             }
107434             else {
107435                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1));
107436             }
107437         }
107438         function createDiagnosticForOption(onKey, option1, option2, message, arg0, arg1, arg2) {
107439             var compilerOptionsObjectLiteralSyntax = getCompilerOptionsObjectLiteralSyntax();
107440             var needCompilerDiagnostic = !compilerOptionsObjectLiteralSyntax ||
107441                 !createOptionDiagnosticInObjectLiteralSyntax(compilerOptionsObjectLiteralSyntax, onKey, option1, option2, message, arg0, arg1, arg2);
107442             if (needCompilerDiagnostic) {
107443                 programDiagnostics.add(ts.createCompilerDiagnostic(message, arg0, arg1, arg2));
107444             }
107445         }
107446         function getCompilerOptionsObjectLiteralSyntax() {
107447             if (_compilerOptionsObjectLiteralSyntax === undefined) {
107448                 _compilerOptionsObjectLiteralSyntax = null; // eslint-disable-line no-null/no-null
107449                 var jsonObjectLiteral = ts.getTsConfigObjectLiteralExpression(options.configFile);
107450                 if (jsonObjectLiteral) {
107451                     for (var _i = 0, _a = ts.getPropertyAssignment(jsonObjectLiteral, "compilerOptions"); _i < _a.length; _i++) {
107452                         var prop = _a[_i];
107453                         if (ts.isObjectLiteralExpression(prop.initializer)) {
107454                             _compilerOptionsObjectLiteralSyntax = prop.initializer;
107455                             break;
107456                         }
107457                     }
107458                 }
107459             }
107460             return _compilerOptionsObjectLiteralSyntax;
107461         }
107462         function createOptionDiagnosticInObjectLiteralSyntax(objectLiteral, onKey, key1, key2, message, arg0, arg1, arg2) {
107463             var props = ts.getPropertyAssignment(objectLiteral, key1, key2);
107464             for (var _i = 0, props_3 = props; _i < props_3.length; _i++) {
107465                 var prop = props_3[_i];
107466                 programDiagnostics.add(ts.createDiagnosticForNodeInSourceFile(options.configFile, onKey ? prop.name : prop.initializer, message, arg0, arg1, arg2));
107467             }
107468             return !!props.length;
107469         }
107470         function blockEmittingOfFile(emitFileName, diag) {
107471             hasEmitBlockingDiagnostics.set(toPath(emitFileName), true);
107472             programDiagnostics.add(diag);
107473         }
107474         function isEmittedFile(file) {
107475             if (options.noEmit) {
107476                 return false;
107477             }
107478             // If this is source file, its not emitted file
107479             var filePath = toPath(file);
107480             if (getSourceFileByPath(filePath)) {
107481                 return false;
107482             }
107483             // If options have --outFile or --out just check that
107484             var out = ts.outFile(options);
107485             if (out) {
107486                 return isSameFile(filePath, out) || isSameFile(filePath, ts.removeFileExtension(out) + ".d.ts" /* Dts */);
107487             }
107488             // If declarationDir is specified, return if its a file in that directory
107489             if (options.declarationDir && ts.containsPath(options.declarationDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames())) {
107490                 return true;
107491             }
107492             // If --outDir, check if file is in that directory
107493             if (options.outDir) {
107494                 return ts.containsPath(options.outDir, filePath, currentDirectory, !host.useCaseSensitiveFileNames());
107495             }
107496             if (ts.fileExtensionIsOneOf(filePath, ts.supportedJSExtensions) || ts.fileExtensionIs(filePath, ".d.ts" /* Dts */)) {
107497                 // Otherwise just check if sourceFile with the name exists
107498                 var filePathWithoutExtension = ts.removeFileExtension(filePath);
107499                 return !!getSourceFileByPath((filePathWithoutExtension + ".ts" /* Ts */)) ||
107500                     !!getSourceFileByPath((filePathWithoutExtension + ".tsx" /* Tsx */));
107501             }
107502             return false;
107503         }
107504         function isSameFile(file1, file2) {
107505             return ts.comparePaths(file1, file2, currentDirectory, !host.useCaseSensitiveFileNames()) === 0 /* EqualTo */;
107506         }
107507         function getSymlinkCache() {
107508             if (host.getSymlinkCache) {
107509                 return host.getSymlinkCache();
107510             }
107511             return symlinks || (symlinks = ts.discoverProbableSymlinks(files, getCanonicalFileName, host.getCurrentDirectory()));
107512         }
107513     }
107514     ts.createProgram = createProgram;
107515     function updateHostForUseSourceOfProjectReferenceRedirect(host) {
107516         var setOfDeclarationDirectories;
107517         var originalFileExists = host.compilerHost.fileExists;
107518         var originalDirectoryExists = host.compilerHost.directoryExists;
107519         var originalGetDirectories = host.compilerHost.getDirectories;
107520         var originalRealpath = host.compilerHost.realpath;
107521         if (!host.useSourceOfProjectReferenceRedirect)
107522             return { onProgramCreateComplete: ts.noop, fileExists: fileExists };
107523         host.compilerHost.fileExists = fileExists;
107524         var directoryExists;
107525         if (originalDirectoryExists) {
107526             // This implementation of directoryExists checks if the directory being requested is
107527             // directory of .d.ts file for the referenced Project.
107528             // If it is it returns true irrespective of whether that directory exists on host
107529             directoryExists = host.compilerHost.directoryExists = function (path) {
107530                 if (originalDirectoryExists.call(host.compilerHost, path)) {
107531                     handleDirectoryCouldBeSymlink(path);
107532                     return true;
107533                 }
107534                 if (!host.getResolvedProjectReferences())
107535                     return false;
107536                 if (!setOfDeclarationDirectories) {
107537                     setOfDeclarationDirectories = new ts.Set();
107538                     host.forEachResolvedProjectReference(function (ref) {
107539                         var out = ts.outFile(ref.commandLine.options);
107540                         if (out) {
107541                             setOfDeclarationDirectories.add(ts.getDirectoryPath(host.toPath(out)));
107542                         }
107543                         else {
107544                             // Set declaration's in different locations only, if they are next to source the directory present doesnt change
107545                             var declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
107546                             if (declarationDir) {
107547                                 setOfDeclarationDirectories.add(host.toPath(declarationDir));
107548                             }
107549                         }
107550                     });
107551                 }
107552                 return fileOrDirectoryExistsUsingSource(path, /*isFile*/ false);
107553             };
107554         }
107555         if (originalGetDirectories) {
107556             // Call getDirectories only if directory actually present on the host
107557             // This is needed to ensure that we arent getting directories that we fake about presence for
107558             host.compilerHost.getDirectories = function (path) {
107559                 return !host.getResolvedProjectReferences() || (originalDirectoryExists && originalDirectoryExists.call(host.compilerHost, path)) ?
107560                     originalGetDirectories.call(host.compilerHost, path) :
107561                     [];
107562             };
107563         }
107564         // This is something we keep for life time of the host
107565         if (originalRealpath) {
107566             host.compilerHost.realpath = function (s) {
107567                 var _a;
107568                 return ((_a = host.getSymlinkCache().getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.get(host.toPath(s))) ||
107569                     originalRealpath.call(host.compilerHost, s);
107570             };
107571         }
107572         return { onProgramCreateComplete: onProgramCreateComplete, fileExists: fileExists, directoryExists: directoryExists };
107573         function onProgramCreateComplete() {
107574             host.compilerHost.fileExists = originalFileExists;
107575             host.compilerHost.directoryExists = originalDirectoryExists;
107576             host.compilerHost.getDirectories = originalGetDirectories;
107577             // DO not revert realpath as it could be used later
107578         }
107579         // This implementation of fileExists checks if the file being requested is
107580         // .d.ts file for the referenced Project.
107581         // If it is it returns true irrespective of whether that file exists on host
107582         function fileExists(file) {
107583             if (originalFileExists.call(host.compilerHost, file))
107584                 return true;
107585             if (!host.getResolvedProjectReferences())
107586                 return false;
107587             if (!ts.isDeclarationFileName(file))
107588                 return false;
107589             // Project references go to source file instead of .d.ts file
107590             return fileOrDirectoryExistsUsingSource(file, /*isFile*/ true);
107591         }
107592         function fileExistsIfProjectReferenceDts(file) {
107593             var source = host.getSourceOfProjectReferenceRedirect(file);
107594             return source !== undefined ?
107595                 ts.isString(source) ? originalFileExists.call(host.compilerHost, source) : true :
107596                 undefined;
107597         }
107598         function directoryExistsIfProjectReferenceDeclDir(dir) {
107599             var dirPath = host.toPath(dir);
107600             var dirPathWithTrailingDirectorySeparator = "" + dirPath + ts.directorySeparator;
107601             return ts.forEachKey(setOfDeclarationDirectories, function (declDirPath) { return dirPath === declDirPath ||
107602                 // Any parent directory of declaration dir
107603                 ts.startsWith(declDirPath, dirPathWithTrailingDirectorySeparator) ||
107604                 // Any directory inside declaration dir
107605                 ts.startsWith(dirPath, declDirPath + "/"); });
107606         }
107607         function handleDirectoryCouldBeSymlink(directory) {
107608             var _a;
107609             if (!host.getResolvedProjectReferences())
107610                 return;
107611             // Because we already watch node_modules, handle symlinks in there
107612             if (!originalRealpath || !ts.stringContains(directory, ts.nodeModulesPathPart))
107613                 return;
107614             var symlinkCache = host.getSymlinkCache();
107615             var directoryPath = ts.ensureTrailingDirectorySeparator(host.toPath(directory));
107616             if ((_a = symlinkCache.getSymlinkedDirectories()) === null || _a === void 0 ? void 0 : _a.has(directoryPath))
107617                 return;
107618             var real = ts.normalizePath(originalRealpath.call(host.compilerHost, directory));
107619             var realPath;
107620             if (real === directory ||
107621                 (realPath = ts.ensureTrailingDirectorySeparator(host.toPath(real))) === directoryPath) {
107622                 // not symlinked
107623                 symlinkCache.setSymlinkedDirectory(directoryPath, false);
107624                 return;
107625             }
107626             symlinkCache.setSymlinkedDirectory(directoryPath, {
107627                 real: ts.ensureTrailingDirectorySeparator(real),
107628                 realPath: realPath
107629             });
107630         }
107631         function fileOrDirectoryExistsUsingSource(fileOrDirectory, isFile) {
107632             var _a;
107633             var fileOrDirectoryExistsUsingSource = isFile ?
107634                 function (file) { return fileExistsIfProjectReferenceDts(file); } :
107635                 function (dir) { return directoryExistsIfProjectReferenceDeclDir(dir); };
107636             // Check current directory or file
107637             var result = fileOrDirectoryExistsUsingSource(fileOrDirectory);
107638             if (result !== undefined)
107639                 return result;
107640             var symlinkCache = host.getSymlinkCache();
107641             var symlinkedDirectories = symlinkCache.getSymlinkedDirectories();
107642             if (!symlinkedDirectories)
107643                 return false;
107644             var fileOrDirectoryPath = host.toPath(fileOrDirectory);
107645             if (!ts.stringContains(fileOrDirectoryPath, ts.nodeModulesPathPart))
107646                 return false;
107647             if (isFile && ((_a = symlinkCache.getSymlinkedFiles()) === null || _a === void 0 ? void 0 : _a.has(fileOrDirectoryPath)))
107648                 return true;
107649             // If it contains node_modules check if its one of the symlinked path we know of
107650             return ts.firstDefinedIterator(symlinkedDirectories.entries(), function (_a) {
107651                 var directoryPath = _a[0], symlinkedDirectory = _a[1];
107652                 if (!symlinkedDirectory || !ts.startsWith(fileOrDirectoryPath, directoryPath))
107653                     return undefined;
107654                 var result = fileOrDirectoryExistsUsingSource(fileOrDirectoryPath.replace(directoryPath, symlinkedDirectory.realPath));
107655                 if (isFile && result) {
107656                     // Store the real path for the file'
107657                     var absolutePath = ts.getNormalizedAbsolutePath(fileOrDirectory, host.compilerHost.getCurrentDirectory());
107658                     symlinkCache.setSymlinkedFile(fileOrDirectoryPath, "" + symlinkedDirectory.real + absolutePath.replace(new RegExp(directoryPath, "i"), ""));
107659                 }
107660                 return result;
107661             }) || false;
107662         }
107663     }
107664     /*@internal*/
107665     ts.emitSkippedWithNoDiagnostics = { diagnostics: ts.emptyArray, sourceMaps: undefined, emittedFiles: undefined, emitSkipped: true };
107666     /*@internal*/
107667     function handleNoEmitOptions(program, sourceFile, writeFile, cancellationToken) {
107668         var options = program.getCompilerOptions();
107669         if (options.noEmit) {
107670             // Cache the semantic diagnostics
107671             program.getSemanticDiagnostics(sourceFile, cancellationToken);
107672             return sourceFile || ts.outFile(options) ?
107673                 ts.emitSkippedWithNoDiagnostics :
107674                 program.emitBuildInfo(writeFile, cancellationToken);
107675         }
107676         // If the noEmitOnError flag is set, then check if we have any errors so far.  If so,
107677         // immediately bail out.  Note that we pass 'undefined' for 'sourceFile' so that we
107678         // get any preEmit diagnostics, not just the ones
107679         if (!options.noEmitOnError)
107680             return undefined;
107681         var diagnostics = __spreadArrays(program.getOptionsDiagnostics(cancellationToken), program.getSyntacticDiagnostics(sourceFile, cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSemanticDiagnostics(sourceFile, cancellationToken));
107682         if (diagnostics.length === 0 && ts.getEmitDeclarations(program.getCompilerOptions())) {
107683             diagnostics = program.getDeclarationDiagnostics(/*sourceFile*/ undefined, cancellationToken);
107684         }
107685         if (!diagnostics.length)
107686             return undefined;
107687         var emittedFiles;
107688         if (!sourceFile && !ts.outFile(options)) {
107689             var emitResult = program.emitBuildInfo(writeFile, cancellationToken);
107690             if (emitResult.diagnostics)
107691                 diagnostics = __spreadArrays(diagnostics, emitResult.diagnostics);
107692             emittedFiles = emitResult.emittedFiles;
107693         }
107694         return { diagnostics: diagnostics, sourceMaps: undefined, emittedFiles: emittedFiles, emitSkipped: true };
107695     }
107696     ts.handleNoEmitOptions = handleNoEmitOptions;
107697     /*@internal*/
107698     function filterSemanticDiagnotics(diagnostic, option) {
107699         return ts.filter(diagnostic, function (d) { return !d.skippedOn || !option[d.skippedOn]; });
107700     }
107701     ts.filterSemanticDiagnotics = filterSemanticDiagnotics;
107702     /* @internal */
107703     function parseConfigHostFromCompilerHostLike(host, directoryStructureHost) {
107704         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
107705         return {
107706             fileExists: function (f) { return directoryStructureHost.fileExists(f); },
107707             readDirectory: function (root, extensions, excludes, includes, depth) {
107708                 ts.Debug.assertIsDefined(directoryStructureHost.readDirectory, "'CompilerHost.readDirectory' must be implemented to correctly process 'projectReferences'");
107709                 return directoryStructureHost.readDirectory(root, extensions, excludes, includes, depth);
107710             },
107711             readFile: function (f) { return directoryStructureHost.readFile(f); },
107712             useCaseSensitiveFileNames: host.useCaseSensitiveFileNames(),
107713             getCurrentDirectory: function () { return host.getCurrentDirectory(); },
107714             onUnRecoverableConfigFileDiagnostic: host.onUnRecoverableConfigFileDiagnostic || ts.returnUndefined,
107715             trace: host.trace ? function (s) { return host.trace(s); } : undefined
107716         };
107717     }
107718     ts.parseConfigHostFromCompilerHostLike = parseConfigHostFromCompilerHostLike;
107719     /* @internal */
107720     function createPrependNodes(projectReferences, getCommandLine, readFile) {
107721         if (!projectReferences)
107722             return ts.emptyArray;
107723         var nodes;
107724         for (var i = 0; i < projectReferences.length; i++) {
107725             var ref = projectReferences[i];
107726             var resolvedRefOpts = getCommandLine(ref, i);
107727             if (ref.prepend && resolvedRefOpts && resolvedRefOpts.options) {
107728                 var out = ts.outFile(resolvedRefOpts.options);
107729                 // Upstream project didn't have outFile set -- skip (error will have been issued earlier)
107730                 if (!out)
107731                     continue;
107732                 var _a = ts.getOutputPathsForBundle(resolvedRefOpts.options, /*forceDtsPaths*/ true), jsFilePath = _a.jsFilePath, sourceMapFilePath = _a.sourceMapFilePath, declarationFilePath = _a.declarationFilePath, declarationMapPath = _a.declarationMapPath, buildInfoPath = _a.buildInfoPath;
107733                 var node = ts.createInputFiles(readFile, jsFilePath, sourceMapFilePath, declarationFilePath, declarationMapPath, buildInfoPath);
107734                 (nodes || (nodes = [])).push(node);
107735             }
107736         }
107737         return nodes || ts.emptyArray;
107738     }
107739     ts.createPrependNodes = createPrependNodes;
107740     function resolveProjectReferencePath(hostOrRef, ref) {
107741         var passedInRef = ref ? ref : hostOrRef;
107742         return ts.resolveConfigFileProjectName(passedInRef.path);
107743     }
107744     ts.resolveProjectReferencePath = resolveProjectReferencePath;
107745     /* @internal */
107746     /**
107747      * Returns a DiagnosticMessage if we won't include a resolved module due to its extension.
107748      * The DiagnosticMessage's parameters are the imported module name, and the filename it resolved to.
107749      * This returns a diagnostic even if the module will be an untyped module.
107750      */
107751     function getResolutionDiagnostic(options, _a) {
107752         var extension = _a.extension;
107753         switch (extension) {
107754             case ".ts" /* Ts */:
107755             case ".d.ts" /* Dts */:
107756                 // These are always allowed.
107757                 return undefined;
107758             case ".tsx" /* Tsx */:
107759                 return needJsx();
107760             case ".jsx" /* Jsx */:
107761                 return needJsx() || needAllowJs();
107762             case ".js" /* Js */:
107763                 return needAllowJs();
107764             case ".json" /* Json */:
107765                 return needResolveJsonModule();
107766         }
107767         function needJsx() {
107768             return options.jsx ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_jsx_is_not_set;
107769         }
107770         function needAllowJs() {
107771             return ts.getAllowJSCompilerOption(options) || !ts.getStrictOptionValue(options, "noImplicitAny") ? undefined : ts.Diagnostics.Could_not_find_a_declaration_file_for_module_0_1_implicitly_has_an_any_type;
107772         }
107773         function needResolveJsonModule() {
107774             return options.resolveJsonModule ? undefined : ts.Diagnostics.Module_0_was_resolved_to_1_but_resolveJsonModule_is_not_used;
107775         }
107776     }
107777     ts.getResolutionDiagnostic = getResolutionDiagnostic;
107778     function getModuleNames(_a) {
107779         var imports = _a.imports, moduleAugmentations = _a.moduleAugmentations;
107780         var res = imports.map(function (i) { return i.text; });
107781         for (var _i = 0, moduleAugmentations_1 = moduleAugmentations; _i < moduleAugmentations_1.length; _i++) {
107782             var aug = moduleAugmentations_1[_i];
107783             if (aug.kind === 10 /* StringLiteral */) {
107784                 res.push(aug.text);
107785             }
107786             // Do nothing if it's an Identifier; we don't need to do module resolution for `declare global`.
107787         }
107788         return res;
107789     }
107790 })(ts || (ts = {}));
107791 /*@internal*/
107792 var ts;
107793 (function (ts) {
107794     function getFileEmitOutput(program, sourceFile, emitOnlyDtsFiles, cancellationToken, customTransformers, forceDtsEmit) {
107795         var outputFiles = [];
107796         var _a = program.emit(sourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers, forceDtsEmit), emitSkipped = _a.emitSkipped, diagnostics = _a.diagnostics, exportedModulesFromDeclarationEmit = _a.exportedModulesFromDeclarationEmit;
107797         return { outputFiles: outputFiles, emitSkipped: emitSkipped, diagnostics: diagnostics, exportedModulesFromDeclarationEmit: exportedModulesFromDeclarationEmit };
107798         function writeFile(fileName, text, writeByteOrderMark) {
107799             outputFiles.push({ name: fileName, writeByteOrderMark: writeByteOrderMark, text: text });
107800         }
107801     }
107802     ts.getFileEmitOutput = getFileEmitOutput;
107803     var BuilderState;
107804     (function (BuilderState) {
107805         /**
107806          * Get the referencedFile from the imported module symbol
107807          */
107808         function getReferencedFileFromImportedModuleSymbol(symbol) {
107809             if (symbol.declarations && symbol.declarations[0]) {
107810                 var declarationSourceFile = ts.getSourceFileOfNode(symbol.declarations[0]);
107811                 return declarationSourceFile && declarationSourceFile.resolvedPath;
107812             }
107813         }
107814         /**
107815          * Get the referencedFile from the import name node from file
107816          */
107817         function getReferencedFileFromImportLiteral(checker, importName) {
107818             var symbol = checker.getSymbolAtLocation(importName);
107819             return symbol && getReferencedFileFromImportedModuleSymbol(symbol);
107820         }
107821         /**
107822          * Gets the path to reference file from file name, it could be resolvedPath if present otherwise path
107823          */
107824         function getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName) {
107825             return ts.toPath(program.getProjectReferenceRedirect(fileName) || fileName, sourceFileDirectory, getCanonicalFileName);
107826         }
107827         /**
107828          * Gets the referenced files for a file from the program with values for the keys as referenced file's path to be true
107829          */
107830         function getReferencedFiles(program, sourceFile, getCanonicalFileName) {
107831             var referencedFiles;
107832             // We need to use a set here since the code can contain the same import twice,
107833             // but that will only be one dependency.
107834             // To avoid invernal conversion, the key of the referencedFiles map must be of type Path
107835             if (sourceFile.imports && sourceFile.imports.length > 0) {
107836                 var checker = program.getTypeChecker();
107837                 for (var _i = 0, _a = sourceFile.imports; _i < _a.length; _i++) {
107838                     var importName = _a[_i];
107839                     var declarationSourceFilePath = getReferencedFileFromImportLiteral(checker, importName);
107840                     if (declarationSourceFilePath) {
107841                         addReferencedFile(declarationSourceFilePath);
107842                     }
107843                 }
107844             }
107845             var sourceFileDirectory = ts.getDirectoryPath(sourceFile.resolvedPath);
107846             // Handle triple slash references
107847             if (sourceFile.referencedFiles && sourceFile.referencedFiles.length > 0) {
107848                 for (var _b = 0, _c = sourceFile.referencedFiles; _b < _c.length; _b++) {
107849                     var referencedFile = _c[_b];
107850                     var referencedPath = getReferencedFileFromFileName(program, referencedFile.fileName, sourceFileDirectory, getCanonicalFileName);
107851                     addReferencedFile(referencedPath);
107852                 }
107853             }
107854             // Handle type reference directives
107855             if (sourceFile.resolvedTypeReferenceDirectiveNames) {
107856                 sourceFile.resolvedTypeReferenceDirectiveNames.forEach(function (resolvedTypeReferenceDirective) {
107857                     if (!resolvedTypeReferenceDirective) {
107858                         return;
107859                     }
107860                     var fileName = resolvedTypeReferenceDirective.resolvedFileName; // TODO: GH#18217
107861                     var typeFilePath = getReferencedFileFromFileName(program, fileName, sourceFileDirectory, getCanonicalFileName);
107862                     addReferencedFile(typeFilePath);
107863                 });
107864             }
107865             // Add module augmentation as references
107866             if (sourceFile.moduleAugmentations.length) {
107867                 var checker = program.getTypeChecker();
107868                 for (var _d = 0, _e = sourceFile.moduleAugmentations; _d < _e.length; _d++) {
107869                     var moduleName = _e[_d];
107870                     if (!ts.isStringLiteral(moduleName)) {
107871                         continue;
107872                     }
107873                     var symbol = checker.getSymbolAtLocation(moduleName);
107874                     if (!symbol) {
107875                         continue;
107876                     }
107877                     // Add any file other than our own as reference
107878                     addReferenceFromAmbientModule(symbol);
107879                 }
107880             }
107881             // From ambient modules
107882             for (var _f = 0, _g = program.getTypeChecker().getAmbientModules(); _f < _g.length; _f++) {
107883                 var ambientModule = _g[_f];
107884                 if (ambientModule.declarations.length > 1) {
107885                     addReferenceFromAmbientModule(ambientModule);
107886                 }
107887             }
107888             return referencedFiles;
107889             function addReferenceFromAmbientModule(symbol) {
107890                 // Add any file other than our own as reference
107891                 for (var _i = 0, _a = symbol.declarations; _i < _a.length; _i++) {
107892                     var declaration = _a[_i];
107893                     var declarationSourceFile = ts.getSourceFileOfNode(declaration);
107894                     if (declarationSourceFile &&
107895                         declarationSourceFile !== sourceFile) {
107896                         addReferencedFile(declarationSourceFile.resolvedPath);
107897                     }
107898                 }
107899             }
107900             function addReferencedFile(referencedPath) {
107901                 (referencedFiles || (referencedFiles = new ts.Set())).add(referencedPath);
107902             }
107903         }
107904         /**
107905          * Returns true if oldState is reusable, that is the emitKind = module/non module has not changed
107906          */
107907         function canReuseOldState(newReferencedMap, oldState) {
107908             return oldState && !oldState.referencedMap === !newReferencedMap;
107909         }
107910         BuilderState.canReuseOldState = canReuseOldState;
107911         /**
107912          * Creates the state of file references and signature for the new program from oldState if it is safe
107913          */
107914         function create(newProgram, getCanonicalFileName, oldState) {
107915             var fileInfos = new ts.Map();
107916             var referencedMap = newProgram.getCompilerOptions().module !== ts.ModuleKind.None ? new ts.Map() : undefined;
107917             var exportedModulesMap = referencedMap ? new ts.Map() : undefined;
107918             var hasCalledUpdateShapeSignature = new ts.Set();
107919             var useOldState = canReuseOldState(referencedMap, oldState);
107920             // Ensure source files have parent pointers set
107921             newProgram.getTypeChecker();
107922             // Create the reference map, and set the file infos
107923             for (var _i = 0, _a = newProgram.getSourceFiles(); _i < _a.length; _i++) {
107924                 var sourceFile = _a[_i];
107925                 var version_2 = ts.Debug.checkDefined(sourceFile.version, "Program intended to be used with Builder should have source files with versions set");
107926                 var oldInfo = useOldState ? oldState.fileInfos.get(sourceFile.resolvedPath) : undefined;
107927                 if (referencedMap) {
107928                     var newReferences = getReferencedFiles(newProgram, sourceFile, getCanonicalFileName);
107929                     if (newReferences) {
107930                         referencedMap.set(sourceFile.resolvedPath, newReferences);
107931                     }
107932                     // Copy old visible to outside files map
107933                     if (useOldState) {
107934                         var exportedModules = oldState.exportedModulesMap.get(sourceFile.resolvedPath);
107935                         if (exportedModules) {
107936                             exportedModulesMap.set(sourceFile.resolvedPath, exportedModules);
107937                         }
107938                     }
107939                 }
107940                 fileInfos.set(sourceFile.resolvedPath, { version: version_2, signature: oldInfo && oldInfo.signature, affectsGlobalScope: isFileAffectingGlobalScope(sourceFile) });
107941             }
107942             return {
107943                 fileInfos: fileInfos,
107944                 referencedMap: referencedMap,
107945                 exportedModulesMap: exportedModulesMap,
107946                 hasCalledUpdateShapeSignature: hasCalledUpdateShapeSignature
107947             };
107948         }
107949         BuilderState.create = create;
107950         /**
107951          * Releases needed properties
107952          */
107953         function releaseCache(state) {
107954             state.allFilesExcludingDefaultLibraryFile = undefined;
107955             state.allFileNames = undefined;
107956         }
107957         BuilderState.releaseCache = releaseCache;
107958         /**
107959          * Creates a clone of the state
107960          */
107961         function clone(state) {
107962             // Dont need to backup allFiles info since its cache anyway
107963             return {
107964                 fileInfos: new ts.Map(state.fileInfos),
107965                 referencedMap: state.referencedMap && new ts.Map(state.referencedMap),
107966                 exportedModulesMap: state.exportedModulesMap && new ts.Map(state.exportedModulesMap),
107967                 hasCalledUpdateShapeSignature: new ts.Set(state.hasCalledUpdateShapeSignature),
107968             };
107969         }
107970         BuilderState.clone = clone;
107971         /**
107972          * Gets the files affected by the path from the program
107973          */
107974         function getFilesAffectedBy(state, programOfThisState, path, cancellationToken, computeHash, cacheToUpdateSignature, exportedModulesMapCache) {
107975             // Since the operation could be cancelled, the signatures are always stored in the cache
107976             // They will be committed once it is safe to use them
107977             // eg when calling this api from tsserver, if there is no cancellation of the operation
107978             // In the other cases the affected files signatures are committed only after the iteration through the result is complete
107979             var signatureCache = cacheToUpdateSignature || new ts.Map();
107980             var sourceFile = programOfThisState.getSourceFileByPath(path);
107981             if (!sourceFile) {
107982                 return ts.emptyArray;
107983             }
107984             if (!updateShapeSignature(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache)) {
107985                 return [sourceFile];
107986             }
107987             var result = (state.referencedMap ? getFilesAffectedByUpdatedShapeWhenModuleEmit : getFilesAffectedByUpdatedShapeWhenNonModuleEmit)(state, programOfThisState, sourceFile, signatureCache, cancellationToken, computeHash, exportedModulesMapCache);
107988             if (!cacheToUpdateSignature) {
107989                 // Commit all the signatures in the signature cache
107990                 updateSignaturesFromCache(state, signatureCache);
107991             }
107992             return result;
107993         }
107994         BuilderState.getFilesAffectedBy = getFilesAffectedBy;
107995         /**
107996          * Updates the signatures from the cache into state's fileinfo signatures
107997          * This should be called whenever it is safe to commit the state of the builder
107998          */
107999         function updateSignaturesFromCache(state, signatureCache) {
108000             signatureCache.forEach(function (signature, path) { return updateSignatureOfFile(state, signature, path); });
108001         }
108002         BuilderState.updateSignaturesFromCache = updateSignaturesFromCache;
108003         function updateSignatureOfFile(state, signature, path) {
108004             state.fileInfos.get(path).signature = signature;
108005             state.hasCalledUpdateShapeSignature.add(path);
108006         }
108007         BuilderState.updateSignatureOfFile = updateSignatureOfFile;
108008         /**
108009          * Returns if the shape of the signature has changed since last emit
108010          */
108011         function updateShapeSignature(state, programOfThisState, sourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
108012             ts.Debug.assert(!!sourceFile);
108013             ts.Debug.assert(!exportedModulesMapCache || !!state.exportedModulesMap, "Compute visible to outside map only if visibleToOutsideReferencedMap present in the state");
108014             // If we have cached the result for this file, that means hence forth we should assume file shape is uptodate
108015             if (state.hasCalledUpdateShapeSignature.has(sourceFile.resolvedPath) || cacheToUpdateSignature.has(sourceFile.resolvedPath)) {
108016                 return false;
108017             }
108018             var info = state.fileInfos.get(sourceFile.resolvedPath);
108019             if (!info)
108020                 return ts.Debug.fail();
108021             var prevSignature = info.signature;
108022             var latestSignature;
108023             if (sourceFile.isDeclarationFile) {
108024                 latestSignature = sourceFile.version;
108025                 if (exportedModulesMapCache && latestSignature !== prevSignature) {
108026                     // All the references in this file are exported
108027                     var references = state.referencedMap ? state.referencedMap.get(sourceFile.resolvedPath) : undefined;
108028                     exportedModulesMapCache.set(sourceFile.resolvedPath, references || false);
108029                 }
108030             }
108031             else {
108032                 var emitOutput_1 = getFileEmitOutput(programOfThisState, sourceFile, 
108033                 /*emitOnlyDtsFiles*/ true, cancellationToken, 
108034                 /*customTransformers*/ undefined, 
108035                 /*forceDtsEmit*/ true);
108036                 var firstDts_1 = emitOutput_1.outputFiles &&
108037                     programOfThisState.getCompilerOptions().declarationMap ?
108038                     emitOutput_1.outputFiles.length > 1 ? emitOutput_1.outputFiles[1] : undefined :
108039                     emitOutput_1.outputFiles.length > 0 ? emitOutput_1.outputFiles[0] : undefined;
108040                 if (firstDts_1) {
108041                     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; })); });
108042                     latestSignature = (computeHash || ts.generateDjb2Hash)(firstDts_1.text);
108043                     if (exportedModulesMapCache && latestSignature !== prevSignature) {
108044                         updateExportedModules(sourceFile, emitOutput_1.exportedModulesFromDeclarationEmit, exportedModulesMapCache);
108045                     }
108046                 }
108047                 else {
108048                     latestSignature = prevSignature; // TODO: GH#18217
108049                 }
108050             }
108051             cacheToUpdateSignature.set(sourceFile.resolvedPath, latestSignature);
108052             return !prevSignature || latestSignature !== prevSignature;
108053         }
108054         BuilderState.updateShapeSignature = updateShapeSignature;
108055         /**
108056          * Coverts the declaration emit result into exported modules map
108057          */
108058         function updateExportedModules(sourceFile, exportedModulesFromDeclarationEmit, exportedModulesMapCache) {
108059             if (!exportedModulesFromDeclarationEmit) {
108060                 exportedModulesMapCache.set(sourceFile.resolvedPath, false);
108061                 return;
108062             }
108063             var exportedModules;
108064             exportedModulesFromDeclarationEmit.forEach(function (symbol) { return addExportedModule(getReferencedFileFromImportedModuleSymbol(symbol)); });
108065             exportedModulesMapCache.set(sourceFile.resolvedPath, exportedModules || false);
108066             function addExportedModule(exportedModulePath) {
108067                 if (exportedModulePath) {
108068                     if (!exportedModules) {
108069                         exportedModules = new ts.Set();
108070                     }
108071                     exportedModules.add(exportedModulePath);
108072                 }
108073             }
108074         }
108075         /**
108076          * Updates the exported modules from cache into state's exported modules map
108077          * This should be called whenever it is safe to commit the state of the builder
108078          */
108079         function updateExportedFilesMapFromCache(state, exportedModulesMapCache) {
108080             if (exportedModulesMapCache) {
108081                 ts.Debug.assert(!!state.exportedModulesMap);
108082                 exportedModulesMapCache.forEach(function (exportedModules, path) {
108083                     if (exportedModules) {
108084                         state.exportedModulesMap.set(path, exportedModules);
108085                     }
108086                     else {
108087                         state.exportedModulesMap.delete(path);
108088                     }
108089                 });
108090             }
108091         }
108092         BuilderState.updateExportedFilesMapFromCache = updateExportedFilesMapFromCache;
108093         /**
108094          * Get all the dependencies of the sourceFile
108095          */
108096         function getAllDependencies(state, programOfThisState, sourceFile) {
108097             var compilerOptions = programOfThisState.getCompilerOptions();
108098             // With --out or --outFile all outputs go into single file, all files depend on each other
108099             if (ts.outFile(compilerOptions)) {
108100                 return getAllFileNames(state, programOfThisState);
108101             }
108102             // If this is non module emit, or its a global file, it depends on all the source files
108103             if (!state.referencedMap || isFileAffectingGlobalScope(sourceFile)) {
108104                 return getAllFileNames(state, programOfThisState);
108105             }
108106             // Get the references, traversing deep from the referenceMap
108107             var seenMap = new ts.Set();
108108             var queue = [sourceFile.resolvedPath];
108109             while (queue.length) {
108110                 var path = queue.pop();
108111                 if (!seenMap.has(path)) {
108112                     seenMap.add(path);
108113                     var references = state.referencedMap.get(path);
108114                     if (references) {
108115                         var iterator = references.keys();
108116                         for (var iterResult = iterator.next(); !iterResult.done; iterResult = iterator.next()) {
108117                             queue.push(iterResult.value);
108118                         }
108119                     }
108120                 }
108121             }
108122             return ts.arrayFrom(ts.mapDefinedIterator(seenMap.keys(), function (path) { var _a, _b; return (_b = (_a = programOfThisState.getSourceFileByPath(path)) === null || _a === void 0 ? void 0 : _a.fileName) !== null && _b !== void 0 ? _b : path; }));
108123         }
108124         BuilderState.getAllDependencies = getAllDependencies;
108125         /**
108126          * Gets the names of all files from the program
108127          */
108128         function getAllFileNames(state, programOfThisState) {
108129             if (!state.allFileNames) {
108130                 var sourceFiles = programOfThisState.getSourceFiles();
108131                 state.allFileNames = sourceFiles === ts.emptyArray ? ts.emptyArray : sourceFiles.map(function (file) { return file.fileName; });
108132             }
108133             return state.allFileNames;
108134         }
108135         /**
108136          * Gets the files referenced by the the file path
108137          */
108138         function getReferencedByPaths(state, referencedFilePath) {
108139             return ts.arrayFrom(ts.mapDefinedIterator(state.referencedMap.entries(), function (_a) {
108140                 var filePath = _a[0], referencesInFile = _a[1];
108141                 return referencesInFile.has(referencedFilePath) ? filePath : undefined;
108142             }));
108143         }
108144         BuilderState.getReferencedByPaths = getReferencedByPaths;
108145         /**
108146          * For script files that contains only ambient external modules, although they are not actually external module files,
108147          * they can only be consumed via importing elements from them. Regular script files cannot consume them. Therefore,
108148          * there are no point to rebuild all script files if these special files have changed. However, if any statement
108149          * in the file is not ambient external module, we treat it as a regular script file.
108150          */
108151         function containsOnlyAmbientModules(sourceFile) {
108152             for (var _i = 0, _a = sourceFile.statements; _i < _a.length; _i++) {
108153                 var statement = _a[_i];
108154                 if (!ts.isModuleWithStringLiteralName(statement)) {
108155                     return false;
108156                 }
108157             }
108158             return true;
108159         }
108160         /**
108161          * Return true if file contains anything that augments to global scope we need to build them as if
108162          * they are global files as well as module
108163          */
108164         function containsGlobalScopeAugmentation(sourceFile) {
108165             return ts.some(sourceFile.moduleAugmentations, function (augmentation) { return ts.isGlobalScopeAugmentation(augmentation.parent); });
108166         }
108167         /**
108168          * Return true if the file will invalidate all files because it affectes global scope
108169          */
108170         function isFileAffectingGlobalScope(sourceFile) {
108171             return containsGlobalScopeAugmentation(sourceFile) ||
108172                 !ts.isExternalModule(sourceFile) && !containsOnlyAmbientModules(sourceFile);
108173         }
108174         /**
108175          * Gets all files of the program excluding the default library file
108176          */
108177         function getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, firstSourceFile) {
108178             // Use cached result
108179             if (state.allFilesExcludingDefaultLibraryFile) {
108180                 return state.allFilesExcludingDefaultLibraryFile;
108181             }
108182             var result;
108183             if (firstSourceFile)
108184                 addSourceFile(firstSourceFile);
108185             for (var _i = 0, _a = programOfThisState.getSourceFiles(); _i < _a.length; _i++) {
108186                 var sourceFile = _a[_i];
108187                 if (sourceFile !== firstSourceFile) {
108188                     addSourceFile(sourceFile);
108189                 }
108190             }
108191             state.allFilesExcludingDefaultLibraryFile = result || ts.emptyArray;
108192             return state.allFilesExcludingDefaultLibraryFile;
108193             function addSourceFile(sourceFile) {
108194                 if (!programOfThisState.isSourceFileDefaultLibrary(sourceFile)) {
108195                     (result || (result = [])).push(sourceFile);
108196                 }
108197             }
108198         }
108199         BuilderState.getAllFilesExcludingDefaultLibraryFile = getAllFilesExcludingDefaultLibraryFile;
108200         /**
108201          * When program emits non modular code, gets the files affected by the sourceFile whose shape has changed
108202          */
108203         function getFilesAffectedByUpdatedShapeWhenNonModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape) {
108204             var compilerOptions = programOfThisState.getCompilerOptions();
108205             // If `--out` or `--outFile` is specified, any new emit will result in re-emitting the entire project,
108206             // so returning the file itself is good enough.
108207             if (compilerOptions && ts.outFile(compilerOptions)) {
108208                 return [sourceFileWithUpdatedShape];
108209             }
108210             return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
108211         }
108212         /**
108213          * When program emits modular code, gets the files affected by the sourceFile whose shape has changed
108214          */
108215         function getFilesAffectedByUpdatedShapeWhenModuleEmit(state, programOfThisState, sourceFileWithUpdatedShape, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache) {
108216             if (isFileAffectingGlobalScope(sourceFileWithUpdatedShape)) {
108217                 return getAllFilesExcludingDefaultLibraryFile(state, programOfThisState, sourceFileWithUpdatedShape);
108218             }
108219             var compilerOptions = programOfThisState.getCompilerOptions();
108220             if (compilerOptions && (compilerOptions.isolatedModules || ts.outFile(compilerOptions))) {
108221                 return [sourceFileWithUpdatedShape];
108222             }
108223             // Now we need to if each file in the referencedBy list has a shape change as well.
108224             // Because if so, its own referencedBy files need to be saved as well to make the
108225             // emitting result consistent with files on disk.
108226             var seenFileNamesMap = new ts.Map();
108227             // Start with the paths this file was referenced by
108228             seenFileNamesMap.set(sourceFileWithUpdatedShape.resolvedPath, sourceFileWithUpdatedShape);
108229             var queue = getReferencedByPaths(state, sourceFileWithUpdatedShape.resolvedPath);
108230             while (queue.length > 0) {
108231                 var currentPath = queue.pop();
108232                 if (!seenFileNamesMap.has(currentPath)) {
108233                     var currentSourceFile = programOfThisState.getSourceFileByPath(currentPath);
108234                     seenFileNamesMap.set(currentPath, currentSourceFile);
108235                     if (currentSourceFile && updateShapeSignature(state, programOfThisState, currentSourceFile, cacheToUpdateSignature, cancellationToken, computeHash, exportedModulesMapCache)) {
108236                         queue.push.apply(queue, getReferencedByPaths(state, currentSourceFile.resolvedPath));
108237                     }
108238                 }
108239             }
108240             // Return array of values that needs emit
108241             return ts.arrayFrom(ts.mapDefinedIterator(seenFileNamesMap.values(), function (value) { return value; }));
108242         }
108243     })(BuilderState = ts.BuilderState || (ts.BuilderState = {}));
108244 })(ts || (ts = {}));
108245 /*@internal*/
108246 var ts;
108247 (function (ts) {
108248     var BuilderFileEmit;
108249     (function (BuilderFileEmit) {
108250         BuilderFileEmit[BuilderFileEmit["DtsOnly"] = 0] = "DtsOnly";
108251         BuilderFileEmit[BuilderFileEmit["Full"] = 1] = "Full";
108252     })(BuilderFileEmit = ts.BuilderFileEmit || (ts.BuilderFileEmit = {}));
108253     function hasSameKeys(map1, map2) {
108254         // Has same size and every key is present in both maps
108255         return map1 === map2 || map1 !== undefined && map2 !== undefined && map1.size === map2.size && !ts.forEachKey(map1, function (key) { return !map2.has(key); });
108256     }
108257     /**
108258      * Create the state so that we can iterate on changedFiles/affected files
108259      */
108260     function createBuilderProgramState(newProgram, getCanonicalFileName, oldState) {
108261         var state = ts.BuilderState.create(newProgram, getCanonicalFileName, oldState);
108262         state.program = newProgram;
108263         var compilerOptions = newProgram.getCompilerOptions();
108264         state.compilerOptions = compilerOptions;
108265         // With --out or --outFile, any change affects all semantic diagnostics so no need to cache them
108266         if (!ts.outFile(compilerOptions)) {
108267             state.semanticDiagnosticsPerFile = new ts.Map();
108268         }
108269         state.changedFilesSet = new ts.Set();
108270         var useOldState = ts.BuilderState.canReuseOldState(state.referencedMap, oldState);
108271         var oldCompilerOptions = useOldState ? oldState.compilerOptions : undefined;
108272         var canCopySemanticDiagnostics = useOldState && oldState.semanticDiagnosticsPerFile && !!state.semanticDiagnosticsPerFile &&
108273             !ts.compilerOptionsAffectSemanticDiagnostics(compilerOptions, oldCompilerOptions);
108274         if (useOldState) {
108275             // Verify the sanity of old state
108276             if (!oldState.currentChangedFilePath) {
108277                 var affectedSignatures = oldState.currentAffectedFilesSignatures;
108278                 ts.Debug.assert(!oldState.affectedFiles && (!affectedSignatures || !affectedSignatures.size), "Cannot reuse if only few affected files of currentChangedFile were iterated");
108279             }
108280             var changedFilesSet = oldState.changedFilesSet;
108281             if (canCopySemanticDiagnostics) {
108282                 ts.Debug.assert(!changedFilesSet || !ts.forEachKey(changedFilesSet, function (path) { return oldState.semanticDiagnosticsPerFile.has(path); }), "Semantic diagnostics shouldnt be available for changed files");
108283             }
108284             // Copy old state's changed files set
108285             changedFilesSet === null || changedFilesSet === void 0 ? void 0 : changedFilesSet.forEach(function (value) { return state.changedFilesSet.add(value); });
108286             if (!ts.outFile(compilerOptions) && oldState.affectedFilesPendingEmit) {
108287                 state.affectedFilesPendingEmit = oldState.affectedFilesPendingEmit.slice();
108288                 state.affectedFilesPendingEmitKind = oldState.affectedFilesPendingEmitKind && new ts.Map(oldState.affectedFilesPendingEmitKind);
108289                 state.affectedFilesPendingEmitIndex = oldState.affectedFilesPendingEmitIndex;
108290                 state.seenAffectedFiles = new ts.Set();
108291             }
108292         }
108293         // Update changed files and copy semantic diagnostics if we can
108294         var referencedMap = state.referencedMap;
108295         var oldReferencedMap = useOldState ? oldState.referencedMap : undefined;
108296         var copyDeclarationFileDiagnostics = canCopySemanticDiagnostics && !compilerOptions.skipLibCheck === !oldCompilerOptions.skipLibCheck;
108297         var copyLibFileDiagnostics = copyDeclarationFileDiagnostics && !compilerOptions.skipDefaultLibCheck === !oldCompilerOptions.skipDefaultLibCheck;
108298         state.fileInfos.forEach(function (info, sourceFilePath) {
108299             var oldInfo;
108300             var newReferences;
108301             // if not using old state, every file is changed
108302             if (!useOldState ||
108303                 // File wasnt present in old state
108304                 !(oldInfo = oldState.fileInfos.get(sourceFilePath)) ||
108305                 // versions dont match
108306                 oldInfo.version !== info.version ||
108307                 // Referenced files changed
108308                 !hasSameKeys(newReferences = referencedMap && referencedMap.get(sourceFilePath), oldReferencedMap && oldReferencedMap.get(sourceFilePath)) ||
108309                 // Referenced file was deleted in the new program
108310                 newReferences && ts.forEachKey(newReferences, function (path) { return !state.fileInfos.has(path) && oldState.fileInfos.has(path); })) {
108311                 // Register file as changed file and do not copy semantic diagnostics, since all changed files need to be re-evaluated
108312                 state.changedFilesSet.add(sourceFilePath);
108313             }
108314             else if (canCopySemanticDiagnostics) {
108315                 var sourceFile = newProgram.getSourceFileByPath(sourceFilePath);
108316                 if (sourceFile.isDeclarationFile && !copyDeclarationFileDiagnostics) {
108317                     return;
108318                 }
108319                 if (sourceFile.hasNoDefaultLib && !copyLibFileDiagnostics) {
108320                     return;
108321                 }
108322                 // Unchanged file copy diagnostics
108323                 var diagnostics = oldState.semanticDiagnosticsPerFile.get(sourceFilePath);
108324                 if (diagnostics) {
108325                     state.semanticDiagnosticsPerFile.set(sourceFilePath, oldState.hasReusableDiagnostic ? convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) : diagnostics);
108326                     if (!state.semanticDiagnosticsFromOldState) {
108327                         state.semanticDiagnosticsFromOldState = new ts.Set();
108328                     }
108329                     state.semanticDiagnosticsFromOldState.add(sourceFilePath);
108330                 }
108331             }
108332         });
108333         // If the global file is removed, add all files as changed
108334         if (useOldState && ts.forEachEntry(oldState.fileInfos, function (info, sourceFilePath) { return info.affectsGlobalScope && !state.fileInfos.has(sourceFilePath); })) {
108335             ts.BuilderState.getAllFilesExcludingDefaultLibraryFile(state, newProgram, /*firstSourceFile*/ undefined)
108336                 .forEach(function (file) { return state.changedFilesSet.add(file.resolvedPath); });
108337         }
108338         else if (oldCompilerOptions && !ts.outFile(compilerOptions) && ts.compilerOptionsAffectEmit(compilerOptions, oldCompilerOptions)) {
108339             // Add all files to affectedFilesPendingEmit since emit changed
108340             newProgram.getSourceFiles().forEach(function (f) { return addToAffectedFilesPendingEmit(state, f.resolvedPath, 1 /* Full */); });
108341             ts.Debug.assert(!state.seenAffectedFiles || !state.seenAffectedFiles.size);
108342             state.seenAffectedFiles = state.seenAffectedFiles || new ts.Set();
108343         }
108344         state.buildInfoEmitPending = !!state.changedFilesSet.size;
108345         return state;
108346     }
108347     function convertToDiagnostics(diagnostics, newProgram, getCanonicalFileName) {
108348         if (!diagnostics.length)
108349             return ts.emptyArray;
108350         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(newProgram.getCompilerOptions()), newProgram.getCurrentDirectory()));
108351         return diagnostics.map(function (diagnostic) {
108352             var result = convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath);
108353             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
108354             result.reportsDeprecated = diagnostic.reportDeprecated;
108355             result.source = diagnostic.source;
108356             result.skippedOn = diagnostic.skippedOn;
108357             var relatedInformation = diagnostic.relatedInformation;
108358             result.relatedInformation = relatedInformation ?
108359                 relatedInformation.length ?
108360                     relatedInformation.map(function (r) { return convertToDiagnosticRelatedInformation(r, newProgram, toPath); }) :
108361                     [] :
108362                 undefined;
108363             return result;
108364         });
108365         function toPath(path) {
108366             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
108367         }
108368     }
108369     function convertToDiagnosticRelatedInformation(diagnostic, newProgram, toPath) {
108370         var file = diagnostic.file;
108371         return __assign(__assign({}, diagnostic), { file: file ? newProgram.getSourceFileByPath(toPath(file)) : undefined });
108372     }
108373     /**
108374      * Releases program and other related not needed properties
108375      */
108376     function releaseCache(state) {
108377         ts.BuilderState.releaseCache(state);
108378         state.program = undefined;
108379     }
108380     /**
108381      * Creates a clone of the state
108382      */
108383     function cloneBuilderProgramState(state) {
108384         var newState = ts.BuilderState.clone(state);
108385         newState.semanticDiagnosticsPerFile = state.semanticDiagnosticsPerFile && new ts.Map(state.semanticDiagnosticsPerFile);
108386         newState.changedFilesSet = new ts.Set(state.changedFilesSet);
108387         newState.affectedFiles = state.affectedFiles;
108388         newState.affectedFilesIndex = state.affectedFilesIndex;
108389         newState.currentChangedFilePath = state.currentChangedFilePath;
108390         newState.currentAffectedFilesSignatures = state.currentAffectedFilesSignatures && new ts.Map(state.currentAffectedFilesSignatures);
108391         newState.currentAffectedFilesExportedModulesMap = state.currentAffectedFilesExportedModulesMap && new ts.Map(state.currentAffectedFilesExportedModulesMap);
108392         newState.seenAffectedFiles = state.seenAffectedFiles && new ts.Set(state.seenAffectedFiles);
108393         newState.cleanedDiagnosticsOfLibFiles = state.cleanedDiagnosticsOfLibFiles;
108394         newState.semanticDiagnosticsFromOldState = state.semanticDiagnosticsFromOldState && new ts.Set(state.semanticDiagnosticsFromOldState);
108395         newState.program = state.program;
108396         newState.compilerOptions = state.compilerOptions;
108397         newState.affectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
108398         newState.affectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
108399         newState.affectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
108400         newState.seenEmittedFiles = state.seenEmittedFiles && new ts.Map(state.seenEmittedFiles);
108401         newState.programEmitComplete = state.programEmitComplete;
108402         return newState;
108403     }
108404     /**
108405      * Verifies that source file is ok to be used in calls that arent handled by next
108406      */
108407     function assertSourceFileOkWithoutNextAffectedCall(state, sourceFile) {
108408         ts.Debug.assert(!sourceFile || !state.affectedFiles || state.affectedFiles[state.affectedFilesIndex - 1] !== sourceFile || !state.semanticDiagnosticsPerFile.has(sourceFile.resolvedPath));
108409     }
108410     /**
108411      * This function returns the next affected file to be processed.
108412      * Note that until doneAffected is called it would keep reporting same result
108413      * This is to allow the callers to be able to actually remove affected file only when the operation is complete
108414      * eg. if during diagnostics check cancellation token ends up cancelling the request, the affected file should be retained
108415      */
108416     function getNextAffectedFile(state, cancellationToken, computeHash) {
108417         while (true) {
108418             var affectedFiles = state.affectedFiles;
108419             if (affectedFiles) {
108420                 var seenAffectedFiles = state.seenAffectedFiles;
108421                 var affectedFilesIndex = state.affectedFilesIndex; // TODO: GH#18217
108422                 while (affectedFilesIndex < affectedFiles.length) {
108423                     var affectedFile = affectedFiles[affectedFilesIndex];
108424                     if (!seenAffectedFiles.has(affectedFile.resolvedPath)) {
108425                         // Set the next affected file as seen and remove the cached semantic diagnostics
108426                         state.affectedFilesIndex = affectedFilesIndex;
108427                         handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash);
108428                         return affectedFile;
108429                     }
108430                     affectedFilesIndex++;
108431                 }
108432                 // Remove the changed file from the change set
108433                 state.changedFilesSet.delete(state.currentChangedFilePath);
108434                 state.currentChangedFilePath = undefined;
108435                 // Commit the changes in file signature
108436                 ts.BuilderState.updateSignaturesFromCache(state, state.currentAffectedFilesSignatures);
108437                 state.currentAffectedFilesSignatures.clear();
108438                 ts.BuilderState.updateExportedFilesMapFromCache(state, state.currentAffectedFilesExportedModulesMap);
108439                 state.affectedFiles = undefined;
108440             }
108441             // Get next changed file
108442             var nextKey = state.changedFilesSet.keys().next();
108443             if (nextKey.done) {
108444                 // Done
108445                 return undefined;
108446             }
108447             // With --out or --outFile all outputs go into single file
108448             // so operations are performed directly on program, return program
108449             var program = ts.Debug.checkDefined(state.program);
108450             var compilerOptions = program.getCompilerOptions();
108451             if (ts.outFile(compilerOptions)) {
108452                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
108453                 return program;
108454             }
108455             // Get next batch of affected files
108456             if (!state.currentAffectedFilesSignatures)
108457                 state.currentAffectedFilesSignatures = new ts.Map();
108458             if (state.exportedModulesMap) {
108459                 if (!state.currentAffectedFilesExportedModulesMap)
108460                     state.currentAffectedFilesExportedModulesMap = new ts.Map();
108461             }
108462             state.affectedFiles = ts.BuilderState.getFilesAffectedBy(state, program, nextKey.value, cancellationToken, computeHash, state.currentAffectedFilesSignatures, state.currentAffectedFilesExportedModulesMap);
108463             state.currentChangedFilePath = nextKey.value;
108464             state.affectedFilesIndex = 0;
108465             if (!state.seenAffectedFiles)
108466                 state.seenAffectedFiles = new ts.Set();
108467         }
108468     }
108469     /**
108470      * Returns next file to be emitted from files that retrieved semantic diagnostics but did not emit yet
108471      */
108472     function getNextAffectedFilePendingEmit(state) {
108473         var affectedFilesPendingEmit = state.affectedFilesPendingEmit;
108474         if (affectedFilesPendingEmit) {
108475             var seenEmittedFiles = (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map()));
108476             for (var i = state.affectedFilesPendingEmitIndex; i < affectedFilesPendingEmit.length; i++) {
108477                 var affectedFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(affectedFilesPendingEmit[i]);
108478                 if (affectedFile) {
108479                     var seenKind = seenEmittedFiles.get(affectedFile.resolvedPath);
108480                     var emitKind = ts.Debug.checkDefined(ts.Debug.checkDefined(state.affectedFilesPendingEmitKind).get(affectedFile.resolvedPath));
108481                     if (seenKind === undefined || seenKind < emitKind) {
108482                         // emit this file
108483                         state.affectedFilesPendingEmitIndex = i;
108484                         return { affectedFile: affectedFile, emitKind: emitKind };
108485                     }
108486                 }
108487             }
108488             state.affectedFilesPendingEmit = undefined;
108489             state.affectedFilesPendingEmitKind = undefined;
108490             state.affectedFilesPendingEmitIndex = undefined;
108491         }
108492         return undefined;
108493     }
108494     /**
108495      *  Handles semantic diagnostics and dts emit for affectedFile and files, that are referencing modules that export entities from affected file
108496      *  This is because even though js emit doesnt change, dts emit / type used can change resulting in need for dts emit and js change
108497      */
108498     function handleDtsMayChangeOfAffectedFile(state, affectedFile, cancellationToken, computeHash) {
108499         removeSemanticDiagnosticsOf(state, affectedFile.resolvedPath);
108500         // If affected files is everything except default library, then nothing more to do
108501         if (state.allFilesExcludingDefaultLibraryFile === state.affectedFiles) {
108502             if (!state.cleanedDiagnosticsOfLibFiles) {
108503                 state.cleanedDiagnosticsOfLibFiles = true;
108504                 var program_1 = ts.Debug.checkDefined(state.program);
108505                 var options_2 = program_1.getCompilerOptions();
108506                 ts.forEach(program_1.getSourceFiles(), function (f) {
108507                     return program_1.isSourceFileDefaultLibrary(f) &&
108508                         !ts.skipTypeChecking(f, options_2, program_1) &&
108509                         removeSemanticDiagnosticsOf(state, f.resolvedPath);
108510                 });
108511             }
108512             return;
108513         }
108514         if (!state.compilerOptions.assumeChangesOnlyAffectDirectDependencies) {
108515             forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, function (state, path) { return handleDtsMayChangeOf(state, path, cancellationToken, computeHash); });
108516         }
108517     }
108518     /**
108519      * Handle the dts may change, so they need to be added to pending emit if dts emit is enabled,
108520      * Also we need to make sure signature is updated for these files
108521      */
108522     function handleDtsMayChangeOf(state, path, cancellationToken, computeHash) {
108523         removeSemanticDiagnosticsOf(state, path);
108524         if (!state.changedFilesSet.has(path)) {
108525             var program = ts.Debug.checkDefined(state.program);
108526             var sourceFile = program.getSourceFileByPath(path);
108527             if (sourceFile) {
108528                 // Even though the js emit doesnt change and we are already handling dts emit and semantic diagnostics
108529                 // we need to update the signature to reflect correctness of the signature(which is output d.ts emit) of this file
108530                 // This ensures that we dont later during incremental builds considering wrong signature.
108531                 // Eg where this also is needed to ensure that .tsbuildinfo generated by incremental build should be same as if it was first fresh build
108532                 ts.BuilderState.updateShapeSignature(state, program, sourceFile, ts.Debug.checkDefined(state.currentAffectedFilesSignatures), cancellationToken, computeHash, state.currentAffectedFilesExportedModulesMap);
108533                 // If not dts emit, nothing more to do
108534                 if (ts.getEmitDeclarations(state.compilerOptions)) {
108535                     addToAffectedFilesPendingEmit(state, path, 0 /* DtsOnly */);
108536                 }
108537             }
108538         }
108539         return false;
108540     }
108541     /**
108542      * Removes semantic diagnostics for path and
108543      * returns true if there are no more semantic diagnostics from the old state
108544      */
108545     function removeSemanticDiagnosticsOf(state, path) {
108546         if (!state.semanticDiagnosticsFromOldState) {
108547             return true;
108548         }
108549         state.semanticDiagnosticsFromOldState.delete(path);
108550         state.semanticDiagnosticsPerFile.delete(path);
108551         return !state.semanticDiagnosticsFromOldState.size;
108552     }
108553     function isChangedSignature(state, path) {
108554         var newSignature = ts.Debug.checkDefined(state.currentAffectedFilesSignatures).get(path);
108555         var oldSignature = ts.Debug.checkDefined(state.fileInfos.get(path)).signature;
108556         return newSignature !== oldSignature;
108557     }
108558     /**
108559      * Iterate on referencing modules that export entities from affected file
108560      */
108561     function forEachReferencingModulesOfExportOfAffectedFile(state, affectedFile, fn) {
108562         // If there was change in signature (dts output) for the changed file,
108563         // then only we need to handle pending file emit
108564         if (!state.exportedModulesMap || !state.changedFilesSet.has(affectedFile.resolvedPath)) {
108565             return;
108566         }
108567         if (!isChangedSignature(state, affectedFile.resolvedPath))
108568             return;
108569         // Since isolated modules dont change js files, files affected by change in signature is itself
108570         // But we need to cleanup semantic diagnostics and queue dts emit for affected files
108571         if (state.compilerOptions.isolatedModules) {
108572             var seenFileNamesMap = new ts.Map();
108573             seenFileNamesMap.set(affectedFile.resolvedPath, true);
108574             var queue = ts.BuilderState.getReferencedByPaths(state, affectedFile.resolvedPath);
108575             while (queue.length > 0) {
108576                 var currentPath = queue.pop();
108577                 if (!seenFileNamesMap.has(currentPath)) {
108578                     seenFileNamesMap.set(currentPath, true);
108579                     var result = fn(state, currentPath);
108580                     if (result && isChangedSignature(state, currentPath)) {
108581                         var currentSourceFile = ts.Debug.checkDefined(state.program).getSourceFileByPath(currentPath);
108582                         queue.push.apply(queue, ts.BuilderState.getReferencedByPaths(state, currentSourceFile.resolvedPath));
108583                     }
108584                 }
108585             }
108586         }
108587         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
108588         var seenFileAndExportsOfFile = new ts.Set();
108589         // Go through exported modules from cache first
108590         // If exported modules has path, all files referencing file exported from are affected
108591         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
108592             return exportedModules &&
108593                 exportedModules.has(affectedFile.resolvedPath) &&
108594                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
108595         })) {
108596             return;
108597         }
108598         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
108599         ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
108600             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
108601                 exportedModules.has(affectedFile.resolvedPath) &&
108602                 forEachFilesReferencingPath(state, exportedFromPath, seenFileAndExportsOfFile, fn);
108603         });
108604     }
108605     /**
108606      * Iterate on files referencing referencedPath
108607      */
108608     function forEachFilesReferencingPath(state, referencedPath, seenFileAndExportsOfFile, fn) {
108609         return ts.forEachEntry(state.referencedMap, function (referencesInFile, filePath) {
108610             return referencesInFile.has(referencedPath) && forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn);
108611         });
108612     }
108613     /**
108614      * fn on file and iterate on anything that exports this file
108615      */
108616     function forEachFileAndExportsOfFile(state, filePath, seenFileAndExportsOfFile, fn) {
108617         if (!ts.tryAddToSet(seenFileAndExportsOfFile, filePath)) {
108618             return false;
108619         }
108620         if (fn(state, filePath)) {
108621             // If there are no more diagnostics from old cache, done
108622             return true;
108623         }
108624         ts.Debug.assert(!!state.currentAffectedFilesExportedModulesMap);
108625         // Go through exported modules from cache first
108626         // If exported modules has path, all files referencing file exported from are affected
108627         if (ts.forEachEntry(state.currentAffectedFilesExportedModulesMap, function (exportedModules, exportedFromPath) {
108628             return exportedModules &&
108629                 exportedModules.has(filePath) &&
108630                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
108631         })) {
108632             return true;
108633         }
108634         // If exported from path is not from cache and exported modules has path, all files referencing file exported from are affected
108635         if (ts.forEachEntry(state.exportedModulesMap, function (exportedModules, exportedFromPath) {
108636             return !state.currentAffectedFilesExportedModulesMap.has(exportedFromPath) && // If we already iterated this through cache, ignore it
108637                 exportedModules.has(filePath) &&
108638                 forEachFileAndExportsOfFile(state, exportedFromPath, seenFileAndExportsOfFile, fn);
108639         })) {
108640             return true;
108641         }
108642         // Remove diagnostics of files that import this file (without going to exports of referencing files)
108643         return !!ts.forEachEntry(state.referencedMap, function (referencesInFile, referencingFilePath) {
108644             return referencesInFile.has(filePath) &&
108645                 !seenFileAndExportsOfFile.has(referencingFilePath) && // Not already removed diagnostic file
108646                 fn(state, referencingFilePath);
108647         } // Dont add to seen since this is not yet done with the export removal
108648         );
108649     }
108650     /**
108651      * This is called after completing operation on the next affected file.
108652      * The operations here are postponed to ensure that cancellation during the iteration is handled correctly
108653      */
108654     function doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
108655         if (isBuildInfoEmit) {
108656             state.buildInfoEmitPending = false;
108657         }
108658         else if (affected === state.program) {
108659             state.changedFilesSet.clear();
108660             state.programEmitComplete = true;
108661         }
108662         else {
108663             state.seenAffectedFiles.add(affected.resolvedPath);
108664             if (emitKind !== undefined) {
108665                 (state.seenEmittedFiles || (state.seenEmittedFiles = new ts.Map())).set(affected.resolvedPath, emitKind);
108666             }
108667             if (isPendingEmit) {
108668                 state.affectedFilesPendingEmitIndex++;
108669                 state.buildInfoEmitPending = true;
108670             }
108671             else {
108672                 state.affectedFilesIndex++;
108673             }
108674         }
108675     }
108676     /**
108677      * Returns the result with affected file
108678      */
108679     function toAffectedFileResult(state, result, affected) {
108680         doneWithAffectedFile(state, affected);
108681         return { result: result, affected: affected };
108682     }
108683     /**
108684      * Returns the result with affected file
108685      */
108686     function toAffectedFileEmitResult(state, result, affected, emitKind, isPendingEmit, isBuildInfoEmit) {
108687         doneWithAffectedFile(state, affected, emitKind, isPendingEmit, isBuildInfoEmit);
108688         return { result: result, affected: affected };
108689     }
108690     /**
108691      * Gets semantic diagnostics for the file which are
108692      * bindAndCheckDiagnostics (from cache) and program diagnostics
108693      */
108694     function getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken) {
108695         return ts.concatenate(getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken), ts.Debug.checkDefined(state.program).getProgramDiagnostics(sourceFile));
108696     }
108697     /**
108698      * Gets the binder and checker diagnostics either from cache if present, or otherwise from program and caches it
108699      * 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
108700      */
108701     function getBinderAndCheckerDiagnosticsOfFile(state, sourceFile, cancellationToken) {
108702         var path = sourceFile.resolvedPath;
108703         if (state.semanticDiagnosticsPerFile) {
108704             var cachedDiagnostics = state.semanticDiagnosticsPerFile.get(path);
108705             // Report the bind and check diagnostics from the cache if we already have those diagnostics present
108706             if (cachedDiagnostics) {
108707                 return ts.filterSemanticDiagnotics(cachedDiagnostics, state.compilerOptions);
108708             }
108709         }
108710         // Diagnostics werent cached, get them from program, and cache the result
108711         var diagnostics = ts.Debug.checkDefined(state.program).getBindAndCheckDiagnostics(sourceFile, cancellationToken);
108712         if (state.semanticDiagnosticsPerFile) {
108713             state.semanticDiagnosticsPerFile.set(path, diagnostics);
108714         }
108715         return ts.filterSemanticDiagnotics(diagnostics, state.compilerOptions);
108716     }
108717     /**
108718      * Gets the program information to be emitted in buildInfo so that we can use it to create new program
108719      */
108720     function getProgramBuildInfo(state, getCanonicalFileName) {
108721         if (ts.outFile(state.compilerOptions))
108722             return undefined;
108723         var currentDirectory = ts.Debug.checkDefined(state.program).getCurrentDirectory();
108724         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(ts.getTsBuildInfoEmitOutputFilePath(state.compilerOptions), currentDirectory));
108725         var fileInfos = {};
108726         state.fileInfos.forEach(function (value, key) {
108727             var signature = state.currentAffectedFilesSignatures && state.currentAffectedFilesSignatures.get(key);
108728             fileInfos[relativeToBuildInfo(key)] = signature === undefined ? value : { version: value.version, signature: signature, affectsGlobalScope: value.affectsGlobalScope };
108729         });
108730         var result = {
108731             fileInfos: fileInfos,
108732             options: convertToReusableCompilerOptions(state.compilerOptions, relativeToBuildInfoEnsuringAbsolutePath)
108733         };
108734         if (state.referencedMap) {
108735             var referencedMap = {};
108736             for (var _i = 0, _a = ts.arrayFrom(state.referencedMap.keys()).sort(ts.compareStringsCaseSensitive); _i < _a.length; _i++) {
108737                 var key = _a[_i];
108738                 referencedMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.referencedMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
108739             }
108740             result.referencedMap = referencedMap;
108741         }
108742         if (state.exportedModulesMap) {
108743             var exportedModulesMap = {};
108744             for (var _b = 0, _c = ts.arrayFrom(state.exportedModulesMap.keys()).sort(ts.compareStringsCaseSensitive); _b < _c.length; _b++) {
108745                 var key = _c[_b];
108746                 var newValue = state.currentAffectedFilesExportedModulesMap && state.currentAffectedFilesExportedModulesMap.get(key);
108747                 // Not in temporary cache, use existing value
108748                 if (newValue === undefined)
108749                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(state.exportedModulesMap.get(key).keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
108750                 // Value in cache and has updated value map, use that
108751                 else if (newValue)
108752                     exportedModulesMap[relativeToBuildInfo(key)] = ts.arrayFrom(newValue.keys(), relativeToBuildInfo).sort(ts.compareStringsCaseSensitive);
108753             }
108754             result.exportedModulesMap = exportedModulesMap;
108755         }
108756         if (state.semanticDiagnosticsPerFile) {
108757             var semanticDiagnosticsPerFile = [];
108758             for (var _d = 0, _e = ts.arrayFrom(state.semanticDiagnosticsPerFile.keys()).sort(ts.compareStringsCaseSensitive); _d < _e.length; _d++) {
108759                 var key = _e[_d];
108760                 var value = state.semanticDiagnosticsPerFile.get(key);
108761                 semanticDiagnosticsPerFile.push(value.length ?
108762                     [
108763                         relativeToBuildInfo(key),
108764                         state.hasReusableDiagnostic ?
108765                             value :
108766                             convertToReusableDiagnostics(value, relativeToBuildInfo)
108767                     ] :
108768                     relativeToBuildInfo(key));
108769             }
108770             result.semanticDiagnosticsPerFile = semanticDiagnosticsPerFile;
108771         }
108772         if (state.affectedFilesPendingEmit) {
108773             var affectedFilesPendingEmit = [];
108774             var seenFiles = new ts.Set();
108775             for (var _f = 0, _g = state.affectedFilesPendingEmit.slice(state.affectedFilesPendingEmitIndex).sort(ts.compareStringsCaseSensitive); _f < _g.length; _f++) {
108776                 var path = _g[_f];
108777                 if (ts.tryAddToSet(seenFiles, path)) {
108778                     affectedFilesPendingEmit.push([relativeToBuildInfo(path), state.affectedFilesPendingEmitKind.get(path)]);
108779                 }
108780             }
108781             result.affectedFilesPendingEmit = affectedFilesPendingEmit;
108782         }
108783         return result;
108784         function relativeToBuildInfoEnsuringAbsolutePath(path) {
108785             return relativeToBuildInfo(ts.getNormalizedAbsolutePath(path, currentDirectory));
108786         }
108787         function relativeToBuildInfo(path) {
108788             return ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(buildInfoDirectory, path, getCanonicalFileName));
108789         }
108790     }
108791     function convertToReusableCompilerOptions(options, relativeToBuildInfo) {
108792         var result = {};
108793         var optionsNameMap = ts.getOptionsNameMap().optionsNameMap;
108794         for (var name in options) {
108795             if (ts.hasProperty(options, name)) {
108796                 result[name] = convertToReusableCompilerOptionValue(optionsNameMap.get(name.toLowerCase()), options[name], relativeToBuildInfo);
108797             }
108798         }
108799         if (result.configFilePath) {
108800             result.configFilePath = relativeToBuildInfo(result.configFilePath);
108801         }
108802         return result;
108803     }
108804     function convertToReusableCompilerOptionValue(option, value, relativeToBuildInfo) {
108805         if (option) {
108806             if (option.type === "list") {
108807                 var values = value;
108808                 if (option.element.isFilePath && values.length) {
108809                     return values.map(relativeToBuildInfo);
108810                 }
108811             }
108812             else if (option.isFilePath) {
108813                 return relativeToBuildInfo(value);
108814             }
108815         }
108816         return value;
108817     }
108818     function convertToReusableDiagnostics(diagnostics, relativeToBuildInfo) {
108819         ts.Debug.assert(!!diagnostics.length);
108820         return diagnostics.map(function (diagnostic) {
108821             var result = convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo);
108822             result.reportsUnnecessary = diagnostic.reportsUnnecessary;
108823             result.reportDeprecated = diagnostic.reportsDeprecated;
108824             result.source = diagnostic.source;
108825             result.skippedOn = diagnostic.skippedOn;
108826             var relatedInformation = diagnostic.relatedInformation;
108827             result.relatedInformation = relatedInformation ?
108828                 relatedInformation.length ?
108829                     relatedInformation.map(function (r) { return convertToReusableDiagnosticRelatedInformation(r, relativeToBuildInfo); }) :
108830                     [] :
108831                 undefined;
108832             return result;
108833         });
108834     }
108835     function convertToReusableDiagnosticRelatedInformation(diagnostic, relativeToBuildInfo) {
108836         var file = diagnostic.file;
108837         return __assign(__assign({}, diagnostic), { file: file ? relativeToBuildInfo(file.resolvedPath) : undefined });
108838     }
108839     var BuilderProgramKind;
108840     (function (BuilderProgramKind) {
108841         BuilderProgramKind[BuilderProgramKind["SemanticDiagnosticsBuilderProgram"] = 0] = "SemanticDiagnosticsBuilderProgram";
108842         BuilderProgramKind[BuilderProgramKind["EmitAndSemanticDiagnosticsBuilderProgram"] = 1] = "EmitAndSemanticDiagnosticsBuilderProgram";
108843     })(BuilderProgramKind = ts.BuilderProgramKind || (ts.BuilderProgramKind = {}));
108844     function getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
108845         var host;
108846         var newProgram;
108847         var oldProgram;
108848         if (newProgramOrRootNames === undefined) {
108849             ts.Debug.assert(hostOrOptions === undefined);
108850             host = oldProgramOrHost;
108851             oldProgram = configFileParsingDiagnosticsOrOldProgram;
108852             ts.Debug.assert(!!oldProgram);
108853             newProgram = oldProgram.getProgram();
108854         }
108855         else if (ts.isArray(newProgramOrRootNames)) {
108856             oldProgram = configFileParsingDiagnosticsOrOldProgram;
108857             newProgram = ts.createProgram({
108858                 rootNames: newProgramOrRootNames,
108859                 options: hostOrOptions,
108860                 host: oldProgramOrHost,
108861                 oldProgram: oldProgram && oldProgram.getProgramOrUndefined(),
108862                 configFileParsingDiagnostics: configFileParsingDiagnostics,
108863                 projectReferences: projectReferences
108864             });
108865             host = oldProgramOrHost;
108866         }
108867         else {
108868             newProgram = newProgramOrRootNames;
108869             host = hostOrOptions;
108870             oldProgram = oldProgramOrHost;
108871             configFileParsingDiagnostics = configFileParsingDiagnosticsOrOldProgram;
108872         }
108873         return { host: host, newProgram: newProgram, oldProgram: oldProgram, configFileParsingDiagnostics: configFileParsingDiagnostics || ts.emptyArray };
108874     }
108875     ts.getBuilderCreationParameters = getBuilderCreationParameters;
108876     function createBuilderProgram(kind, _a) {
108877         var newProgram = _a.newProgram, host = _a.host, oldProgram = _a.oldProgram, configFileParsingDiagnostics = _a.configFileParsingDiagnostics;
108878         // Return same program if underlying program doesnt change
108879         var oldState = oldProgram && oldProgram.getState();
108880         if (oldState && newProgram === oldState.program && configFileParsingDiagnostics === newProgram.getConfigFileParsingDiagnostics()) {
108881             newProgram = undefined; // TODO: GH#18217
108882             oldState = undefined;
108883             return oldProgram;
108884         }
108885         /**
108886          * Create the canonical file name for identity
108887          */
108888         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
108889         /**
108890          * Computing hash to for signature verification
108891          */
108892         var computeHash = ts.maybeBind(host, host.createHash);
108893         var state = createBuilderProgramState(newProgram, getCanonicalFileName, oldState);
108894         var backupState;
108895         newProgram.getProgramBuildInfo = function () { return getProgramBuildInfo(state, getCanonicalFileName); };
108896         // To ensure that we arent storing any references to old program or new program without state
108897         newProgram = undefined; // TODO: GH#18217
108898         oldProgram = undefined;
108899         oldState = undefined;
108900         var builderProgram = createRedirectedBuilderProgram(state, configFileParsingDiagnostics);
108901         builderProgram.getState = function () { return state; };
108902         builderProgram.backupState = function () {
108903             ts.Debug.assert(backupState === undefined);
108904             backupState = cloneBuilderProgramState(state);
108905         };
108906         builderProgram.restoreState = function () {
108907             state = ts.Debug.checkDefined(backupState);
108908             backupState = undefined;
108909         };
108910         builderProgram.getAllDependencies = function (sourceFile) { return ts.BuilderState.getAllDependencies(state, ts.Debug.checkDefined(state.program), sourceFile); };
108911         builderProgram.getSemanticDiagnostics = getSemanticDiagnostics;
108912         builderProgram.emit = emit;
108913         builderProgram.releaseProgram = function () {
108914             releaseCache(state);
108915             backupState = undefined;
108916         };
108917         if (kind === BuilderProgramKind.SemanticDiagnosticsBuilderProgram) {
108918             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
108919         }
108920         else if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
108921             builderProgram.getSemanticDiagnosticsOfNextAffectedFile = getSemanticDiagnosticsOfNextAffectedFile;
108922             builderProgram.emitNextAffectedFile = emitNextAffectedFile;
108923             builderProgram.emitBuildInfo = emitBuildInfo;
108924         }
108925         else {
108926             ts.notImplemented();
108927         }
108928         return builderProgram;
108929         function emitBuildInfo(writeFile, cancellationToken) {
108930             if (state.buildInfoEmitPending) {
108931                 var result = ts.Debug.checkDefined(state.program).emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken);
108932                 state.buildInfoEmitPending = false;
108933                 return result;
108934             }
108935             return ts.emitSkippedWithNoDiagnostics;
108936         }
108937         /**
108938          * Emits the next affected file's emit result (EmitResult and sourceFiles emitted) or returns undefined if iteration is complete
108939          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
108940          * in that order would be used to write the files
108941          */
108942         function emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
108943             var affected = getNextAffectedFile(state, cancellationToken, computeHash);
108944             var emitKind = 1 /* Full */;
108945             var isPendingEmitFile = false;
108946             if (!affected) {
108947                 if (!ts.outFile(state.compilerOptions)) {
108948                     var pendingAffectedFile = getNextAffectedFilePendingEmit(state);
108949                     if (!pendingAffectedFile) {
108950                         if (!state.buildInfoEmitPending) {
108951                             return undefined;
108952                         }
108953                         var affected_1 = ts.Debug.checkDefined(state.program);
108954                         return toAffectedFileEmitResult(state, 
108955                         // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
108956                         // Otherwise just affected file
108957                         affected_1.emitBuildInfo(writeFile || ts.maybeBind(host, host.writeFile), cancellationToken), affected_1, 1 /* Full */, 
108958                         /*isPendingEmitFile*/ false, 
108959                         /*isBuildInfoEmit*/ true);
108960                     }
108961                     (affected = pendingAffectedFile.affectedFile, emitKind = pendingAffectedFile.emitKind);
108962                     isPendingEmitFile = true;
108963                 }
108964                 else {
108965                     var program = ts.Debug.checkDefined(state.program);
108966                     if (state.programEmitComplete)
108967                         return undefined;
108968                     affected = program;
108969                 }
108970             }
108971             return toAffectedFileEmitResult(state, 
108972             // When whole program is affected, do emit only once (eg when --out or --outFile is specified)
108973             // Otherwise just affected file
108974             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);
108975         }
108976         /**
108977          * Emits the JavaScript and declaration files.
108978          * When targetSource file is specified, emits the files corresponding to that source file,
108979          * otherwise for the whole program.
108980          * In case of EmitAndSemanticDiagnosticsBuilderProgram, when targetSourceFile is specified,
108981          * it is assumed that that file is handled from affected file list. If targetSourceFile is not specified,
108982          * it will only emit all the affected files instead of whole program
108983          *
108984          * The first of writeFile if provided, writeFile of BuilderProgramHost if provided, writeFile of compiler host
108985          * in that order would be used to write the files
108986          */
108987         function emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
108988             var restorePendingEmitOnHandlingNoEmitSuccess = false;
108989             var savedAffectedFilesPendingEmit;
108990             var savedAffectedFilesPendingEmitKind;
108991             var savedAffectedFilesPendingEmitIndex;
108992             // Backup and restore affected pendings emit state for non emit Builder if noEmitOnError is enabled and emitBuildInfo could be written in case there are errors
108993             // This ensures pending files to emit is updated in tsbuildinfo
108994             // Note that when there are no errors, emit proceeds as if everything is emitted as it is callers reponsibility to write the files to disk if at all (because its builder that doesnt track files to emit)
108995             if (kind !== BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram &&
108996                 !targetSourceFile &&
108997                 !ts.outFile(state.compilerOptions) &&
108998                 !state.compilerOptions.noEmit &&
108999                 state.compilerOptions.noEmitOnError) {
109000                 restorePendingEmitOnHandlingNoEmitSuccess = true;
109001                 savedAffectedFilesPendingEmit = state.affectedFilesPendingEmit && state.affectedFilesPendingEmit.slice();
109002                 savedAffectedFilesPendingEmitKind = state.affectedFilesPendingEmitKind && new ts.Map(state.affectedFilesPendingEmitKind);
109003                 savedAffectedFilesPendingEmitIndex = state.affectedFilesPendingEmitIndex;
109004             }
109005             if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
109006                 assertSourceFileOkWithoutNextAffectedCall(state, targetSourceFile);
109007             }
109008             var result = ts.handleNoEmitOptions(builderProgram, targetSourceFile, writeFile, cancellationToken);
109009             if (result)
109010                 return result;
109011             if (restorePendingEmitOnHandlingNoEmitSuccess) {
109012                 state.affectedFilesPendingEmit = savedAffectedFilesPendingEmit;
109013                 state.affectedFilesPendingEmitKind = savedAffectedFilesPendingEmitKind;
109014                 state.affectedFilesPendingEmitIndex = savedAffectedFilesPendingEmitIndex;
109015             }
109016             // Emit only affected files if using builder for emit
109017             if (!targetSourceFile && kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram) {
109018                 // Emit and report any errors we ran into.
109019                 var sourceMaps = [];
109020                 var emitSkipped = false;
109021                 var diagnostics = void 0;
109022                 var emittedFiles = [];
109023                 var affectedEmitResult = void 0;
109024                 while (affectedEmitResult = emitNextAffectedFile(writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers)) {
109025                     emitSkipped = emitSkipped || affectedEmitResult.result.emitSkipped;
109026                     diagnostics = ts.addRange(diagnostics, affectedEmitResult.result.diagnostics);
109027                     emittedFiles = ts.addRange(emittedFiles, affectedEmitResult.result.emittedFiles);
109028                     sourceMaps = ts.addRange(sourceMaps, affectedEmitResult.result.sourceMaps);
109029                 }
109030                 return {
109031                     emitSkipped: emitSkipped,
109032                     diagnostics: diagnostics || ts.emptyArray,
109033                     emittedFiles: emittedFiles,
109034                     sourceMaps: sourceMaps
109035                 };
109036             }
109037             return ts.Debug.checkDefined(state.program).emit(targetSourceFile, writeFile || ts.maybeBind(host, host.writeFile), cancellationToken, emitOnlyDtsFiles, customTransformers);
109038         }
109039         /**
109040          * Return the semantic diagnostics for the next affected file or undefined if iteration is complete
109041          * If provided ignoreSourceFile would be called before getting the diagnostics and would ignore the sourceFile if the returned value was true
109042          */
109043         function getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile) {
109044             while (true) {
109045                 var affected = getNextAffectedFile(state, cancellationToken, computeHash);
109046                 if (!affected) {
109047                     // Done
109048                     return undefined;
109049                 }
109050                 else if (affected === state.program) {
109051                     // When whole program is affected, get all semantic diagnostics (eg when --out or --outFile is specified)
109052                     return toAffectedFileResult(state, state.program.getSemanticDiagnostics(/*targetSourceFile*/ undefined, cancellationToken), affected);
109053                 }
109054                 // Add file to affected file pending emit to handle for later emit time
109055                 // Apart for emit builder do this for tsbuildinfo, do this for non emit builder when noEmit is set as tsbuildinfo is written and reused between emitters
109056                 if (kind === BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram || state.compilerOptions.noEmit || state.compilerOptions.noEmitOnError) {
109057                     addToAffectedFilesPendingEmit(state, affected.resolvedPath, 1 /* Full */);
109058                 }
109059                 // Get diagnostics for the affected file if its not ignored
109060                 if (ignoreSourceFile && ignoreSourceFile(affected)) {
109061                     // Get next affected file
109062                     doneWithAffectedFile(state, affected);
109063                     continue;
109064                 }
109065                 return toAffectedFileResult(state, getSemanticDiagnosticsOfFile(state, affected, cancellationToken), affected);
109066             }
109067         }
109068         /**
109069          * Gets the semantic diagnostics from the program corresponding to this state of file (if provided) or whole program
109070          * The semantic diagnostics are cached and managed here
109071          * Note that it is assumed that when asked about semantic diagnostics through this API,
109072          * the file has been taken out of affected files so it is safe to use cache or get from program and cache the diagnostics
109073          * In case of SemanticDiagnosticsBuilderProgram if the source file is not provided,
109074          * it will iterate through all the affected files, to ensure that cache stays valid and yet provide a way to get all semantic diagnostics
109075          */
109076         function getSemanticDiagnostics(sourceFile, cancellationToken) {
109077             assertSourceFileOkWithoutNextAffectedCall(state, sourceFile);
109078             var compilerOptions = ts.Debug.checkDefined(state.program).getCompilerOptions();
109079             if (ts.outFile(compilerOptions)) {
109080                 ts.Debug.assert(!state.semanticDiagnosticsPerFile);
109081                 // We dont need to cache the diagnostics just return them from program
109082                 return ts.Debug.checkDefined(state.program).getSemanticDiagnostics(sourceFile, cancellationToken);
109083             }
109084             if (sourceFile) {
109085                 return getSemanticDiagnosticsOfFile(state, sourceFile, cancellationToken);
109086             }
109087             // When semantic builder asks for diagnostics of the whole program,
109088             // ensure that all the affected files are handled
109089             // eslint-disable-next-line no-empty
109090             while (getSemanticDiagnosticsOfNextAffectedFile(cancellationToken)) {
109091             }
109092             var diagnostics;
109093             for (var _i = 0, _a = ts.Debug.checkDefined(state.program).getSourceFiles(); _i < _a.length; _i++) {
109094                 var sourceFile_1 = _a[_i];
109095                 diagnostics = ts.addRange(diagnostics, getSemanticDiagnosticsOfFile(state, sourceFile_1, cancellationToken));
109096             }
109097             return diagnostics || ts.emptyArray;
109098         }
109099     }
109100     ts.createBuilderProgram = createBuilderProgram;
109101     function addToAffectedFilesPendingEmit(state, affectedFilePendingEmit, kind) {
109102         if (!state.affectedFilesPendingEmit)
109103             state.affectedFilesPendingEmit = [];
109104         if (!state.affectedFilesPendingEmitKind)
109105             state.affectedFilesPendingEmitKind = new ts.Map();
109106         var existingKind = state.affectedFilesPendingEmitKind.get(affectedFilePendingEmit);
109107         state.affectedFilesPendingEmit.push(affectedFilePendingEmit);
109108         state.affectedFilesPendingEmitKind.set(affectedFilePendingEmit, existingKind || kind);
109109         // affectedFilesPendingEmitIndex === undefined
109110         // - means the emit state.affectedFilesPendingEmit was undefined before adding current affected files
109111         //   so start from 0 as array would be affectedFilesPendingEmit
109112         // else, continue to iterate from existing index, the current set is appended to existing files
109113         if (state.affectedFilesPendingEmitIndex === undefined) {
109114             state.affectedFilesPendingEmitIndex = 0;
109115         }
109116     }
109117     function getMapOfReferencedSet(mapLike, toPath) {
109118         if (!mapLike)
109119             return undefined;
109120         var map = new ts.Map();
109121         // Copies keys/values from template. Note that for..in will not throw if
109122         // template is undefined, and instead will just exit the loop.
109123         for (var key in mapLike) {
109124             if (ts.hasProperty(mapLike, key)) {
109125                 map.set(toPath(key), new ts.Set(mapLike[key].map(toPath)));
109126             }
109127         }
109128         return map;
109129     }
109130     function createBuildProgramUsingProgramBuildInfo(program, buildInfoPath, host) {
109131         var buildInfoDirectory = ts.getDirectoryPath(ts.getNormalizedAbsolutePath(buildInfoPath, host.getCurrentDirectory()));
109132         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
109133         var fileInfos = new ts.Map();
109134         for (var key in program.fileInfos) {
109135             if (ts.hasProperty(program.fileInfos, key)) {
109136                 fileInfos.set(toPath(key), program.fileInfos[key]);
109137             }
109138         }
109139         var state = {
109140             fileInfos: fileInfos,
109141             compilerOptions: ts.convertToOptionsWithAbsolutePaths(program.options, toAbsolutePath),
109142             referencedMap: getMapOfReferencedSet(program.referencedMap, toPath),
109143             exportedModulesMap: getMapOfReferencedSet(program.exportedModulesMap, toPath),
109144             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]; }),
109145             hasReusableDiagnostic: true,
109146             affectedFilesPendingEmit: ts.map(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }),
109147             affectedFilesPendingEmitKind: program.affectedFilesPendingEmit && ts.arrayToMap(program.affectedFilesPendingEmit, function (value) { return toPath(value[0]); }, function (value) { return value[1]; }),
109148             affectedFilesPendingEmitIndex: program.affectedFilesPendingEmit && 0,
109149         };
109150         return {
109151             getState: function () { return state; },
109152             backupState: ts.noop,
109153             restoreState: ts.noop,
109154             getProgram: ts.notImplemented,
109155             getProgramOrUndefined: ts.returnUndefined,
109156             releaseProgram: ts.noop,
109157             getCompilerOptions: function () { return state.compilerOptions; },
109158             getSourceFile: ts.notImplemented,
109159             getSourceFiles: ts.notImplemented,
109160             getOptionsDiagnostics: ts.notImplemented,
109161             getGlobalDiagnostics: ts.notImplemented,
109162             getConfigFileParsingDiagnostics: ts.notImplemented,
109163             getSyntacticDiagnostics: ts.notImplemented,
109164             getDeclarationDiagnostics: ts.notImplemented,
109165             getSemanticDiagnostics: ts.notImplemented,
109166             emit: ts.notImplemented,
109167             getAllDependencies: ts.notImplemented,
109168             getCurrentDirectory: ts.notImplemented,
109169             emitNextAffectedFile: ts.notImplemented,
109170             getSemanticDiagnosticsOfNextAffectedFile: ts.notImplemented,
109171             emitBuildInfo: ts.notImplemented,
109172             close: ts.noop,
109173         };
109174         function toPath(path) {
109175             return ts.toPath(path, buildInfoDirectory, getCanonicalFileName);
109176         }
109177         function toAbsolutePath(path) {
109178             return ts.getNormalizedAbsolutePath(path, buildInfoDirectory);
109179         }
109180     }
109181     ts.createBuildProgramUsingProgramBuildInfo = createBuildProgramUsingProgramBuildInfo;
109182     function createRedirectedBuilderProgram(state, configFileParsingDiagnostics) {
109183         return {
109184             getState: ts.notImplemented,
109185             backupState: ts.noop,
109186             restoreState: ts.noop,
109187             getProgram: getProgram,
109188             getProgramOrUndefined: function () { return state.program; },
109189             releaseProgram: function () { return state.program = undefined; },
109190             getCompilerOptions: function () { return state.compilerOptions; },
109191             getSourceFile: function (fileName) { return getProgram().getSourceFile(fileName); },
109192             getSourceFiles: function () { return getProgram().getSourceFiles(); },
109193             getOptionsDiagnostics: function (cancellationToken) { return getProgram().getOptionsDiagnostics(cancellationToken); },
109194             getGlobalDiagnostics: function (cancellationToken) { return getProgram().getGlobalDiagnostics(cancellationToken); },
109195             getConfigFileParsingDiagnostics: function () { return configFileParsingDiagnostics; },
109196             getSyntacticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSyntacticDiagnostics(sourceFile, cancellationToken); },
109197             getDeclarationDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getDeclarationDiagnostics(sourceFile, cancellationToken); },
109198             getSemanticDiagnostics: function (sourceFile, cancellationToken) { return getProgram().getSemanticDiagnostics(sourceFile, cancellationToken); },
109199             emit: function (sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers) { return getProgram().emit(sourceFile, writeFile, cancellationToken, emitOnlyDts, customTransformers); },
109200             emitBuildInfo: function (writeFile, cancellationToken) { return getProgram().emitBuildInfo(writeFile, cancellationToken); },
109201             getAllDependencies: ts.notImplemented,
109202             getCurrentDirectory: function () { return getProgram().getCurrentDirectory(); },
109203             close: ts.noop,
109204         };
109205         function getProgram() {
109206             return ts.Debug.checkDefined(state.program);
109207         }
109208     }
109209     ts.createRedirectedBuilderProgram = createRedirectedBuilderProgram;
109210 })(ts || (ts = {}));
109211 var ts;
109212 (function (ts) {
109213     function createSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
109214         return ts.createBuilderProgram(ts.BuilderProgramKind.SemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
109215     }
109216     ts.createSemanticDiagnosticsBuilderProgram = createSemanticDiagnosticsBuilderProgram;
109217     function createEmitAndSemanticDiagnosticsBuilderProgram(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
109218         return ts.createBuilderProgram(ts.BuilderProgramKind.EmitAndSemanticDiagnosticsBuilderProgram, ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences));
109219     }
109220     ts.createEmitAndSemanticDiagnosticsBuilderProgram = createEmitAndSemanticDiagnosticsBuilderProgram;
109221     function createAbstractBuilder(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences) {
109222         var _a = ts.getBuilderCreationParameters(newProgramOrRootNames, hostOrOptions, oldProgramOrHost, configFileParsingDiagnosticsOrOldProgram, configFileParsingDiagnostics, projectReferences), newProgram = _a.newProgram, newConfigFileParsingDiagnostics = _a.configFileParsingDiagnostics;
109223         return ts.createRedirectedBuilderProgram({ program: newProgram, compilerOptions: newProgram.getCompilerOptions() }, newConfigFileParsingDiagnostics);
109224     }
109225     ts.createAbstractBuilder = createAbstractBuilder;
109226 })(ts || (ts = {}));
109227 /*@internal*/
109228 var ts;
109229 (function (ts) {
109230     function removeIgnoredPath(path) {
109231         // Consider whole staging folder as if node_modules changed.
109232         if (ts.endsWith(path, "/node_modules/.staging")) {
109233             return ts.removeSuffix(path, "/.staging");
109234         }
109235         return ts.some(ts.ignoredPaths, function (searchPath) { return ts.stringContains(path, searchPath); }) ?
109236             undefined :
109237             path;
109238     }
109239     ts.removeIgnoredPath = removeIgnoredPath;
109240     /**
109241      * Filter out paths like
109242      * "/", "/user", "/user/username", "/user/username/folderAtRoot",
109243      * "c:/", "c:/users", "c:/users/username", "c:/users/username/folderAtRoot", "c:/folderAtRoot"
109244      * @param dirPath
109245      */
109246     function canWatchDirectory(dirPath) {
109247         var rootLength = ts.getRootLength(dirPath);
109248         if (dirPath.length === rootLength) {
109249             // Ignore "/", "c:/"
109250             return false;
109251         }
109252         var nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, rootLength);
109253         if (nextDirectorySeparator === -1) {
109254             // ignore "/user", "c:/users" or "c:/folderAtRoot"
109255             return false;
109256         }
109257         var pathPartForUserCheck = dirPath.substring(rootLength, nextDirectorySeparator + 1);
109258         var isNonDirectorySeparatorRoot = rootLength > 1 || dirPath.charCodeAt(0) !== 47 /* slash */;
109259         if (isNonDirectorySeparatorRoot &&
109260             dirPath.search(/[a-zA-Z]:/) !== 0 && // Non dos style paths
109261             pathPartForUserCheck.search(/[a-zA-z]\$\//) === 0) { // Dos style nextPart
109262             nextDirectorySeparator = dirPath.indexOf(ts.directorySeparator, nextDirectorySeparator + 1);
109263             if (nextDirectorySeparator === -1) {
109264                 // ignore "//vda1cs4850/c$/folderAtRoot"
109265                 return false;
109266             }
109267             pathPartForUserCheck = dirPath.substring(rootLength + pathPartForUserCheck.length, nextDirectorySeparator + 1);
109268         }
109269         if (isNonDirectorySeparatorRoot &&
109270             pathPartForUserCheck.search(/users\//i) !== 0) {
109271             // Paths like c:/folderAtRoot/subFolder are allowed
109272             return true;
109273         }
109274         for (var searchIndex = nextDirectorySeparator + 1, searchLevels = 2; searchLevels > 0; searchLevels--) {
109275             searchIndex = dirPath.indexOf(ts.directorySeparator, searchIndex) + 1;
109276             if (searchIndex === 0) {
109277                 // Folder isnt at expected minimum levels
109278                 return false;
109279             }
109280         }
109281         return true;
109282     }
109283     ts.canWatchDirectory = canWatchDirectory;
109284     function createResolutionCache(resolutionHost, rootDirForResolution, logChangesWhenResolvingModule) {
109285         var filesWithChangedSetOfUnresolvedImports;
109286         var filesWithInvalidatedResolutions;
109287         var filesWithInvalidatedNonRelativeUnresolvedImports;
109288         var nonRelativeExternalModuleResolutions = ts.createMultiMap();
109289         var resolutionsWithFailedLookups = [];
109290         var resolvedFileToResolution = ts.createMultiMap();
109291         var hasChangedAutomaticTypeDirectiveNames = false;
109292         var failedLookupChecks = [];
109293         var startsWithPathChecks = [];
109294         var isInDirectoryChecks = [];
109295         var getCurrentDirectory = ts.memoize(function () { return resolutionHost.getCurrentDirectory(); }); // TODO: GH#18217
109296         var cachedDirectoryStructureHost = resolutionHost.getCachedDirectoryStructureHost();
109297         // The resolvedModuleNames and resolvedTypeReferenceDirectives are the cache of resolutions per file.
109298         // The key in the map is source file's path.
109299         // The values are Map of resolutions with key being name lookedup.
109300         var resolvedModuleNames = new ts.Map();
109301         var perDirectoryResolvedModuleNames = ts.createCacheWithRedirects();
109302         var nonRelativeModuleNameCache = ts.createCacheWithRedirects();
109303         var moduleResolutionCache = ts.createModuleResolutionCacheWithMaps(perDirectoryResolvedModuleNames, nonRelativeModuleNameCache, getCurrentDirectory(), resolutionHost.getCanonicalFileName);
109304         var resolvedTypeReferenceDirectives = new ts.Map();
109305         var perDirectoryResolvedTypeReferenceDirectives = ts.createCacheWithRedirects();
109306         /**
109307          * These are the extensions that failed lookup files will have by default,
109308          * any other extension of failed lookup will be store that path in custom failed lookup path
109309          * This helps in not having to comb through all resolutions when files are added/removed
109310          * Note that .d.ts file also has .d.ts extension hence will be part of default extensions
109311          */
109312         var failedLookupDefaultExtensions = [".ts" /* Ts */, ".tsx" /* Tsx */, ".js" /* Js */, ".jsx" /* Jsx */, ".json" /* Json */];
109313         var customFailedLookupPaths = new ts.Map();
109314         var directoryWatchesOfFailedLookups = new ts.Map();
109315         var rootDir = rootDirForResolution && ts.removeTrailingDirectorySeparator(ts.getNormalizedAbsolutePath(rootDirForResolution, getCurrentDirectory()));
109316         var rootPath = (rootDir && resolutionHost.toPath(rootDir)); // TODO: GH#18217
109317         var rootSplitLength = rootPath !== undefined ? rootPath.split(ts.directorySeparator).length : 0;
109318         // TypeRoot watches for the types that get added as part of getAutomaticTypeDirectiveNames
109319         var typeRootsWatches = new ts.Map();
109320         return {
109321             startRecordingFilesWithChangedResolutions: startRecordingFilesWithChangedResolutions,
109322             finishRecordingFilesWithChangedResolutions: finishRecordingFilesWithChangedResolutions,
109323             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
109324             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
109325             startCachingPerDirectoryResolution: clearPerDirectoryResolutions,
109326             finishCachingPerDirectoryResolution: finishCachingPerDirectoryResolution,
109327             resolveModuleNames: resolveModuleNames,
109328             getResolvedModuleWithFailedLookupLocationsFromCache: getResolvedModuleWithFailedLookupLocationsFromCache,
109329             resolveTypeReferenceDirectives: resolveTypeReferenceDirectives,
109330             removeResolutionsFromProjectReferenceRedirects: removeResolutionsFromProjectReferenceRedirects,
109331             removeResolutionsOfFile: removeResolutionsOfFile,
109332             hasChangedAutomaticTypeDirectiveNames: function () { return hasChangedAutomaticTypeDirectiveNames; },
109333             invalidateResolutionOfFile: invalidateResolutionOfFile,
109334             invalidateResolutionsOfFailedLookupLocations: invalidateResolutionsOfFailedLookupLocations,
109335             setFilesWithInvalidatedNonRelativeUnresolvedImports: setFilesWithInvalidatedNonRelativeUnresolvedImports,
109336             createHasInvalidatedResolution: createHasInvalidatedResolution,
109337             updateTypeRootsWatch: updateTypeRootsWatch,
109338             closeTypeRootsWatch: closeTypeRootsWatch,
109339             clear: clear
109340         };
109341         function getResolvedModule(resolution) {
109342             return resolution.resolvedModule;
109343         }
109344         function getResolvedTypeReferenceDirective(resolution) {
109345             return resolution.resolvedTypeReferenceDirective;
109346         }
109347         function isInDirectoryPath(dir, file) {
109348             if (dir === undefined || file.length <= dir.length) {
109349                 return false;
109350             }
109351             return ts.startsWith(file, dir) && file[dir.length] === ts.directorySeparator;
109352         }
109353         function clear() {
109354             ts.clearMap(directoryWatchesOfFailedLookups, ts.closeFileWatcherOf);
109355             customFailedLookupPaths.clear();
109356             nonRelativeExternalModuleResolutions.clear();
109357             closeTypeRootsWatch();
109358             resolvedModuleNames.clear();
109359             resolvedTypeReferenceDirectives.clear();
109360             resolvedFileToResolution.clear();
109361             resolutionsWithFailedLookups.length = 0;
109362             failedLookupChecks.length = 0;
109363             startsWithPathChecks.length = 0;
109364             isInDirectoryChecks.length = 0;
109365             // perDirectoryResolvedModuleNames and perDirectoryResolvedTypeReferenceDirectives could be non empty if there was exception during program update
109366             // (between startCachingPerDirectoryResolution and finishCachingPerDirectoryResolution)
109367             clearPerDirectoryResolutions();
109368             hasChangedAutomaticTypeDirectiveNames = false;
109369         }
109370         function startRecordingFilesWithChangedResolutions() {
109371             filesWithChangedSetOfUnresolvedImports = [];
109372         }
109373         function finishRecordingFilesWithChangedResolutions() {
109374             var collected = filesWithChangedSetOfUnresolvedImports;
109375             filesWithChangedSetOfUnresolvedImports = undefined;
109376             return collected;
109377         }
109378         function isFileWithInvalidatedNonRelativeUnresolvedImports(path) {
109379             if (!filesWithInvalidatedNonRelativeUnresolvedImports) {
109380                 return false;
109381             }
109382             // Invalidated if file has unresolved imports
109383             var value = filesWithInvalidatedNonRelativeUnresolvedImports.get(path);
109384             return !!value && !!value.length;
109385         }
109386         function createHasInvalidatedResolution(forceAllFilesAsInvalidated) {
109387             // Ensure pending resolutions are applied
109388             invalidateResolutionsOfFailedLookupLocations();
109389             if (forceAllFilesAsInvalidated) {
109390                 // Any file asked would have invalidated resolution
109391                 filesWithInvalidatedResolutions = undefined;
109392                 return ts.returnTrue;
109393             }
109394             var collected = filesWithInvalidatedResolutions;
109395             filesWithInvalidatedResolutions = undefined;
109396             return function (path) { return (!!collected && collected.has(path)) ||
109397                 isFileWithInvalidatedNonRelativeUnresolvedImports(path); };
109398         }
109399         function clearPerDirectoryResolutions() {
109400             perDirectoryResolvedModuleNames.clear();
109401             nonRelativeModuleNameCache.clear();
109402             perDirectoryResolvedTypeReferenceDirectives.clear();
109403             nonRelativeExternalModuleResolutions.forEach(watchFailedLookupLocationOfNonRelativeModuleResolutions);
109404             nonRelativeExternalModuleResolutions.clear();
109405         }
109406         function finishCachingPerDirectoryResolution() {
109407             filesWithInvalidatedNonRelativeUnresolvedImports = undefined;
109408             clearPerDirectoryResolutions();
109409             directoryWatchesOfFailedLookups.forEach(function (watcher, path) {
109410                 if (watcher.refCount === 0) {
109411                     directoryWatchesOfFailedLookups.delete(path);
109412                     watcher.watcher.close();
109413                 }
109414             });
109415             hasChangedAutomaticTypeDirectiveNames = false;
109416         }
109417         function resolveModuleName(moduleName, containingFile, compilerOptions, host, redirectedReference) {
109418             var _a;
109419             var primaryResult = ts.resolveModuleName(moduleName, containingFile, compilerOptions, host, moduleResolutionCache, redirectedReference);
109420             // return result immediately only if global cache support is not enabled or if it is .ts, .tsx or .d.ts
109421             if (!resolutionHost.getGlobalCache) {
109422                 return primaryResult;
109423             }
109424             // otherwise try to load typings from @types
109425             var globalCache = resolutionHost.getGlobalCache();
109426             if (globalCache !== undefined && !ts.isExternalModuleNameRelative(moduleName) && !(primaryResult.resolvedModule && ts.extensionIsTS(primaryResult.resolvedModule.extension))) {
109427                 // create different collection of failed lookup locations for second pass
109428                 // if it will fail and we've already found something during the first pass - we don't want to pollute its results
109429                 var _b = ts.loadModuleFromGlobalCache(ts.Debug.checkDefined(resolutionHost.globalCacheResolutionModuleName)(moduleName), resolutionHost.projectName, compilerOptions, host, globalCache), resolvedModule = _b.resolvedModule, failedLookupLocations = _b.failedLookupLocations;
109430                 if (resolvedModule) {
109431                     // Modify existing resolution so its saved in the directory cache as well
109432                     primaryResult.resolvedModule = resolvedModule;
109433                     (_a = primaryResult.failedLookupLocations).push.apply(_a, failedLookupLocations);
109434                     return primaryResult;
109435                 }
109436             }
109437             // Default return the result from the first pass
109438             return primaryResult;
109439         }
109440         function resolveNamesWithLocalCache(_a) {
109441             var _b;
109442             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;
109443             var path = resolutionHost.toPath(containingFile);
109444             var resolutionsInFile = cache.get(path) || cache.set(path, new ts.Map()).get(path);
109445             var dirPath = ts.getDirectoryPath(path);
109446             var perDirectoryCache = perDirectoryCacheWithRedirects.getOrCreateMapOfCacheRedirects(redirectedReference);
109447             var perDirectoryResolution = perDirectoryCache.get(dirPath);
109448             if (!perDirectoryResolution) {
109449                 perDirectoryResolution = new ts.Map();
109450                 perDirectoryCache.set(dirPath, perDirectoryResolution);
109451             }
109452             var resolvedModules = [];
109453             var compilerOptions = resolutionHost.getCompilationSettings();
109454             var hasInvalidatedNonRelativeUnresolvedImport = logChanges && isFileWithInvalidatedNonRelativeUnresolvedImports(path);
109455             // All the resolutions in this file are invalidated if this file wasnt resolved using same redirect
109456             var program = resolutionHost.getCurrentProgram();
109457             var oldRedirect = program && program.getResolvedProjectReferenceToRedirect(containingFile);
109458             var unmatchedRedirects = oldRedirect ?
109459                 !redirectedReference || redirectedReference.sourceFile.path !== oldRedirect.sourceFile.path :
109460                 !!redirectedReference;
109461             var seenNamesInFile = new ts.Map();
109462             for (var _i = 0, names_3 = names; _i < names_3.length; _i++) {
109463                 var name = names_3[_i];
109464                 var resolution = resolutionsInFile.get(name);
109465                 // Resolution is valid if it is present and not invalidated
109466                 if (!seenNamesInFile.has(name) &&
109467                     unmatchedRedirects || !resolution || resolution.isInvalidated ||
109468                     // If the name is unresolved import that was invalidated, recalculate
109469                     (hasInvalidatedNonRelativeUnresolvedImport && !ts.isExternalModuleNameRelative(name) && shouldRetryResolution(resolution))) {
109470                     var existingResolution = resolution;
109471                     var resolutionInDirectory = perDirectoryResolution.get(name);
109472                     if (resolutionInDirectory) {
109473                         resolution = resolutionInDirectory;
109474                     }
109475                     else {
109476                         resolution = loader(name, containingFile, compilerOptions, ((_b = resolutionHost.getCompilerHost) === null || _b === void 0 ? void 0 : _b.call(resolutionHost)) || resolutionHost, redirectedReference);
109477                         perDirectoryResolution.set(name, resolution);
109478                     }
109479                     resolutionsInFile.set(name, resolution);
109480                     watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, path, getResolutionWithResolvedFileName);
109481                     if (existingResolution) {
109482                         stopWatchFailedLookupLocationOfResolution(existingResolution, path, getResolutionWithResolvedFileName);
109483                     }
109484                     if (logChanges && filesWithChangedSetOfUnresolvedImports && !resolutionIsEqualTo(existingResolution, resolution)) {
109485                         filesWithChangedSetOfUnresolvedImports.push(path);
109486                         // reset log changes to avoid recording the same file multiple times
109487                         logChanges = false;
109488                     }
109489                 }
109490                 ts.Debug.assert(resolution !== undefined && !resolution.isInvalidated);
109491                 seenNamesInFile.set(name, true);
109492                 resolvedModules.push(getResolutionWithResolvedFileName(resolution));
109493             }
109494             // Stop watching and remove the unused name
109495             resolutionsInFile.forEach(function (resolution, name) {
109496                 if (!seenNamesInFile.has(name) && !ts.contains(reusedNames, name)) {
109497                     stopWatchFailedLookupLocationOfResolution(resolution, path, getResolutionWithResolvedFileName);
109498                     resolutionsInFile.delete(name);
109499                 }
109500             });
109501             return resolvedModules;
109502             function resolutionIsEqualTo(oldResolution, newResolution) {
109503                 if (oldResolution === newResolution) {
109504                     return true;
109505                 }
109506                 if (!oldResolution || !newResolution) {
109507                     return false;
109508                 }
109509                 var oldResult = getResolutionWithResolvedFileName(oldResolution);
109510                 var newResult = getResolutionWithResolvedFileName(newResolution);
109511                 if (oldResult === newResult) {
109512                     return true;
109513                 }
109514                 if (!oldResult || !newResult) {
109515                     return false;
109516                 }
109517                 return oldResult.resolvedFileName === newResult.resolvedFileName;
109518             }
109519         }
109520         function resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference) {
109521             return resolveNamesWithLocalCache({
109522                 names: typeDirectiveNames,
109523                 containingFile: containingFile,
109524                 redirectedReference: redirectedReference,
109525                 cache: resolvedTypeReferenceDirectives,
109526                 perDirectoryCacheWithRedirects: perDirectoryResolvedTypeReferenceDirectives,
109527                 loader: ts.resolveTypeReferenceDirective,
109528                 getResolutionWithResolvedFileName: getResolvedTypeReferenceDirective,
109529                 shouldRetryResolution: function (resolution) { return resolution.resolvedTypeReferenceDirective === undefined; },
109530             });
109531         }
109532         function resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference) {
109533             return resolveNamesWithLocalCache({
109534                 names: moduleNames,
109535                 containingFile: containingFile,
109536                 redirectedReference: redirectedReference,
109537                 cache: resolvedModuleNames,
109538                 perDirectoryCacheWithRedirects: perDirectoryResolvedModuleNames,
109539                 loader: resolveModuleName,
109540                 getResolutionWithResolvedFileName: getResolvedModule,
109541                 shouldRetryResolution: function (resolution) { return !resolution.resolvedModule || !ts.resolutionExtensionIsTSOrJson(resolution.resolvedModule.extension); },
109542                 reusedNames: reusedNames,
109543                 logChanges: logChangesWhenResolvingModule,
109544             });
109545         }
109546         function getResolvedModuleWithFailedLookupLocationsFromCache(moduleName, containingFile) {
109547             var cache = resolvedModuleNames.get(resolutionHost.toPath(containingFile));
109548             return cache && cache.get(moduleName);
109549         }
109550         function isNodeModulesAtTypesDirectory(dirPath) {
109551             return ts.endsWith(dirPath, "/node_modules/@types");
109552         }
109553         function getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath) {
109554             if (isInDirectoryPath(rootPath, failedLookupLocationPath)) {
109555                 // Ensure failed look up is normalized path
109556                 failedLookupLocation = ts.isRootedDiskPath(failedLookupLocation) ? ts.normalizePath(failedLookupLocation) : ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory());
109557                 var failedLookupPathSplit = failedLookupLocationPath.split(ts.directorySeparator);
109558                 var failedLookupSplit = failedLookupLocation.split(ts.directorySeparator);
109559                 ts.Debug.assert(failedLookupSplit.length === failedLookupPathSplit.length, "FailedLookup: " + failedLookupLocation + " failedLookupLocationPath: " + failedLookupLocationPath);
109560                 if (failedLookupPathSplit.length > rootSplitLength + 1) {
109561                     // Instead of watching root, watch directory in root to avoid watching excluded directories not needed for module resolution
109562                     return {
109563                         dir: failedLookupSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator),
109564                         dirPath: failedLookupPathSplit.slice(0, rootSplitLength + 1).join(ts.directorySeparator)
109565                     };
109566                 }
109567                 else {
109568                     // Always watch root directory non recursively
109569                     return {
109570                         dir: rootDir,
109571                         dirPath: rootPath,
109572                         nonRecursive: false
109573                     };
109574                 }
109575             }
109576             return getDirectoryToWatchFromFailedLookupLocationDirectory(ts.getDirectoryPath(ts.getNormalizedAbsolutePath(failedLookupLocation, getCurrentDirectory())), ts.getDirectoryPath(failedLookupLocationPath));
109577         }
109578         function getDirectoryToWatchFromFailedLookupLocationDirectory(dir, dirPath) {
109579             // If directory path contains node module, get the most parent node_modules directory for watching
109580             while (ts.pathContainsNodeModules(dirPath)) {
109581                 dir = ts.getDirectoryPath(dir);
109582                 dirPath = ts.getDirectoryPath(dirPath);
109583             }
109584             // If the directory is node_modules use it to watch, always watch it recursively
109585             if (ts.isNodeModulesDirectory(dirPath)) {
109586                 return canWatchDirectory(ts.getDirectoryPath(dirPath)) ? { dir: dir, dirPath: dirPath } : undefined;
109587             }
109588             var nonRecursive = true;
109589             // Use some ancestor of the root directory
109590             var subDirectoryPath, subDirectory;
109591             if (rootPath !== undefined) {
109592                 while (!isInDirectoryPath(dirPath, rootPath)) {
109593                     var parentPath = ts.getDirectoryPath(dirPath);
109594                     if (parentPath === dirPath) {
109595                         break;
109596                     }
109597                     nonRecursive = false;
109598                     subDirectoryPath = dirPath;
109599                     subDirectory = dir;
109600                     dirPath = parentPath;
109601                     dir = ts.getDirectoryPath(dir);
109602                 }
109603             }
109604             return canWatchDirectory(dirPath) ? { dir: subDirectory || dir, dirPath: subDirectoryPath || dirPath, nonRecursive: nonRecursive } : undefined;
109605         }
109606         function isPathWithDefaultFailedLookupExtension(path) {
109607             return ts.fileExtensionIsOneOf(path, failedLookupDefaultExtensions);
109608         }
109609         function watchFailedLookupLocationsOfExternalModuleResolutions(name, resolution, filePath, getResolutionWithResolvedFileName) {
109610             if (resolution.refCount) {
109611                 resolution.refCount++;
109612                 ts.Debug.assertDefined(resolution.files);
109613             }
109614             else {
109615                 resolution.refCount = 1;
109616                 ts.Debug.assert(ts.length(resolution.files) === 0); // This resolution shouldnt be referenced by any file yet
109617                 if (ts.isExternalModuleNameRelative(name)) {
109618                     watchFailedLookupLocationOfResolution(resolution);
109619                 }
109620                 else {
109621                     nonRelativeExternalModuleResolutions.add(name, resolution);
109622                 }
109623                 var resolved = getResolutionWithResolvedFileName(resolution);
109624                 if (resolved && resolved.resolvedFileName) {
109625                     resolvedFileToResolution.add(resolutionHost.toPath(resolved.resolvedFileName), resolution);
109626                 }
109627             }
109628             (resolution.files || (resolution.files = [])).push(filePath);
109629         }
109630         function watchFailedLookupLocationOfResolution(resolution) {
109631             ts.Debug.assert(!!resolution.refCount);
109632             var failedLookupLocations = resolution.failedLookupLocations;
109633             if (!failedLookupLocations.length)
109634                 return;
109635             resolutionsWithFailedLookups.push(resolution);
109636             var setAtRoot = false;
109637             for (var _i = 0, failedLookupLocations_1 = failedLookupLocations; _i < failedLookupLocations_1.length; _i++) {
109638                 var failedLookupLocation = failedLookupLocations_1[_i];
109639                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
109640                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
109641                 if (toWatch) {
109642                     var dir = toWatch.dir, dirPath = toWatch.dirPath, nonRecursive = toWatch.nonRecursive;
109643                     // If the failed lookup location path is not one of the supported extensions,
109644                     // store it in the custom path
109645                     if (!isPathWithDefaultFailedLookupExtension(failedLookupLocationPath)) {
109646                         var refCount = customFailedLookupPaths.get(failedLookupLocationPath) || 0;
109647                         customFailedLookupPaths.set(failedLookupLocationPath, refCount + 1);
109648                     }
109649                     if (dirPath === rootPath) {
109650                         ts.Debug.assert(!nonRecursive);
109651                         setAtRoot = true;
109652                     }
109653                     else {
109654                         setDirectoryWatcher(dir, dirPath, nonRecursive);
109655                     }
109656                 }
109657             }
109658             if (setAtRoot) {
109659                 // This is always non recursive
109660                 setDirectoryWatcher(rootDir, rootPath, /*nonRecursive*/ true); // TODO: GH#18217
109661             }
109662         }
109663         function watchFailedLookupLocationOfNonRelativeModuleResolutions(resolutions, name) {
109664             var program = resolutionHost.getCurrentProgram();
109665             if (!program || !program.getTypeChecker().tryFindAmbientModuleWithoutAugmentations(name)) {
109666                 resolutions.forEach(watchFailedLookupLocationOfResolution);
109667             }
109668         }
109669         function setDirectoryWatcher(dir, dirPath, nonRecursive) {
109670             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
109671             if (dirWatcher) {
109672                 ts.Debug.assert(!!nonRecursive === !!dirWatcher.nonRecursive);
109673                 dirWatcher.refCount++;
109674             }
109675             else {
109676                 directoryWatchesOfFailedLookups.set(dirPath, { watcher: createDirectoryWatcher(dir, dirPath, nonRecursive), refCount: 1, nonRecursive: nonRecursive });
109677             }
109678         }
109679         function stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName) {
109680             ts.unorderedRemoveItem(ts.Debug.assertDefined(resolution.files), filePath);
109681             resolution.refCount--;
109682             if (resolution.refCount) {
109683                 return;
109684             }
109685             var resolved = getResolutionWithResolvedFileName(resolution);
109686             if (resolved && resolved.resolvedFileName) {
109687                 resolvedFileToResolution.remove(resolutionHost.toPath(resolved.resolvedFileName), resolution);
109688             }
109689             if (!ts.unorderedRemoveItem(resolutionsWithFailedLookups, resolution)) {
109690                 // If not watching failed lookups, it wont be there in resolutionsWithFailedLookups
109691                 return;
109692             }
109693             var failedLookupLocations = resolution.failedLookupLocations;
109694             var removeAtRoot = false;
109695             for (var _i = 0, failedLookupLocations_2 = failedLookupLocations; _i < failedLookupLocations_2.length; _i++) {
109696                 var failedLookupLocation = failedLookupLocations_2[_i];
109697                 var failedLookupLocationPath = resolutionHost.toPath(failedLookupLocation);
109698                 var toWatch = getDirectoryToWatchFailedLookupLocation(failedLookupLocation, failedLookupLocationPath);
109699                 if (toWatch) {
109700                     var dirPath = toWatch.dirPath;
109701                     var refCount = customFailedLookupPaths.get(failedLookupLocationPath);
109702                     if (refCount) {
109703                         if (refCount === 1) {
109704                             customFailedLookupPaths.delete(failedLookupLocationPath);
109705                         }
109706                         else {
109707                             ts.Debug.assert(refCount > 1);
109708                             customFailedLookupPaths.set(failedLookupLocationPath, refCount - 1);
109709                         }
109710                     }
109711                     if (dirPath === rootPath) {
109712                         removeAtRoot = true;
109713                     }
109714                     else {
109715                         removeDirectoryWatcher(dirPath);
109716                     }
109717                 }
109718             }
109719             if (removeAtRoot) {
109720                 removeDirectoryWatcher(rootPath);
109721             }
109722         }
109723         function removeDirectoryWatcher(dirPath) {
109724             var dirWatcher = directoryWatchesOfFailedLookups.get(dirPath);
109725             // Do not close the watcher yet since it might be needed by other failed lookup locations.
109726             dirWatcher.refCount--;
109727         }
109728         function createDirectoryWatcher(directory, dirPath, nonRecursive) {
109729             return resolutionHost.watchDirectoryOfFailedLookupLocation(directory, function (fileOrDirectory) {
109730                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
109731                 if (cachedDirectoryStructureHost) {
109732                     // Since the file existence changed, update the sourceFiles cache
109733                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
109734                 }
109735                 scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
109736             }, nonRecursive ? 0 /* None */ : 1 /* Recursive */);
109737         }
109738         function removeResolutionsOfFileFromCache(cache, filePath, getResolutionWithResolvedFileName) {
109739             // Deleted file, stop watching failed lookups for all the resolutions in the file
109740             var resolutions = cache.get(filePath);
109741             if (resolutions) {
109742                 resolutions.forEach(function (resolution) { return stopWatchFailedLookupLocationOfResolution(resolution, filePath, getResolutionWithResolvedFileName); });
109743                 cache.delete(filePath);
109744             }
109745         }
109746         function removeResolutionsFromProjectReferenceRedirects(filePath) {
109747             if (!ts.fileExtensionIs(filePath, ".json" /* Json */)) {
109748                 return;
109749             }
109750             var program = resolutionHost.getCurrentProgram();
109751             if (!program) {
109752                 return;
109753             }
109754             // If this file is input file for the referenced project, get it
109755             var resolvedProjectReference = program.getResolvedProjectReferenceByPath(filePath);
109756             if (!resolvedProjectReference) {
109757                 return;
109758             }
109759             // filePath is for the projectReference and the containing file is from this project reference, invalidate the resolution
109760             resolvedProjectReference.commandLine.fileNames.forEach(function (f) { return removeResolutionsOfFile(resolutionHost.toPath(f)); });
109761         }
109762         function removeResolutionsOfFile(filePath) {
109763             removeResolutionsOfFileFromCache(resolvedModuleNames, filePath, getResolvedModule);
109764             removeResolutionsOfFileFromCache(resolvedTypeReferenceDirectives, filePath, getResolvedTypeReferenceDirective);
109765         }
109766         function invalidateResolutions(resolutions, canInvalidate) {
109767             if (!resolutions)
109768                 return false;
109769             var invalidated = false;
109770             for (var _i = 0, resolutions_1 = resolutions; _i < resolutions_1.length; _i++) {
109771                 var resolution = resolutions_1[_i];
109772                 if (resolution.isInvalidated || !canInvalidate(resolution))
109773                     continue;
109774                 resolution.isInvalidated = invalidated = true;
109775                 for (var _a = 0, _b = ts.Debug.assertDefined(resolution.files); _a < _b.length; _a++) {
109776                     var containingFilePath = _b[_a];
109777                     (filesWithInvalidatedResolutions || (filesWithInvalidatedResolutions = new ts.Set())).add(containingFilePath);
109778                     // When its a file with inferred types resolution, invalidate type reference directive resolution
109779                     hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames || ts.endsWith(containingFilePath, ts.inferredTypesContainingFile);
109780                 }
109781             }
109782             return invalidated;
109783         }
109784         function invalidateResolutionOfFile(filePath) {
109785             removeResolutionsOfFile(filePath);
109786             // Resolution is invalidated if the resulting file name is same as the deleted file path
109787             var prevHasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
109788             if (invalidateResolutions(resolvedFileToResolution.get(filePath), ts.returnTrue) &&
109789                 hasChangedAutomaticTypeDirectiveNames &&
109790                 !prevHasChangedAutomaticTypeDirectiveNames) {
109791                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
109792             }
109793         }
109794         function setFilesWithInvalidatedNonRelativeUnresolvedImports(filesMap) {
109795             ts.Debug.assert(filesWithInvalidatedNonRelativeUnresolvedImports === filesMap || filesWithInvalidatedNonRelativeUnresolvedImports === undefined);
109796             filesWithInvalidatedNonRelativeUnresolvedImports = filesMap;
109797         }
109798         function scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, isCreatingWatchedDirectory) {
109799             if (isCreatingWatchedDirectory) {
109800                 // Watching directory is created
109801                 // Invalidate any resolution has failed lookup in this directory
109802                 isInDirectoryChecks.push(fileOrDirectoryPath);
109803             }
109804             else {
109805                 // If something to do with folder/file starting with "." in node_modules folder, skip it
109806                 var updatedPath = removeIgnoredPath(fileOrDirectoryPath);
109807                 if (!updatedPath)
109808                     return false;
109809                 fileOrDirectoryPath = updatedPath;
109810                 // prevent saving an open file from over-eagerly triggering invalidation
109811                 if (resolutionHost.fileIsOpen(fileOrDirectoryPath)) {
109812                     return false;
109813                 }
109814                 // Some file or directory in the watching directory is created
109815                 // Return early if it does not have any of the watching extension or not the custom failed lookup path
109816                 var dirOfFileOrDirectory = ts.getDirectoryPath(fileOrDirectoryPath);
109817                 if (isNodeModulesAtTypesDirectory(fileOrDirectoryPath) || ts.isNodeModulesDirectory(fileOrDirectoryPath) ||
109818                     isNodeModulesAtTypesDirectory(dirOfFileOrDirectory) || ts.isNodeModulesDirectory(dirOfFileOrDirectory)) {
109819                     // Invalidate any resolution from this directory
109820                     failedLookupChecks.push(fileOrDirectoryPath);
109821                     startsWithPathChecks.push(fileOrDirectoryPath);
109822                 }
109823                 else {
109824                     if (!isPathWithDefaultFailedLookupExtension(fileOrDirectoryPath) && !customFailedLookupPaths.has(fileOrDirectoryPath)) {
109825                         return false;
109826                     }
109827                     // Ignore emits from the program
109828                     if (ts.isEmittedFileOfProgram(resolutionHost.getCurrentProgram(), fileOrDirectoryPath)) {
109829                         return false;
109830                     }
109831                     // Resolution need to be invalidated if failed lookup location is same as the file or directory getting created
109832                     failedLookupChecks.push(fileOrDirectoryPath);
109833                 }
109834             }
109835             resolutionHost.scheduleInvalidateResolutionsOfFailedLookupLocations();
109836         }
109837         function invalidateResolutionsOfFailedLookupLocations() {
109838             if (!failedLookupChecks.length && !startsWithPathChecks.length && !isInDirectoryChecks.length) {
109839                 return false;
109840             }
109841             var invalidated = invalidateResolutions(resolutionsWithFailedLookups, canInvalidateFailedLookupResolution);
109842             failedLookupChecks.length = 0;
109843             startsWithPathChecks.length = 0;
109844             isInDirectoryChecks.length = 0;
109845             return invalidated;
109846         }
109847         function canInvalidateFailedLookupResolution(resolution) {
109848             return resolution.failedLookupLocations.some(function (location) {
109849                 var locationPath = resolutionHost.toPath(location);
109850                 return ts.contains(failedLookupChecks, locationPath) ||
109851                     startsWithPathChecks.some(function (fileOrDirectoryPath) { return ts.startsWith(locationPath, fileOrDirectoryPath); }) ||
109852                     isInDirectoryChecks.some(function (fileOrDirectoryPath) { return isInDirectoryPath(fileOrDirectoryPath, locationPath); });
109853             });
109854         }
109855         function closeTypeRootsWatch() {
109856             ts.clearMap(typeRootsWatches, ts.closeFileWatcher);
109857         }
109858         function getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath) {
109859             if (isInDirectoryPath(rootPath, typeRootPath)) {
109860                 return rootPath;
109861             }
109862             var toWatch = getDirectoryToWatchFromFailedLookupLocationDirectory(typeRoot, typeRootPath);
109863             return toWatch && directoryWatchesOfFailedLookups.has(toWatch.dirPath) ? toWatch.dirPath : undefined;
109864         }
109865         function createTypeRootsWatch(typeRootPath, typeRoot) {
109866             // Create new watch and recursive info
109867             return resolutionHost.watchTypeRootsDirectory(typeRoot, function (fileOrDirectory) {
109868                 var fileOrDirectoryPath = resolutionHost.toPath(fileOrDirectory);
109869                 if (cachedDirectoryStructureHost) {
109870                     // Since the file existence changed, update the sourceFiles cache
109871                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
109872                 }
109873                 // For now just recompile
109874                 // We could potentially store more data here about whether it was/would be really be used or not
109875                 // and with that determine to trigger compilation but for now this is enough
109876                 hasChangedAutomaticTypeDirectiveNames = true;
109877                 resolutionHost.onChangedAutomaticTypeDirectiveNames();
109878                 // Since directory watchers invoked are flaky, the failed lookup location events might not be triggered
109879                 // So handle to failed lookup locations here as well to ensure we are invalidating resolutions
109880                 var dirPath = getDirectoryToWatchFailedLookupLocationFromTypeRoot(typeRoot, typeRootPath);
109881                 if (dirPath) {
109882                     scheduleInvalidateResolutionOfFailedLookupLocation(fileOrDirectoryPath, dirPath === fileOrDirectoryPath);
109883                 }
109884             }, 1 /* Recursive */);
109885         }
109886         /**
109887          * Watches the types that would get added as part of getAutomaticTypeDirectiveNames
109888          * To be called when compiler options change
109889          */
109890         function updateTypeRootsWatch() {
109891             var options = resolutionHost.getCompilationSettings();
109892             if (options.types) {
109893                 // No need to do any watch since resolution cache is going to handle the failed lookups
109894                 // for the types added by this
109895                 closeTypeRootsWatch();
109896                 return;
109897             }
109898             // we need to assume the directories exist to ensure that we can get all the type root directories that get included
109899             // But filter directories that are at root level to say directory doesnt exist, so that we arent watching them
109900             var typeRoots = ts.getEffectiveTypeRoots(options, { directoryExists: directoryExistsForTypeRootWatch, getCurrentDirectory: getCurrentDirectory });
109901             if (typeRoots) {
109902                 ts.mutateMap(typeRootsWatches, ts.arrayToMap(typeRoots, function (tr) { return resolutionHost.toPath(tr); }), {
109903                     createNewValue: createTypeRootsWatch,
109904                     onDeleteValue: ts.closeFileWatcher
109905                 });
109906             }
109907             else {
109908                 closeTypeRootsWatch();
109909             }
109910         }
109911         /**
109912          * Use this function to return if directory exists to get type roots to watch
109913          * If we return directory exists then only the paths will be added to type roots
109914          * Hence return true for all directories except root directories which are filtered from watching
109915          */
109916         function directoryExistsForTypeRootWatch(nodeTypesDirectory) {
109917             var dir = ts.getDirectoryPath(ts.getDirectoryPath(nodeTypesDirectory));
109918             var dirPath = resolutionHost.toPath(dir);
109919             return dirPath === rootPath || canWatchDirectory(dirPath);
109920         }
109921     }
109922     ts.createResolutionCache = createResolutionCache;
109923 })(ts || (ts = {}));
109924 // Used by importFixes, getEditsForFileRename, and declaration emit to synthesize import module specifiers.
109925 /* @internal */
109926 var ts;
109927 (function (ts) {
109928     var moduleSpecifiers;
109929     (function (moduleSpecifiers) {
109930         var RelativePreference;
109931         (function (RelativePreference) {
109932             RelativePreference[RelativePreference["Relative"] = 0] = "Relative";
109933             RelativePreference[RelativePreference["NonRelative"] = 1] = "NonRelative";
109934             RelativePreference[RelativePreference["Auto"] = 2] = "Auto";
109935         })(RelativePreference || (RelativePreference = {}));
109936         // See UserPreferences#importPathEnding
109937         var Ending;
109938         (function (Ending) {
109939             Ending[Ending["Minimal"] = 0] = "Minimal";
109940             Ending[Ending["Index"] = 1] = "Index";
109941             Ending[Ending["JsExtension"] = 2] = "JsExtension";
109942         })(Ending || (Ending = {}));
109943         function getPreferences(_a, compilerOptions, importingSourceFile) {
109944             var importModuleSpecifierPreference = _a.importModuleSpecifierPreference, importModuleSpecifierEnding = _a.importModuleSpecifierEnding;
109945             return {
109946                 relativePreference: importModuleSpecifierPreference === "relative" ? 0 /* Relative */ : importModuleSpecifierPreference === "non-relative" ? 1 /* NonRelative */ : 2 /* Auto */,
109947                 ending: getEnding(),
109948             };
109949             function getEnding() {
109950                 switch (importModuleSpecifierEnding) {
109951                     case "minimal": return 0 /* Minimal */;
109952                     case "index": return 1 /* Index */;
109953                     case "js": return 2 /* JsExtension */;
109954                     default: return usesJsExtensionOnImports(importingSourceFile) ? 2 /* JsExtension */
109955                         : ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs ? 1 /* Index */ : 0 /* Minimal */;
109956                 }
109957             }
109958         }
109959         function getPreferencesForUpdate(compilerOptions, oldImportSpecifier) {
109960             return {
109961                 relativePreference: ts.isExternalModuleNameRelative(oldImportSpecifier) ? 0 /* Relative */ : 1 /* NonRelative */,
109962                 ending: ts.hasJSFileExtension(oldImportSpecifier) ?
109963                     2 /* JsExtension */ :
109964                     ts.getEmitModuleResolutionKind(compilerOptions) !== ts.ModuleResolutionKind.NodeJs || ts.endsWith(oldImportSpecifier, "index") ? 1 /* Index */ : 0 /* Minimal */,
109965             };
109966         }
109967         function updateModuleSpecifier(compilerOptions, importingSourceFileName, toFileName, host, oldImportSpecifier) {
109968             var res = getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferencesForUpdate(compilerOptions, oldImportSpecifier));
109969             if (res === oldImportSpecifier)
109970                 return undefined;
109971             return res;
109972         }
109973         moduleSpecifiers.updateModuleSpecifier = updateModuleSpecifier;
109974         // Note: importingSourceFile is just for usesJsExtensionOnImports
109975         function getModuleSpecifier(compilerOptions, importingSourceFile, importingSourceFileName, toFileName, host, preferences) {
109976             if (preferences === void 0) { preferences = {}; }
109977             return getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, getPreferences(preferences, compilerOptions, importingSourceFile));
109978         }
109979         moduleSpecifiers.getModuleSpecifier = getModuleSpecifier;
109980         function getNodeModulesPackageName(compilerOptions, importingSourceFileName, nodeModulesFileName, host) {
109981             var info = getInfo(importingSourceFileName, host);
109982             var modulePaths = getAllModulePaths(importingSourceFileName, nodeModulesFileName, host);
109983             return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions, /*packageNameOnly*/ true); });
109984         }
109985         moduleSpecifiers.getNodeModulesPackageName = getNodeModulesPackageName;
109986         function getModuleSpecifierWorker(compilerOptions, importingSourceFileName, toFileName, host, preferences) {
109987             var info = getInfo(importingSourceFileName, host);
109988             var modulePaths = getAllModulePaths(importingSourceFileName, toFileName, host);
109989             return ts.firstDefined(modulePaths, function (modulePath) { return tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions); }) ||
109990                 getLocalModuleSpecifier(toFileName, info, compilerOptions, host, preferences);
109991         }
109992         /** Returns an import for each symlink and for the realpath. */
109993         function getModuleSpecifiers(moduleSymbol, compilerOptions, importingSourceFile, host, userPreferences) {
109994             var ambient = tryGetModuleNameFromAmbientModule(moduleSymbol);
109995             if (ambient)
109996                 return [ambient];
109997             var info = getInfo(importingSourceFile.path, host);
109998             var moduleSourceFile = ts.getSourceFileOfNode(moduleSymbol.valueDeclaration || ts.getNonAugmentationDeclaration(moduleSymbol));
109999             var modulePaths = getAllModulePaths(importingSourceFile.path, moduleSourceFile.originalFileName, host);
110000             var preferences = getPreferences(userPreferences, compilerOptions, importingSourceFile);
110001             var importedFileIsInNodeModules = ts.some(modulePaths, function (p) { return p.isInNodeModules; });
110002             // Module specifier priority:
110003             //   1. "Bare package specifiers" (e.g. "@foo/bar") resulting from a path through node_modules to a package.json's "types" entry
110004             //   2. Specifiers generated using "paths" from tsconfig
110005             //   3. Non-relative specfiers resulting from a path through node_modules (e.g. "@foo/bar/path/to/file")
110006             //   4. Relative paths
110007             var nodeModulesSpecifiers;
110008             var pathsSpecifiers;
110009             var relativeSpecifiers;
110010             for (var _i = 0, modulePaths_1 = modulePaths; _i < modulePaths_1.length; _i++) {
110011                 var modulePath = modulePaths_1[_i];
110012                 var specifier = tryGetModuleNameAsNodeModule(modulePath, info, host, compilerOptions);
110013                 nodeModulesSpecifiers = ts.append(nodeModulesSpecifiers, specifier);
110014                 if (specifier && modulePath.isRedirect) {
110015                     // If we got a specifier for a redirect, it was a bare package specifier (e.g. "@foo/bar",
110016                     // not "@foo/bar/path/to/file"). No other specifier will be this good, so stop looking.
110017                     return nodeModulesSpecifiers;
110018                 }
110019                 if (!specifier && !modulePath.isRedirect) {
110020                     var local = getLocalModuleSpecifier(modulePath.path, info, compilerOptions, host, preferences);
110021                     if (ts.pathIsBareSpecifier(local)) {
110022                         pathsSpecifiers = ts.append(pathsSpecifiers, local);
110023                     }
110024                     else if (!importedFileIsInNodeModules || modulePath.isInNodeModules) {
110025                         // Why this extra conditional, not just an `else`? If some path to the file contained
110026                         // 'node_modules', but we can't create a non-relative specifier (e.g. "@foo/bar/path/to/file"),
110027                         // that means we had to go through a *sibling's* node_modules, not one we can access directly.
110028                         // If some path to the file was in node_modules but another was not, this likely indicates that
110029                         // we have a monorepo structure with symlinks. In this case, the non-node_modules path is
110030                         // probably the realpath, e.g. "../bar/path/to/file", but a relative path to another package
110031                         // in a monorepo is probably not portable. So, the module specifier we actually go with will be
110032                         // the relative path through node_modules, so that the declaration emitter can produce a
110033                         // portability error. (See declarationEmitReexportedSymlinkReference3)
110034                         relativeSpecifiers = ts.append(relativeSpecifiers, local);
110035                     }
110036                 }
110037             }
110038             return (pathsSpecifiers === null || pathsSpecifiers === void 0 ? void 0 : pathsSpecifiers.length) ? pathsSpecifiers :
110039                 (nodeModulesSpecifiers === null || nodeModulesSpecifiers === void 0 ? void 0 : nodeModulesSpecifiers.length) ? nodeModulesSpecifiers :
110040                     ts.Debug.checkDefined(relativeSpecifiers);
110041         }
110042         moduleSpecifiers.getModuleSpecifiers = getModuleSpecifiers;
110043         // importingSourceFileName is separate because getEditsForFileRename may need to specify an updated path
110044         function getInfo(importingSourceFileName, host) {
110045             var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames ? host.useCaseSensitiveFileNames() : true);
110046             var sourceDirectory = ts.getDirectoryPath(importingSourceFileName);
110047             return { getCanonicalFileName: getCanonicalFileName, sourceDirectory: sourceDirectory };
110048         }
110049         function getLocalModuleSpecifier(moduleFileName, _a, compilerOptions, host, _b) {
110050             var getCanonicalFileName = _a.getCanonicalFileName, sourceDirectory = _a.sourceDirectory;
110051             var ending = _b.ending, relativePreference = _b.relativePreference;
110052             var baseUrl = compilerOptions.baseUrl, paths = compilerOptions.paths, rootDirs = compilerOptions.rootDirs;
110053             var relativePath = rootDirs && tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) ||
110054                 removeExtensionAndIndexPostFix(ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(sourceDirectory, moduleFileName, getCanonicalFileName)), ending, compilerOptions);
110055             if (!baseUrl && !paths || relativePreference === 0 /* Relative */) {
110056                 return relativePath;
110057             }
110058             var baseDirectory = ts.getPathsBasePath(compilerOptions, host) || baseUrl;
110059             var relativeToBaseUrl = getRelativePathIfInDirectory(moduleFileName, baseDirectory, getCanonicalFileName);
110060             if (!relativeToBaseUrl) {
110061                 return relativePath;
110062             }
110063             var importRelativeToBaseUrl = removeExtensionAndIndexPostFix(relativeToBaseUrl, ending, compilerOptions);
110064             var fromPaths = paths && tryGetModuleNameFromPaths(ts.removeFileExtension(relativeToBaseUrl), importRelativeToBaseUrl, paths);
110065             var nonRelative = fromPaths === undefined && baseUrl !== undefined ? importRelativeToBaseUrl : fromPaths;
110066             if (!nonRelative) {
110067                 return relativePath;
110068             }
110069             if (relativePreference === 1 /* NonRelative */) {
110070                 return nonRelative;
110071             }
110072             if (relativePreference !== 2 /* Auto */)
110073                 ts.Debug.assertNever(relativePreference);
110074             // Prefer a relative import over a baseUrl import if it has fewer components.
110075             return isPathRelativeToParent(nonRelative) || countPathComponents(relativePath) < countPathComponents(nonRelative) ? relativePath : nonRelative;
110076         }
110077         function countPathComponents(path) {
110078             var count = 0;
110079             for (var i = ts.startsWith(path, "./") ? 2 : 0; i < path.length; i++) {
110080                 if (path.charCodeAt(i) === 47 /* slash */)
110081                     count++;
110082             }
110083             return count;
110084         }
110085         moduleSpecifiers.countPathComponents = countPathComponents;
110086         function usesJsExtensionOnImports(_a) {
110087             var imports = _a.imports;
110088             return ts.firstDefined(imports, function (_a) {
110089                 var text = _a.text;
110090                 return ts.pathIsRelative(text) ? ts.hasJSFileExtension(text) : undefined;
110091             }) || false;
110092         }
110093         function numberOfDirectorySeparators(str) {
110094             var match = str.match(/\//g);
110095             return match ? match.length : 0;
110096         }
110097         function comparePathsByRedirectAndNumberOfDirectorySeparators(a, b) {
110098             return ts.compareBooleans(b.isRedirect, a.isRedirect) || ts.compareValues(numberOfDirectorySeparators(a.path), numberOfDirectorySeparators(b.path));
110099         }
110100         function forEachFileNameOfModule(importingFileName, importedFileName, host, preferSymlinks, cb) {
110101             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
110102             var cwd = host.getCurrentDirectory();
110103             var referenceRedirect = host.isSourceOfProjectReferenceRedirect(importedFileName) ? host.getProjectReferenceRedirect(importedFileName) : undefined;
110104             var redirects = host.redirectTargetsMap.get(ts.toPath(importedFileName, cwd, getCanonicalFileName)) || ts.emptyArray;
110105             var importedFileNames = __spreadArrays((referenceRedirect ? [referenceRedirect] : ts.emptyArray), [importedFileName], redirects);
110106             var targets = importedFileNames.map(function (f) { return ts.getNormalizedAbsolutePath(f, cwd); });
110107             if (!preferSymlinks) {
110108                 var result_15 = ts.forEach(targets, function (p) { return cb(p, referenceRedirect === p); });
110109                 if (result_15)
110110                     return result_15;
110111             }
110112             var links = host.getSymlinkCache
110113                 ? host.getSymlinkCache()
110114                 : ts.discoverProbableSymlinks(host.getSourceFiles(), getCanonicalFileName, cwd);
110115             var symlinkedDirectories = links.getSymlinkedDirectories();
110116             var useCaseSensitiveFileNames = !host.useCaseSensitiveFileNames || host.useCaseSensitiveFileNames();
110117             var result = symlinkedDirectories && ts.forEachEntry(symlinkedDirectories, function (resolved, path) {
110118                 if (resolved === false)
110119                     return undefined;
110120                 if (ts.startsWithDirectory(importingFileName, resolved.realPath, getCanonicalFileName)) {
110121                     return undefined; // Don't want to a package to globally import from itself
110122                 }
110123                 return ts.forEach(targets, function (target) {
110124                     if (!ts.containsPath(resolved.real, target, !useCaseSensitiveFileNames)) {
110125                         return;
110126                     }
110127                     var relative = ts.getRelativePathFromDirectory(resolved.real, target, getCanonicalFileName);
110128                     var option = ts.resolvePath(path, relative);
110129                     if (!host.fileExists || host.fileExists(option)) {
110130                         var result_16 = cb(option, target === referenceRedirect);
110131                         if (result_16)
110132                             return result_16;
110133                     }
110134                 });
110135             });
110136             return result ||
110137                 (preferSymlinks ? ts.forEach(targets, function (p) { return cb(p, p === referenceRedirect); }) : undefined);
110138         }
110139         moduleSpecifiers.forEachFileNameOfModule = forEachFileNameOfModule;
110140         /**
110141          * Looks for existing imports that use symlinks to this module.
110142          * Symlinks will be returned first so they are preferred over the real path.
110143          */
110144         function getAllModulePaths(importingFileName, importedFileName, host) {
110145             var cwd = host.getCurrentDirectory();
110146             var getCanonicalFileName = ts.hostGetCanonicalFileName(host);
110147             var allFileNames = new ts.Map();
110148             var importedFileFromNodeModules = false;
110149             forEachFileNameOfModule(importingFileName, importedFileName, host, 
110150             /*preferSymlinks*/ true, function (path, isRedirect) {
110151                 var isInNodeModules = ts.pathContainsNodeModules(path);
110152                 allFileNames.set(path, { path: getCanonicalFileName(path), isRedirect: isRedirect, isInNodeModules: isInNodeModules });
110153                 importedFileFromNodeModules = importedFileFromNodeModules || isInNodeModules;
110154                 // don't return value, so we collect everything
110155             });
110156             // Sort by paths closest to importing file Name directory
110157             var sortedPaths = [];
110158             var _loop_24 = function (directory) {
110159                 var directoryStart = ts.ensureTrailingDirectorySeparator(directory);
110160                 var pathsInDirectory;
110161                 allFileNames.forEach(function (_a, fileName) {
110162                     var path = _a.path, isRedirect = _a.isRedirect, isInNodeModules = _a.isInNodeModules;
110163                     if (ts.startsWith(path, directoryStart)) {
110164                         (pathsInDirectory || (pathsInDirectory = [])).push({ path: fileName, isRedirect: isRedirect, isInNodeModules: isInNodeModules });
110165                         allFileNames.delete(fileName);
110166                     }
110167                 });
110168                 if (pathsInDirectory) {
110169                     if (pathsInDirectory.length > 1) {
110170                         pathsInDirectory.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
110171                     }
110172                     sortedPaths.push.apply(sortedPaths, pathsInDirectory);
110173                 }
110174                 var newDirectory = ts.getDirectoryPath(directory);
110175                 if (newDirectory === directory)
110176                     return out_directory_1 = directory, "break";
110177                 directory = newDirectory;
110178                 out_directory_1 = directory;
110179             };
110180             var out_directory_1;
110181             for (var directory = ts.getDirectoryPath(ts.toPath(importingFileName, cwd, getCanonicalFileName)); allFileNames.size !== 0;) {
110182                 var state_8 = _loop_24(directory);
110183                 directory = out_directory_1;
110184                 if (state_8 === "break")
110185                     break;
110186             }
110187             if (allFileNames.size) {
110188                 var remainingPaths = ts.arrayFrom(allFileNames.values());
110189                 if (remainingPaths.length > 1)
110190                     remainingPaths.sort(comparePathsByRedirectAndNumberOfDirectorySeparators);
110191                 sortedPaths.push.apply(sortedPaths, remainingPaths);
110192             }
110193             return sortedPaths;
110194         }
110195         function tryGetModuleNameFromAmbientModule(moduleSymbol) {
110196             var decl = ts.find(moduleSymbol.declarations, function (d) { return ts.isNonGlobalAmbientModule(d) && (!ts.isExternalModuleAugmentation(d) || !ts.isExternalModuleNameRelative(ts.getTextOfIdentifierOrLiteral(d.name))); });
110197             if (decl) {
110198                 return decl.name.text;
110199             }
110200         }
110201         function tryGetModuleNameFromPaths(relativeToBaseUrlWithIndex, relativeToBaseUrl, paths) {
110202             for (var key in paths) {
110203                 for (var _i = 0, _a = paths[key]; _i < _a.length; _i++) {
110204                     var patternText_1 = _a[_i];
110205                     var pattern = ts.removeFileExtension(ts.normalizePath(patternText_1));
110206                     var indexOfStar = pattern.indexOf("*");
110207                     if (indexOfStar !== -1) {
110208                         var prefix = pattern.substr(0, indexOfStar);
110209                         var suffix = pattern.substr(indexOfStar + 1);
110210                         if (relativeToBaseUrl.length >= prefix.length + suffix.length &&
110211                             ts.startsWith(relativeToBaseUrl, prefix) &&
110212                             ts.endsWith(relativeToBaseUrl, suffix) ||
110213                             !suffix && relativeToBaseUrl === ts.removeTrailingDirectorySeparator(prefix)) {
110214                             var matchedStar = relativeToBaseUrl.substr(prefix.length, relativeToBaseUrl.length - suffix.length);
110215                             return key.replace("*", matchedStar);
110216                         }
110217                     }
110218                     else if (pattern === relativeToBaseUrl || pattern === relativeToBaseUrlWithIndex) {
110219                         return key;
110220                     }
110221                 }
110222             }
110223         }
110224         function tryGetModuleNameFromRootDirs(rootDirs, moduleFileName, sourceDirectory, getCanonicalFileName, ending, compilerOptions) {
110225             var normalizedTargetPath = getPathRelativeToRootDirs(moduleFileName, rootDirs, getCanonicalFileName);
110226             if (normalizedTargetPath === undefined) {
110227                 return undefined;
110228             }
110229             var normalizedSourcePath = getPathRelativeToRootDirs(sourceDirectory, rootDirs, getCanonicalFileName);
110230             var relativePath = normalizedSourcePath !== undefined ? ts.ensurePathIsNonModuleName(ts.getRelativePathFromDirectory(normalizedSourcePath, normalizedTargetPath, getCanonicalFileName)) : normalizedTargetPath;
110231             return ts.getEmitModuleResolutionKind(compilerOptions) === ts.ModuleResolutionKind.NodeJs
110232                 ? removeExtensionAndIndexPostFix(relativePath, ending, compilerOptions)
110233                 : ts.removeFileExtension(relativePath);
110234         }
110235         function tryGetModuleNameAsNodeModule(_a, _b, host, options, packageNameOnly) {
110236             var path = _a.path, isRedirect = _a.isRedirect;
110237             var getCanonicalFileName = _b.getCanonicalFileName, sourceDirectory = _b.sourceDirectory;
110238             if (!host.fileExists || !host.readFile) {
110239                 return undefined;
110240             }
110241             var parts = getNodeModulePathParts(path);
110242             if (!parts) {
110243                 return undefined;
110244             }
110245             // Simplify the full file path to something that can be resolved by Node.
110246             var moduleSpecifier = path;
110247             var isPackageRootPath = false;
110248             if (!packageNameOnly) {
110249                 var packageRootIndex = parts.packageRootIndex;
110250                 var moduleFileNameForExtensionless = void 0;
110251                 while (true) {
110252                     // If the module could be imported by a directory name, use that directory's name
110253                     var _c = tryDirectoryWithPackageJson(packageRootIndex), moduleFileToTry = _c.moduleFileToTry, packageRootPath = _c.packageRootPath;
110254                     if (packageRootPath) {
110255                         moduleSpecifier = packageRootPath;
110256                         isPackageRootPath = true;
110257                         break;
110258                     }
110259                     if (!moduleFileNameForExtensionless)
110260                         moduleFileNameForExtensionless = moduleFileToTry;
110261                     // try with next level of directory
110262                     packageRootIndex = path.indexOf(ts.directorySeparator, packageRootIndex + 1);
110263                     if (packageRootIndex === -1) {
110264                         moduleSpecifier = getExtensionlessFileName(moduleFileNameForExtensionless);
110265                         break;
110266                     }
110267                 }
110268             }
110269             if (isRedirect && !isPackageRootPath) {
110270                 return undefined;
110271             }
110272             var globalTypingsCacheLocation = host.getGlobalTypingsCacheLocation && host.getGlobalTypingsCacheLocation();
110273             // Get a path that's relative to node_modules or the importing file's path
110274             // if node_modules folder is in this folder or any of its parent folders, no need to keep it.
110275             var pathToTopLevelNodeModules = getCanonicalFileName(moduleSpecifier.substring(0, parts.topLevelNodeModulesIndex));
110276             if (!(ts.startsWith(sourceDirectory, pathToTopLevelNodeModules) || globalTypingsCacheLocation && ts.startsWith(getCanonicalFileName(globalTypingsCacheLocation), pathToTopLevelNodeModules))) {
110277                 return undefined;
110278             }
110279             // If the module was found in @types, get the actual Node package name
110280             var nodeModulesDirectoryName = moduleSpecifier.substring(parts.topLevelPackageNameIndex + 1);
110281             var packageName = ts.getPackageNameFromTypesPackageName(nodeModulesDirectoryName);
110282             // For classic resolution, only allow importing from node_modules/@types, not other node_modules
110283             return ts.getEmitModuleResolutionKind(options) !== ts.ModuleResolutionKind.NodeJs && packageName === nodeModulesDirectoryName ? undefined : packageName;
110284             function tryDirectoryWithPackageJson(packageRootIndex) {
110285                 var packageRootPath = path.substring(0, packageRootIndex);
110286                 var packageJsonPath = ts.combinePaths(packageRootPath, "package.json");
110287                 var moduleFileToTry = path;
110288                 if (host.fileExists(packageJsonPath)) {
110289                     var packageJsonContent = JSON.parse(host.readFile(packageJsonPath));
110290                     var versionPaths = packageJsonContent.typesVersions
110291                         ? ts.getPackageJsonTypesVersionsPaths(packageJsonContent.typesVersions)
110292                         : undefined;
110293                     if (versionPaths) {
110294                         var subModuleName = path.slice(packageRootPath.length + 1);
110295                         var fromPaths = tryGetModuleNameFromPaths(ts.removeFileExtension(subModuleName), removeExtensionAndIndexPostFix(subModuleName, 0 /* Minimal */, options), versionPaths.paths);
110296                         if (fromPaths !== undefined) {
110297                             moduleFileToTry = ts.combinePaths(packageRootPath, fromPaths);
110298                         }
110299                     }
110300                     // If the file is the main module, it can be imported by the package name
110301                     var mainFileRelative = packageJsonContent.typings || packageJsonContent.types || packageJsonContent.main;
110302                     if (ts.isString(mainFileRelative)) {
110303                         var mainExportFile = ts.toPath(mainFileRelative, packageRootPath, getCanonicalFileName);
110304                         if (ts.removeFileExtension(mainExportFile) === ts.removeFileExtension(getCanonicalFileName(moduleFileToTry))) {
110305                             return { packageRootPath: packageRootPath, moduleFileToTry: moduleFileToTry };
110306                         }
110307                     }
110308                 }
110309                 return { moduleFileToTry: moduleFileToTry };
110310             }
110311             function getExtensionlessFileName(path) {
110312                 // We still have a file name - remove the extension
110313                 var fullModulePathWithoutExtension = ts.removeFileExtension(path);
110314                 // If the file is /index, it can be imported by its directory name
110315                 // IFF there is not _also_ a file by the same name
110316                 if (getCanonicalFileName(fullModulePathWithoutExtension.substring(parts.fileNameIndex)) === "/index" && !tryGetAnyFileFromPath(host, fullModulePathWithoutExtension.substring(0, parts.fileNameIndex))) {
110317                     return fullModulePathWithoutExtension.substring(0, parts.fileNameIndex);
110318                 }
110319                 return fullModulePathWithoutExtension;
110320             }
110321         }
110322         function tryGetAnyFileFromPath(host, path) {
110323             if (!host.fileExists)
110324                 return;
110325             // We check all js, `node` and `json` extensions in addition to TS, since node module resolution would also choose those over the directory
110326             var extensions = ts.getSupportedExtensions({ allowJs: true }, [{ extension: "node", isMixedContent: false }, { extension: "json", isMixedContent: false, scriptKind: 6 /* JSON */ }]);
110327             for (var _i = 0, extensions_3 = extensions; _i < extensions_3.length; _i++) {
110328                 var e = extensions_3[_i];
110329                 var fullPath = path + e;
110330                 if (host.fileExists(fullPath)) {
110331                     return fullPath;
110332                 }
110333             }
110334         }
110335         function getNodeModulePathParts(fullPath) {
110336             // If fullPath can't be valid module file within node_modules, returns undefined.
110337             // Example of expected pattern: /base/path/node_modules/[@scope/otherpackage/@otherscope/node_modules/]package/[subdirectory/]file.js
110338             // Returns indices:                       ^            ^                                                      ^             ^
110339             var topLevelNodeModulesIndex = 0;
110340             var topLevelPackageNameIndex = 0;
110341             var packageRootIndex = 0;
110342             var fileNameIndex = 0;
110343             var States;
110344             (function (States) {
110345                 States[States["BeforeNodeModules"] = 0] = "BeforeNodeModules";
110346                 States[States["NodeModules"] = 1] = "NodeModules";
110347                 States[States["Scope"] = 2] = "Scope";
110348                 States[States["PackageContent"] = 3] = "PackageContent";
110349             })(States || (States = {}));
110350             var partStart = 0;
110351             var partEnd = 0;
110352             var state = 0 /* BeforeNodeModules */;
110353             while (partEnd >= 0) {
110354                 partStart = partEnd;
110355                 partEnd = fullPath.indexOf("/", partStart + 1);
110356                 switch (state) {
110357                     case 0 /* BeforeNodeModules */:
110358                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
110359                             topLevelNodeModulesIndex = partStart;
110360                             topLevelPackageNameIndex = partEnd;
110361                             state = 1 /* NodeModules */;
110362                         }
110363                         break;
110364                     case 1 /* NodeModules */:
110365                     case 2 /* Scope */:
110366                         if (state === 1 /* NodeModules */ && fullPath.charAt(partStart + 1) === "@") {
110367                             state = 2 /* Scope */;
110368                         }
110369                         else {
110370                             packageRootIndex = partEnd;
110371                             state = 3 /* PackageContent */;
110372                         }
110373                         break;
110374                     case 3 /* PackageContent */:
110375                         if (fullPath.indexOf(ts.nodeModulesPathPart, partStart) === partStart) {
110376                             state = 1 /* NodeModules */;
110377                         }
110378                         else {
110379                             state = 3 /* PackageContent */;
110380                         }
110381                         break;
110382                 }
110383             }
110384             fileNameIndex = partStart;
110385             return state > 1 /* NodeModules */ ? { topLevelNodeModulesIndex: topLevelNodeModulesIndex, topLevelPackageNameIndex: topLevelPackageNameIndex, packageRootIndex: packageRootIndex, fileNameIndex: fileNameIndex } : undefined;
110386         }
110387         function getPathRelativeToRootDirs(path, rootDirs, getCanonicalFileName) {
110388             return ts.firstDefined(rootDirs, function (rootDir) {
110389                 var relativePath = getRelativePathIfInDirectory(path, rootDir, getCanonicalFileName); // TODO: GH#18217
110390                 return isPathRelativeToParent(relativePath) ? undefined : relativePath;
110391             });
110392         }
110393         function removeExtensionAndIndexPostFix(fileName, ending, options) {
110394             if (ts.fileExtensionIs(fileName, ".json" /* Json */))
110395                 return fileName;
110396             var noExtension = ts.removeFileExtension(fileName);
110397             switch (ending) {
110398                 case 0 /* Minimal */:
110399                     return ts.removeSuffix(noExtension, "/index");
110400                 case 1 /* Index */:
110401                     return noExtension;
110402                 case 2 /* JsExtension */:
110403                     return noExtension + getJSExtensionForFile(fileName, options);
110404                 default:
110405                     return ts.Debug.assertNever(ending);
110406             }
110407         }
110408         function getJSExtensionForFile(fileName, options) {
110409             var ext = ts.extensionFromPath(fileName);
110410             switch (ext) {
110411                 case ".ts" /* Ts */:
110412                 case ".d.ts" /* Dts */:
110413                     return ".js" /* Js */;
110414                 case ".tsx" /* Tsx */:
110415                     return options.jsx === 1 /* Preserve */ ? ".jsx" /* Jsx */ : ".js" /* Js */;
110416                 case ".js" /* Js */:
110417                 case ".jsx" /* Jsx */:
110418                 case ".json" /* Json */:
110419                     return ext;
110420                 case ".tsbuildinfo" /* TsBuildInfo */:
110421                     return ts.Debug.fail("Extension " + ".tsbuildinfo" /* TsBuildInfo */ + " is unsupported:: FileName:: " + fileName);
110422                 default:
110423                     return ts.Debug.assertNever(ext);
110424             }
110425         }
110426         function getRelativePathIfInDirectory(path, directoryPath, getCanonicalFileName) {
110427             var relativePath = ts.getRelativePathToDirectoryOrUrl(directoryPath, path, directoryPath, getCanonicalFileName, /*isAbsolutePathAnUrl*/ false);
110428             return ts.isRootedDiskPath(relativePath) ? undefined : relativePath;
110429         }
110430         function isPathRelativeToParent(path) {
110431             return ts.startsWith(path, "..");
110432         }
110433     })(moduleSpecifiers = ts.moduleSpecifiers || (ts.moduleSpecifiers = {}));
110434 })(ts || (ts = {}));
110435 /*@internal*/
110436 var ts;
110437 (function (ts) {
110438     var sysFormatDiagnosticsHost = ts.sys ? {
110439         getCurrentDirectory: function () { return ts.sys.getCurrentDirectory(); },
110440         getNewLine: function () { return ts.sys.newLine; },
110441         getCanonicalFileName: ts.createGetCanonicalFileName(ts.sys.useCaseSensitiveFileNames)
110442     } : undefined; // TODO: GH#18217
110443     /**
110444      * Create a function that reports error by writing to the system and handles the formating of the diagnostic
110445      */
110446     function createDiagnosticReporter(system, pretty) {
110447         var host = system === ts.sys ? sysFormatDiagnosticsHost : {
110448             getCurrentDirectory: function () { return system.getCurrentDirectory(); },
110449             getNewLine: function () { return system.newLine; },
110450             getCanonicalFileName: ts.createGetCanonicalFileName(system.useCaseSensitiveFileNames),
110451         };
110452         if (!pretty) {
110453             return function (diagnostic) { return system.write(ts.formatDiagnostic(diagnostic, host)); };
110454         }
110455         var diagnostics = new Array(1);
110456         return function (diagnostic) {
110457             diagnostics[0] = diagnostic;
110458             system.write(ts.formatDiagnosticsWithColorAndContext(diagnostics, host) + host.getNewLine());
110459             diagnostics[0] = undefined; // TODO: GH#18217
110460         };
110461     }
110462     ts.createDiagnosticReporter = createDiagnosticReporter;
110463     /**
110464      * @returns Whether the screen was cleared.
110465      */
110466     function clearScreenIfNotWatchingForFileChanges(system, diagnostic, options) {
110467         if (system.clearScreen &&
110468             !options.preserveWatchOutput &&
110469             !options.extendedDiagnostics &&
110470             !options.diagnostics &&
110471             ts.contains(ts.screenStartingMessageCodes, diagnostic.code)) {
110472             system.clearScreen();
110473             return true;
110474         }
110475         return false;
110476     }
110477     ts.screenStartingMessageCodes = [
110478         ts.Diagnostics.Starting_compilation_in_watch_mode.code,
110479         ts.Diagnostics.File_change_detected_Starting_incremental_compilation.code,
110480     ];
110481     function getPlainDiagnosticFollowingNewLines(diagnostic, newLine) {
110482         return ts.contains(ts.screenStartingMessageCodes, diagnostic.code)
110483             ? newLine + newLine
110484             : newLine;
110485     }
110486     /**
110487      * Get locale specific time based on whether we are in test mode
110488      */
110489     function getLocaleTimeString(system) {
110490         return !system.now ?
110491             new Date().toLocaleTimeString() :
110492             system.now().toLocaleTimeString("en-US", { timeZone: "UTC" });
110493     }
110494     ts.getLocaleTimeString = getLocaleTimeString;
110495     /**
110496      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
110497      */
110498     function createWatchStatusReporter(system, pretty) {
110499         return pretty ?
110500             function (diagnostic, newLine, options) {
110501                 clearScreenIfNotWatchingForFileChanges(system, diagnostic, options);
110502                 var output = "[" + ts.formatColorAndReset(getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] ";
110503                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (newLine + newLine);
110504                 system.write(output);
110505             } :
110506             function (diagnostic, newLine, options) {
110507                 var output = "";
110508                 if (!clearScreenIfNotWatchingForFileChanges(system, diagnostic, options)) {
110509                     output += newLine;
110510                 }
110511                 output += getLocaleTimeString(system) + " - ";
110512                 output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + getPlainDiagnosticFollowingNewLines(diagnostic, newLine);
110513                 system.write(output);
110514             };
110515     }
110516     ts.createWatchStatusReporter = createWatchStatusReporter;
110517     /** Parses config file using System interface */
110518     function parseConfigFileWithSystem(configFileName, optionsToExtend, watchOptionsToExtend, system, reportDiagnostic) {
110519         var host = system;
110520         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic); };
110521         var result = ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtend, host, /*extendedConfigCache*/ undefined, watchOptionsToExtend);
110522         host.onUnRecoverableConfigFileDiagnostic = undefined; // TODO: GH#18217
110523         return result;
110524     }
110525     ts.parseConfigFileWithSystem = parseConfigFileWithSystem;
110526     function getErrorCountForSummary(diagnostics) {
110527         return ts.countWhere(diagnostics, function (diagnostic) { return diagnostic.category === ts.DiagnosticCategory.Error; });
110528     }
110529     ts.getErrorCountForSummary = getErrorCountForSummary;
110530     function getWatchErrorSummaryDiagnosticMessage(errorCount) {
110531         return errorCount === 1 ?
110532             ts.Diagnostics.Found_1_error_Watching_for_file_changes :
110533             ts.Diagnostics.Found_0_errors_Watching_for_file_changes;
110534     }
110535     ts.getWatchErrorSummaryDiagnosticMessage = getWatchErrorSummaryDiagnosticMessage;
110536     function getErrorSummaryText(errorCount, newLine) {
110537         if (errorCount === 0)
110538             return "";
110539         var d = ts.createCompilerDiagnostic(errorCount === 1 ? ts.Diagnostics.Found_1_error : ts.Diagnostics.Found_0_errors, errorCount);
110540         return "" + newLine + ts.flattenDiagnosticMessageText(d.messageText, newLine) + newLine + newLine;
110541     }
110542     ts.getErrorSummaryText = getErrorSummaryText;
110543     function listFiles(program, writeFileName) {
110544         if (program.getCompilerOptions().listFiles || program.getCompilerOptions().listFilesOnly) {
110545             ts.forEach(program.getSourceFiles(), function (file) {
110546                 writeFileName(file.fileName);
110547             });
110548         }
110549     }
110550     ts.listFiles = listFiles;
110551     /**
110552      * Helper that emit files, report diagnostics and lists emitted and/or source files depending on compiler options
110553      */
110554     function emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
110555         var isListFilesOnly = !!program.getCompilerOptions().listFilesOnly;
110556         // First get and report any syntactic errors.
110557         var allDiagnostics = program.getConfigFileParsingDiagnostics().slice();
110558         var configFileParsingDiagnosticsLength = allDiagnostics.length;
110559         ts.addRange(allDiagnostics, program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
110560         // If we didn't have any syntactic errors, then also try getting the global and
110561         // semantic errors.
110562         if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
110563             ts.addRange(allDiagnostics, program.getOptionsDiagnostics(cancellationToken));
110564             if (!isListFilesOnly) {
110565                 ts.addRange(allDiagnostics, program.getGlobalDiagnostics(cancellationToken));
110566                 if (allDiagnostics.length === configFileParsingDiagnosticsLength) {
110567                     ts.addRange(allDiagnostics, program.getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken));
110568                 }
110569             }
110570         }
110571         // Emit and report any errors we ran into.
110572         var emitResult = isListFilesOnly
110573             ? { emitSkipped: true, diagnostics: ts.emptyArray }
110574             : program.emit(/*targetSourceFile*/ undefined, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers);
110575         var emittedFiles = emitResult.emittedFiles, emitDiagnostics = emitResult.diagnostics;
110576         ts.addRange(allDiagnostics, emitDiagnostics);
110577         var diagnostics = ts.sortAndDeduplicateDiagnostics(allDiagnostics);
110578         diagnostics.forEach(reportDiagnostic);
110579         if (writeFileName) {
110580             var currentDir_1 = program.getCurrentDirectory();
110581             ts.forEach(emittedFiles, function (file) {
110582                 var filepath = ts.getNormalizedAbsolutePath(file, currentDir_1);
110583                 writeFileName("TSFILE: " + filepath);
110584             });
110585             listFiles(program, writeFileName);
110586         }
110587         if (reportSummary) {
110588             reportSummary(getErrorCountForSummary(diagnostics));
110589         }
110590         return {
110591             emitResult: emitResult,
110592             diagnostics: diagnostics,
110593         };
110594     }
110595     ts.emitFilesAndReportErrors = emitFilesAndReportErrors;
110596     function emitFilesAndReportErrorsAndGetExitStatus(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
110597         var _a = emitFilesAndReportErrors(program, reportDiagnostic, writeFileName, reportSummary, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers), emitResult = _a.emitResult, diagnostics = _a.diagnostics;
110598         if (emitResult.emitSkipped && diagnostics.length > 0) {
110599             // If the emitter didn't emit anything, then pass that value along.
110600             return ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
110601         }
110602         else if (diagnostics.length > 0) {
110603             // The emitter emitted something, inform the caller if that happened in the presence
110604             // of diagnostics or not.
110605             return ts.ExitStatus.DiagnosticsPresent_OutputsGenerated;
110606         }
110607         return ts.ExitStatus.Success;
110608     }
110609     ts.emitFilesAndReportErrorsAndGetExitStatus = emitFilesAndReportErrorsAndGetExitStatus;
110610     ts.noopFileWatcher = { close: ts.noop };
110611     ts.returnNoopFileWatcher = function () { return ts.noopFileWatcher; };
110612     function createWatchHost(system, reportWatchStatus) {
110613         if (system === void 0) { system = ts.sys; }
110614         var onWatchStatusChange = reportWatchStatus || createWatchStatusReporter(system);
110615         return {
110616             onWatchStatusChange: onWatchStatusChange,
110617             watchFile: ts.maybeBind(system, system.watchFile) || ts.returnNoopFileWatcher,
110618             watchDirectory: ts.maybeBind(system, system.watchDirectory) || ts.returnNoopFileWatcher,
110619             setTimeout: ts.maybeBind(system, system.setTimeout) || ts.noop,
110620             clearTimeout: ts.maybeBind(system, system.clearTimeout) || ts.noop
110621         };
110622     }
110623     ts.createWatchHost = createWatchHost;
110624     ts.WatchType = {
110625         ConfigFile: "Config file",
110626         SourceFile: "Source file",
110627         MissingFile: "Missing file",
110628         WildcardDirectory: "Wild card directory",
110629         FailedLookupLocations: "Failed Lookup Locations",
110630         TypeRoots: "Type roots"
110631     };
110632     function createWatchFactory(host, options) {
110633         var watchLogLevel = host.trace ? options.extendedDiagnostics ? ts.WatchLogLevel.Verbose : options.diagnostics ? ts.WatchLogLevel.TriggerOnly : ts.WatchLogLevel.None : ts.WatchLogLevel.None;
110634         var writeLog = watchLogLevel !== ts.WatchLogLevel.None ? (function (s) { return host.trace(s); }) : ts.noop;
110635         var result = ts.getWatchFactory(watchLogLevel, writeLog);
110636         result.writeLog = writeLog;
110637         return result;
110638     }
110639     ts.createWatchFactory = createWatchFactory;
110640     function createCompilerHostFromProgramHost(host, getCompilerOptions, directoryStructureHost) {
110641         if (directoryStructureHost === void 0) { directoryStructureHost = host; }
110642         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
110643         var hostGetNewLine = ts.memoize(function () { return host.getNewLine(); });
110644         return {
110645             getSourceFile: function (fileName, languageVersion, onError) {
110646                 var text;
110647                 try {
110648                     ts.performance.mark("beforeIORead");
110649                     text = host.readFile(fileName, getCompilerOptions().charset);
110650                     ts.performance.mark("afterIORead");
110651                     ts.performance.measure("I/O Read", "beforeIORead", "afterIORead");
110652                 }
110653                 catch (e) {
110654                     if (onError) {
110655                         onError(e.message);
110656                     }
110657                     text = "";
110658                 }
110659                 return text !== undefined ? ts.createSourceFile(fileName, text, languageVersion) : undefined;
110660             },
110661             getDefaultLibLocation: ts.maybeBind(host, host.getDefaultLibLocation),
110662             getDefaultLibFileName: function (options) { return host.getDefaultLibFileName(options); },
110663             writeFile: writeFile,
110664             getCurrentDirectory: ts.memoize(function () { return host.getCurrentDirectory(); }),
110665             useCaseSensitiveFileNames: function () { return useCaseSensitiveFileNames; },
110666             getCanonicalFileName: ts.createGetCanonicalFileName(useCaseSensitiveFileNames),
110667             getNewLine: function () { return ts.getNewLineCharacter(getCompilerOptions(), hostGetNewLine); },
110668             fileExists: function (f) { return host.fileExists(f); },
110669             readFile: function (f) { return host.readFile(f); },
110670             trace: ts.maybeBind(host, host.trace),
110671             directoryExists: ts.maybeBind(directoryStructureHost, directoryStructureHost.directoryExists),
110672             getDirectories: ts.maybeBind(directoryStructureHost, directoryStructureHost.getDirectories),
110673             realpath: ts.maybeBind(host, host.realpath),
110674             getEnvironmentVariable: ts.maybeBind(host, host.getEnvironmentVariable) || (function () { return ""; }),
110675             createHash: ts.maybeBind(host, host.createHash),
110676             readDirectory: ts.maybeBind(host, host.readDirectory),
110677         };
110678         function writeFile(fileName, text, writeByteOrderMark, onError) {
110679             try {
110680                 ts.performance.mark("beforeIOWrite");
110681                 // NOTE: If patchWriteFileEnsuringDirectory has been called,
110682                 // the host.writeFile will do its own directory creation and
110683                 // the ensureDirectoriesExist call will always be redundant.
110684                 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); });
110685                 ts.performance.mark("afterIOWrite");
110686                 ts.performance.measure("I/O Write", "beforeIOWrite", "afterIOWrite");
110687             }
110688             catch (e) {
110689                 if (onError) {
110690                     onError(e.message);
110691                 }
110692             }
110693         }
110694     }
110695     ts.createCompilerHostFromProgramHost = createCompilerHostFromProgramHost;
110696     function setGetSourceFileAsHashVersioned(compilerHost, host) {
110697         var originalGetSourceFile = compilerHost.getSourceFile;
110698         var computeHash = ts.maybeBind(host, host.createHash) || ts.generateDjb2Hash;
110699         compilerHost.getSourceFile = function () {
110700             var args = [];
110701             for (var _i = 0; _i < arguments.length; _i++) {
110702                 args[_i] = arguments[_i];
110703             }
110704             var result = originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
110705             if (result) {
110706                 result.version = computeHash(result.text);
110707             }
110708             return result;
110709         };
110710     }
110711     ts.setGetSourceFileAsHashVersioned = setGetSourceFileAsHashVersioned;
110712     /**
110713      * Creates the watch compiler host that can be extended with config file or root file names and options host
110714      */
110715     function createProgramHost(system, createProgram) {
110716         var getDefaultLibLocation = ts.memoize(function () { return ts.getDirectoryPath(ts.normalizePath(system.getExecutingFilePath())); });
110717         return {
110718             useCaseSensitiveFileNames: function () { return system.useCaseSensitiveFileNames; },
110719             getNewLine: function () { return system.newLine; },
110720             getCurrentDirectory: ts.memoize(function () { return system.getCurrentDirectory(); }),
110721             getDefaultLibLocation: getDefaultLibLocation,
110722             getDefaultLibFileName: function (options) { return ts.combinePaths(getDefaultLibLocation(), ts.getDefaultLibFileName(options)); },
110723             fileExists: function (path) { return system.fileExists(path); },
110724             readFile: function (path, encoding) { return system.readFile(path, encoding); },
110725             directoryExists: function (path) { return system.directoryExists(path); },
110726             getDirectories: function (path) { return system.getDirectories(path); },
110727             readDirectory: function (path, extensions, exclude, include, depth) { return system.readDirectory(path, extensions, exclude, include, depth); },
110728             realpath: ts.maybeBind(system, system.realpath),
110729             getEnvironmentVariable: ts.maybeBind(system, system.getEnvironmentVariable),
110730             trace: function (s) { return system.write(s + system.newLine); },
110731             createDirectory: function (path) { return system.createDirectory(path); },
110732             writeFile: function (path, data, writeByteOrderMark) { return system.writeFile(path, data, writeByteOrderMark); },
110733             createHash: ts.maybeBind(system, system.createHash),
110734             createProgram: createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram
110735         };
110736     }
110737     ts.createProgramHost = createProgramHost;
110738     /**
110739      * Creates the watch compiler host that can be extended with config file or root file names and options host
110740      */
110741     function createWatchCompilerHost(system, createProgram, reportDiagnostic, reportWatchStatus) {
110742         if (system === void 0) { system = ts.sys; }
110743         var writeFileName = function (s) { return system.write(s + system.newLine); };
110744         var result = createProgramHost(system, createProgram);
110745         ts.copyProperties(result, createWatchHost(system, reportWatchStatus));
110746         result.afterProgramCreate = function (builderProgram) {
110747             var compilerOptions = builderProgram.getCompilerOptions();
110748             var newLine = ts.getNewLineCharacter(compilerOptions, function () { return system.newLine; });
110749             emitFilesAndReportErrors(builderProgram, reportDiagnostic, writeFileName, function (errorCount) { return result.onWatchStatusChange(ts.createCompilerDiagnostic(getWatchErrorSummaryDiagnosticMessage(errorCount), errorCount), newLine, compilerOptions, errorCount); });
110750         };
110751         return result;
110752     }
110753     /**
110754      * Report error and exit
110755      */
110756     function reportUnrecoverableDiagnostic(system, reportDiagnostic, diagnostic) {
110757         reportDiagnostic(diagnostic);
110758         system.exit(ts.ExitStatus.DiagnosticsPresent_OutputsSkipped);
110759     }
110760     /**
110761      * Creates the watch compiler host from system for config file in watch mode
110762      */
110763     function createWatchCompilerHostOfConfigFile(_a) {
110764         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;
110765         var diagnosticReporter = reportDiagnostic || createDiagnosticReporter(system);
110766         var host = createWatchCompilerHost(system, createProgram, diagnosticReporter, reportWatchStatus);
110767         host.onUnRecoverableConfigFileDiagnostic = function (diagnostic) { return reportUnrecoverableDiagnostic(system, diagnosticReporter, diagnostic); };
110768         host.configFileName = configFileName;
110769         host.optionsToExtend = optionsToExtend;
110770         host.watchOptionsToExtend = watchOptionsToExtend;
110771         host.extraFileExtensions = extraFileExtensions;
110772         return host;
110773     }
110774     ts.createWatchCompilerHostOfConfigFile = createWatchCompilerHostOfConfigFile;
110775     /**
110776      * Creates the watch compiler host from system for compiling root files and options in watch mode
110777      */
110778     function createWatchCompilerHostOfFilesAndCompilerOptions(_a) {
110779         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;
110780         var host = createWatchCompilerHost(system, createProgram, reportDiagnostic || createDiagnosticReporter(system), reportWatchStatus);
110781         host.rootFiles = rootFiles;
110782         host.options = options;
110783         host.watchOptions = watchOptions;
110784         host.projectReferences = projectReferences;
110785         return host;
110786     }
110787     ts.createWatchCompilerHostOfFilesAndCompilerOptions = createWatchCompilerHostOfFilesAndCompilerOptions;
110788     function performIncrementalCompilation(input) {
110789         var system = input.system || ts.sys;
110790         var host = input.host || (input.host = ts.createIncrementalCompilerHost(input.options, system));
110791         var builderProgram = ts.createIncrementalProgram(input);
110792         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);
110793         if (input.afterProgramEmitAndDiagnostics)
110794             input.afterProgramEmitAndDiagnostics(builderProgram);
110795         return exitStatus;
110796     }
110797     ts.performIncrementalCompilation = performIncrementalCompilation;
110798 })(ts || (ts = {}));
110799 var ts;
110800 (function (ts) {
110801     function readBuilderProgram(compilerOptions, host) {
110802         if (ts.outFile(compilerOptions))
110803             return undefined;
110804         var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(compilerOptions);
110805         if (!buildInfoPath)
110806             return undefined;
110807         var content = host.readFile(buildInfoPath);
110808         if (!content)
110809             return undefined;
110810         var buildInfo = ts.getBuildInfo(content);
110811         if (buildInfo.version !== ts.version)
110812             return undefined;
110813         if (!buildInfo.program)
110814             return undefined;
110815         return ts.createBuildProgramUsingProgramBuildInfo(buildInfo.program, buildInfoPath, host);
110816     }
110817     ts.readBuilderProgram = readBuilderProgram;
110818     function createIncrementalCompilerHost(options, system) {
110819         if (system === void 0) { system = ts.sys; }
110820         var host = ts.createCompilerHostWorker(options, /*setParentNodes*/ undefined, system);
110821         host.createHash = ts.maybeBind(system, system.createHash);
110822         ts.setGetSourceFileAsHashVersioned(host, system);
110823         ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return ts.toPath(fileName, host.getCurrentDirectory(), host.getCanonicalFileName); });
110824         return host;
110825     }
110826     ts.createIncrementalCompilerHost = createIncrementalCompilerHost;
110827     function createIncrementalProgram(_a) {
110828         var rootNames = _a.rootNames, options = _a.options, configFileParsingDiagnostics = _a.configFileParsingDiagnostics, projectReferences = _a.projectReferences, host = _a.host, createProgram = _a.createProgram;
110829         host = host || createIncrementalCompilerHost(options);
110830         createProgram = createProgram || ts.createEmitAndSemanticDiagnosticsBuilderProgram;
110831         var oldProgram = readBuilderProgram(options, host);
110832         return createProgram(rootNames, options, host, oldProgram, configFileParsingDiagnostics, projectReferences);
110833     }
110834     ts.createIncrementalProgram = createIncrementalProgram;
110835     function createWatchCompilerHost(rootFilesOrConfigFileName, options, system, createProgram, reportDiagnostic, reportWatchStatus, projectReferencesOrWatchOptionsToExtend, watchOptionsOrExtraFileExtensions) {
110836         if (ts.isArray(rootFilesOrConfigFileName)) {
110837             return ts.createWatchCompilerHostOfFilesAndCompilerOptions({
110838                 rootFiles: rootFilesOrConfigFileName,
110839                 options: options,
110840                 watchOptions: watchOptionsOrExtraFileExtensions,
110841                 projectReferences: projectReferencesOrWatchOptionsToExtend,
110842                 system: system,
110843                 createProgram: createProgram,
110844                 reportDiagnostic: reportDiagnostic,
110845                 reportWatchStatus: reportWatchStatus,
110846             });
110847         }
110848         else {
110849             return ts.createWatchCompilerHostOfConfigFile({
110850                 configFileName: rootFilesOrConfigFileName,
110851                 optionsToExtend: options,
110852                 watchOptionsToExtend: projectReferencesOrWatchOptionsToExtend,
110853                 extraFileExtensions: watchOptionsOrExtraFileExtensions,
110854                 system: system,
110855                 createProgram: createProgram,
110856                 reportDiagnostic: reportDiagnostic,
110857                 reportWatchStatus: reportWatchStatus,
110858             });
110859         }
110860     }
110861     ts.createWatchCompilerHost = createWatchCompilerHost;
110862     function createWatchProgram(host) {
110863         var builderProgram;
110864         var reloadLevel; // level to indicate if the program needs to be reloaded from config file/just filenames etc
110865         var missingFilesMap; // Map of file watchers for the missing files
110866         var watchedWildcardDirectories; // map of watchers for the wild card directories in the config file
110867         var timerToUpdateProgram; // timer callback to recompile the program
110868         var timerToInvalidateFailedLookupResolutions; // timer callback to invalidate resolutions for changes in failed lookup locations
110869         var sourceFilesCache = new ts.Map(); // Cache that stores the source file and version info
110870         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
110871         var hasChangedCompilerOptions = false; // True if the compiler options have changed between compilations
110872         var useCaseSensitiveFileNames = host.useCaseSensitiveFileNames();
110873         var currentDirectory = host.getCurrentDirectory();
110874         var configFileName = host.configFileName, _a = host.optionsToExtend, optionsToExtendForConfigFile = _a === void 0 ? {} : _a, watchOptionsToExtend = host.watchOptionsToExtend, extraFileExtensions = host.extraFileExtensions, createProgram = host.createProgram;
110875         var rootFileNames = host.rootFiles, compilerOptions = host.options, watchOptions = host.watchOptions, projectReferences = host.projectReferences;
110876         var configFileSpecs;
110877         var configFileParsingDiagnostics;
110878         var canConfigFileJsonReportNoInputFiles = false;
110879         var hasChangedConfigFileParsingErrors = false;
110880         var cachedDirectoryStructureHost = configFileName === undefined ? undefined : ts.createCachedDirectoryStructureHost(host, currentDirectory, useCaseSensitiveFileNames);
110881         var directoryStructureHost = cachedDirectoryStructureHost || host;
110882         var parseConfigFileHost = ts.parseConfigHostFromCompilerHostLike(host, directoryStructureHost);
110883         // From tsc we want to get already parsed result and hence check for rootFileNames
110884         var newLine = updateNewLine();
110885         if (configFileName && host.configFileParsingResult) {
110886             setConfigFileParsingResult(host.configFileParsingResult);
110887             newLine = updateNewLine();
110888         }
110889         reportWatchDiagnostic(ts.Diagnostics.Starting_compilation_in_watch_mode);
110890         if (configFileName && !host.configFileParsingResult) {
110891             newLine = ts.getNewLineCharacter(optionsToExtendForConfigFile, function () { return host.getNewLine(); });
110892             ts.Debug.assert(!rootFileNames);
110893             parseConfigFile();
110894             newLine = updateNewLine();
110895         }
110896         var _b = ts.createWatchFactory(host, compilerOptions), watchFile = _b.watchFile, watchFilePath = _b.watchFilePath, watchDirectory = _b.watchDirectory, writeLog = _b.writeLog;
110897         var getCanonicalFileName = ts.createGetCanonicalFileName(useCaseSensitiveFileNames);
110898         writeLog("Current directory: " + currentDirectory + " CaseSensitiveFileNames: " + useCaseSensitiveFileNames);
110899         var configFileWatcher;
110900         if (configFileName) {
110901             configFileWatcher = watchFile(host, configFileName, scheduleProgramReload, ts.PollingInterval.High, watchOptions, ts.WatchType.ConfigFile);
110902         }
110903         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return compilerOptions; }, directoryStructureHost);
110904         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
110905         // Members for CompilerHost
110906         var getNewSourceFile = compilerHost.getSourceFile;
110907         compilerHost.getSourceFile = function (fileName) {
110908             var args = [];
110909             for (var _i = 1; _i < arguments.length; _i++) {
110910                 args[_i - 1] = arguments[_i];
110911             }
110912             return getVersionedSourceFileByPath.apply(void 0, __spreadArrays([fileName, toPath(fileName)], args));
110913         };
110914         compilerHost.getSourceFileByPath = getVersionedSourceFileByPath;
110915         compilerHost.getNewLine = function () { return newLine; };
110916         compilerHost.fileExists = fileExists;
110917         compilerHost.onReleaseOldSourceFile = onReleaseOldSourceFile;
110918         // Members for ResolutionCacheHost
110919         compilerHost.toPath = toPath;
110920         compilerHost.getCompilationSettings = function () { return compilerOptions; };
110921         compilerHost.useSourceOfProjectReferenceRedirect = ts.maybeBind(host, host.useSourceOfProjectReferenceRedirect);
110922         compilerHost.watchDirectoryOfFailedLookupLocation = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.FailedLookupLocations); };
110923         compilerHost.watchTypeRootsDirectory = function (dir, cb, flags) { return watchDirectory(host, dir, cb, flags, watchOptions, ts.WatchType.TypeRoots); };
110924         compilerHost.getCachedDirectoryStructureHost = function () { return cachedDirectoryStructureHost; };
110925         compilerHost.scheduleInvalidateResolutionsOfFailedLookupLocations = scheduleInvalidateResolutionsOfFailedLookupLocations;
110926         compilerHost.onInvalidatedResolution = scheduleProgramUpdate;
110927         compilerHost.onChangedAutomaticTypeDirectiveNames = scheduleProgramUpdate;
110928         compilerHost.fileIsOpen = ts.returnFalse;
110929         compilerHost.getCurrentProgram = getCurrentProgram;
110930         compilerHost.writeLog = writeLog;
110931         // Cache for the module resolution
110932         var resolutionCache = ts.createResolutionCache(compilerHost, configFileName ?
110933             ts.getDirectoryPath(ts.getNormalizedAbsolutePath(configFileName, currentDirectory)) :
110934             currentDirectory, 
110935         /*logChangesWhenResolvingModule*/ false);
110936         // Resolve module using host module resolution strategy if provided otherwise use resolution cache to resolve module names
110937         compilerHost.resolveModuleNames = host.resolveModuleNames ?
110938             (function () {
110939                 var args = [];
110940                 for (var _i = 0; _i < arguments.length; _i++) {
110941                     args[_i] = arguments[_i];
110942                 }
110943                 return host.resolveModuleNames.apply(host, args);
110944             }) :
110945             (function (moduleNames, containingFile, reusedNames, redirectedReference) { return resolutionCache.resolveModuleNames(moduleNames, containingFile, reusedNames, redirectedReference); });
110946         compilerHost.resolveTypeReferenceDirectives = host.resolveTypeReferenceDirectives ?
110947             (function () {
110948                 var args = [];
110949                 for (var _i = 0; _i < arguments.length; _i++) {
110950                     args[_i] = arguments[_i];
110951                 }
110952                 return host.resolveTypeReferenceDirectives.apply(host, args);
110953             }) :
110954             (function (typeDirectiveNames, containingFile, redirectedReference) { return resolutionCache.resolveTypeReferenceDirectives(typeDirectiveNames, containingFile, redirectedReference); });
110955         var userProvidedResolution = !!host.resolveModuleNames || !!host.resolveTypeReferenceDirectives;
110956         builderProgram = readBuilderProgram(compilerOptions, compilerHost);
110957         synchronizeProgram();
110958         // Update the wild card directory watch
110959         watchConfigFileWildCardDirectories();
110960         return configFileName ?
110961             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, close: close } :
110962             { getCurrentProgram: getCurrentBuilderProgram, getProgram: updateProgram, updateRootFileNames: updateRootFileNames, close: close };
110963         function close() {
110964             clearInvalidateResolutionsOfFailedLookupLocations();
110965             resolutionCache.clear();
110966             ts.clearMap(sourceFilesCache, function (value) {
110967                 if (value && value.fileWatcher) {
110968                     value.fileWatcher.close();
110969                     value.fileWatcher = undefined;
110970                 }
110971             });
110972             if (configFileWatcher) {
110973                 configFileWatcher.close();
110974                 configFileWatcher = undefined;
110975             }
110976             if (watchedWildcardDirectories) {
110977                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
110978                 watchedWildcardDirectories = undefined;
110979             }
110980             if (missingFilesMap) {
110981                 ts.clearMap(missingFilesMap, ts.closeFileWatcher);
110982                 missingFilesMap = undefined;
110983             }
110984         }
110985         function getCurrentBuilderProgram() {
110986             return builderProgram;
110987         }
110988         function getCurrentProgram() {
110989             return builderProgram && builderProgram.getProgramOrUndefined();
110990         }
110991         function synchronizeProgram() {
110992             writeLog("Synchronizing program");
110993             clearInvalidateResolutionsOfFailedLookupLocations();
110994             var program = getCurrentBuilderProgram();
110995             if (hasChangedCompilerOptions) {
110996                 newLine = updateNewLine();
110997                 if (program && ts.changesAffectModuleResolution(program.getCompilerOptions(), compilerOptions)) {
110998                     resolutionCache.clear();
110999                 }
111000             }
111001             // All resolutions are invalid if user provided resolutions
111002             var hasInvalidatedResolution = resolutionCache.createHasInvalidatedResolution(userProvidedResolution);
111003             if (ts.isProgramUptoDate(getCurrentProgram(), rootFileNames, compilerOptions, getSourceVersion, fileExists, hasInvalidatedResolution, hasChangedAutomaticTypeDirectiveNames, projectReferences)) {
111004                 if (hasChangedConfigFileParsingErrors) {
111005                     builderProgram = createProgram(/*rootNames*/ undefined, /*options*/ undefined, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
111006                     hasChangedConfigFileParsingErrors = false;
111007                 }
111008             }
111009             else {
111010                 createNewProgram(hasInvalidatedResolution);
111011             }
111012             if (host.afterProgramCreate && program !== builderProgram) {
111013                 host.afterProgramCreate(builderProgram);
111014             }
111015             return builderProgram;
111016         }
111017         function createNewProgram(hasInvalidatedResolution) {
111018             // Compile the program
111019             writeLog("CreatingProgramWith::");
111020             writeLog("  roots: " + JSON.stringify(rootFileNames));
111021             writeLog("  options: " + JSON.stringify(compilerOptions));
111022             var needsUpdateInTypeRootWatch = hasChangedCompilerOptions || !getCurrentProgram();
111023             hasChangedCompilerOptions = false;
111024             hasChangedConfigFileParsingErrors = false;
111025             resolutionCache.startCachingPerDirectoryResolution();
111026             compilerHost.hasInvalidatedResolution = hasInvalidatedResolution;
111027             compilerHost.hasChangedAutomaticTypeDirectiveNames = hasChangedAutomaticTypeDirectiveNames;
111028             builderProgram = createProgram(rootFileNames, compilerOptions, compilerHost, builderProgram, configFileParsingDiagnostics, projectReferences);
111029             resolutionCache.finishCachingPerDirectoryResolution();
111030             // Update watches
111031             ts.updateMissingFilePathsWatch(builderProgram.getProgram(), missingFilesMap || (missingFilesMap = new ts.Map()), watchMissingFilePath);
111032             if (needsUpdateInTypeRootWatch) {
111033                 resolutionCache.updateTypeRootsWatch();
111034             }
111035             if (missingFilePathsRequestedForRelease) {
111036                 // These are the paths that program creater told us as not in use any more but were missing on the disk.
111037                 // We didnt remove the entry for them from sourceFiles cache so that we dont have to do File IO,
111038                 // if there is already watcher for it (for missing files)
111039                 // At this point our watches were updated, hence now we know that these paths are not tracked and need to be removed
111040                 // so that at later time we have correct result of their presence
111041                 for (var _i = 0, missingFilePathsRequestedForRelease_1 = missingFilePathsRequestedForRelease; _i < missingFilePathsRequestedForRelease_1.length; _i++) {
111042                     var missingFilePath = missingFilePathsRequestedForRelease_1[_i];
111043                     if (!missingFilesMap.has(missingFilePath)) {
111044                         sourceFilesCache.delete(missingFilePath);
111045                     }
111046                 }
111047                 missingFilePathsRequestedForRelease = undefined;
111048             }
111049         }
111050         function updateRootFileNames(files) {
111051             ts.Debug.assert(!configFileName, "Cannot update root file names with config file watch mode");
111052             rootFileNames = files;
111053             scheduleProgramUpdate();
111054         }
111055         function updateNewLine() {
111056             return ts.getNewLineCharacter(compilerOptions || optionsToExtendForConfigFile, function () { return host.getNewLine(); });
111057         }
111058         function toPath(fileName) {
111059             return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
111060         }
111061         function isFileMissingOnHost(hostSourceFile) {
111062             return typeof hostSourceFile === "boolean";
111063         }
111064         function isFilePresenceUnknownOnHost(hostSourceFile) {
111065             return typeof hostSourceFile.version === "boolean";
111066         }
111067         function fileExists(fileName) {
111068             var path = toPath(fileName);
111069             // If file is missing on host from cache, we can definitely say file doesnt exist
111070             // otherwise we need to ensure from the disk
111071             if (isFileMissingOnHost(sourceFilesCache.get(path))) {
111072                 return false;
111073             }
111074             return directoryStructureHost.fileExists(fileName);
111075         }
111076         function getVersionedSourceFileByPath(fileName, path, languageVersion, onError, shouldCreateNewSourceFile) {
111077             var hostSourceFile = sourceFilesCache.get(path);
111078             // No source file on the host
111079             if (isFileMissingOnHost(hostSourceFile)) {
111080                 return undefined;
111081             }
111082             // Create new source file if requested or the versions dont match
111083             if (hostSourceFile === undefined || shouldCreateNewSourceFile || isFilePresenceUnknownOnHost(hostSourceFile)) {
111084                 var sourceFile = getNewSourceFile(fileName, languageVersion, onError);
111085                 if (hostSourceFile) {
111086                     if (sourceFile) {
111087                         // Set the source file and create file watcher now that file was present on the disk
111088                         hostSourceFile.sourceFile = sourceFile;
111089                         hostSourceFile.version = sourceFile.version;
111090                         if (!hostSourceFile.fileWatcher) {
111091                             hostSourceFile.fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
111092                         }
111093                     }
111094                     else {
111095                         // There is no source file on host any more, close the watch, missing file paths will track it
111096                         if (hostSourceFile.fileWatcher) {
111097                             hostSourceFile.fileWatcher.close();
111098                         }
111099                         sourceFilesCache.set(path, false);
111100                     }
111101                 }
111102                 else {
111103                     if (sourceFile) {
111104                         var fileWatcher = watchFilePath(host, fileName, onSourceFileChange, ts.PollingInterval.Low, watchOptions, path, ts.WatchType.SourceFile);
111105                         sourceFilesCache.set(path, { sourceFile: sourceFile, version: sourceFile.version, fileWatcher: fileWatcher });
111106                     }
111107                     else {
111108                         sourceFilesCache.set(path, false);
111109                     }
111110                 }
111111                 return sourceFile;
111112             }
111113             return hostSourceFile.sourceFile;
111114         }
111115         function nextSourceFileVersion(path) {
111116             var hostSourceFile = sourceFilesCache.get(path);
111117             if (hostSourceFile !== undefined) {
111118                 if (isFileMissingOnHost(hostSourceFile)) {
111119                     // The next version, lets set it as presence unknown file
111120                     sourceFilesCache.set(path, { version: false });
111121                 }
111122                 else {
111123                     hostSourceFile.version = false;
111124                 }
111125             }
111126         }
111127         function getSourceVersion(path) {
111128             var hostSourceFile = sourceFilesCache.get(path);
111129             return !hostSourceFile || !hostSourceFile.version ? undefined : hostSourceFile.version;
111130         }
111131         function onReleaseOldSourceFile(oldSourceFile, _oldOptions, hasSourceFileByPath) {
111132             var hostSourceFileInfo = sourceFilesCache.get(oldSourceFile.resolvedPath);
111133             // If this is the source file thats in the cache and new program doesnt need it,
111134             // remove the cached entry.
111135             // Note we arent deleting entry if file became missing in new program or
111136             // there was version update and new source file was created.
111137             if (hostSourceFileInfo !== undefined) {
111138                 // record the missing file paths so they can be removed later if watchers arent tracking them
111139                 if (isFileMissingOnHost(hostSourceFileInfo)) {
111140                     (missingFilePathsRequestedForRelease || (missingFilePathsRequestedForRelease = [])).push(oldSourceFile.path);
111141                 }
111142                 else if (hostSourceFileInfo.sourceFile === oldSourceFile) {
111143                     if (hostSourceFileInfo.fileWatcher) {
111144                         hostSourceFileInfo.fileWatcher.close();
111145                     }
111146                     sourceFilesCache.delete(oldSourceFile.resolvedPath);
111147                     if (!hasSourceFileByPath) {
111148                         resolutionCache.removeResolutionsOfFile(oldSourceFile.path);
111149                     }
111150                 }
111151             }
111152         }
111153         function reportWatchDiagnostic(message) {
111154             if (host.onWatchStatusChange) {
111155                 host.onWatchStatusChange(ts.createCompilerDiagnostic(message), newLine, compilerOptions || optionsToExtendForConfigFile);
111156             }
111157         }
111158         function hasChangedAutomaticTypeDirectiveNames() {
111159             return resolutionCache.hasChangedAutomaticTypeDirectiveNames();
111160         }
111161         function clearInvalidateResolutionsOfFailedLookupLocations() {
111162             if (!timerToInvalidateFailedLookupResolutions)
111163                 return false;
111164             host.clearTimeout(timerToInvalidateFailedLookupResolutions);
111165             timerToInvalidateFailedLookupResolutions = undefined;
111166             return true;
111167         }
111168         function scheduleInvalidateResolutionsOfFailedLookupLocations() {
111169             if (!host.setTimeout || !host.clearTimeout) {
111170                 return resolutionCache.invalidateResolutionsOfFailedLookupLocations();
111171             }
111172             var pending = clearInvalidateResolutionsOfFailedLookupLocations();
111173             writeLog("Scheduling invalidateFailedLookup" + (pending ? ", Cancelled earlier one" : ""));
111174             timerToInvalidateFailedLookupResolutions = host.setTimeout(invalidateResolutionsOfFailedLookup, 250);
111175         }
111176         function invalidateResolutionsOfFailedLookup() {
111177             timerToInvalidateFailedLookupResolutions = undefined;
111178             if (resolutionCache.invalidateResolutionsOfFailedLookupLocations()) {
111179                 scheduleProgramUpdate();
111180             }
111181         }
111182         // Upon detecting a file change, wait for 250ms and then perform a recompilation. This gives batch
111183         // operations (such as saving all modified files in an editor) a chance to complete before we kick
111184         // off a new compilation.
111185         function scheduleProgramUpdate() {
111186             if (!host.setTimeout || !host.clearTimeout) {
111187                 return;
111188             }
111189             if (timerToUpdateProgram) {
111190                 host.clearTimeout(timerToUpdateProgram);
111191             }
111192             writeLog("Scheduling update");
111193             timerToUpdateProgram = host.setTimeout(updateProgramWithWatchStatus, 250);
111194         }
111195         function scheduleProgramReload() {
111196             ts.Debug.assert(!!configFileName);
111197             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
111198             scheduleProgramUpdate();
111199         }
111200         function updateProgramWithWatchStatus() {
111201             timerToUpdateProgram = undefined;
111202             reportWatchDiagnostic(ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
111203             updateProgram();
111204         }
111205         function updateProgram() {
111206             switch (reloadLevel) {
111207                 case ts.ConfigFileProgramReloadLevel.Partial:
111208                     ts.perfLogger.logStartUpdateProgram("PartialConfigReload");
111209                     reloadFileNamesFromConfigFile();
111210                     break;
111211                 case ts.ConfigFileProgramReloadLevel.Full:
111212                     ts.perfLogger.logStartUpdateProgram("FullConfigReload");
111213                     reloadConfigFile();
111214                     break;
111215                 default:
111216                     ts.perfLogger.logStartUpdateProgram("SynchronizeProgram");
111217                     synchronizeProgram();
111218                     break;
111219             }
111220             ts.perfLogger.logStopUpdateProgram("Done");
111221             return getCurrentBuilderProgram();
111222         }
111223         function reloadFileNamesFromConfigFile() {
111224             writeLog("Reloading new file names and options");
111225             var result = ts.getFileNamesFromConfigSpecs(configFileSpecs, ts.getNormalizedAbsolutePath(ts.getDirectoryPath(configFileName), currentDirectory), compilerOptions, parseConfigFileHost, extraFileExtensions);
111226             if (ts.updateErrorForNoInputFiles(result, ts.getNormalizedAbsolutePath(configFileName, currentDirectory), configFileSpecs, configFileParsingDiagnostics, canConfigFileJsonReportNoInputFiles)) {
111227                 hasChangedConfigFileParsingErrors = true;
111228             }
111229             rootFileNames = result.fileNames;
111230             // Update the program
111231             synchronizeProgram();
111232         }
111233         function reloadConfigFile() {
111234             writeLog("Reloading config file: " + configFileName);
111235             reloadLevel = ts.ConfigFileProgramReloadLevel.None;
111236             if (cachedDirectoryStructureHost) {
111237                 cachedDirectoryStructureHost.clearCache();
111238             }
111239             parseConfigFile();
111240             hasChangedCompilerOptions = true;
111241             synchronizeProgram();
111242             // Update the wild card directory watch
111243             watchConfigFileWildCardDirectories();
111244         }
111245         function parseConfigFile() {
111246             setConfigFileParsingResult(ts.getParsedCommandLineOfConfigFile(configFileName, optionsToExtendForConfigFile, parseConfigFileHost, /*extendedConfigCache*/ undefined, watchOptionsToExtend, extraFileExtensions)); // TODO: GH#18217
111247         }
111248         function setConfigFileParsingResult(configFileParseResult) {
111249             rootFileNames = configFileParseResult.fileNames;
111250             compilerOptions = configFileParseResult.options;
111251             watchOptions = configFileParseResult.watchOptions;
111252             configFileSpecs = configFileParseResult.configFileSpecs; // TODO: GH#18217
111253             projectReferences = configFileParseResult.projectReferences;
111254             configFileParsingDiagnostics = ts.getConfigFileParsingDiagnostics(configFileParseResult).slice();
111255             canConfigFileJsonReportNoInputFiles = ts.canJsonReportNoInputFiles(configFileParseResult.raw);
111256             hasChangedConfigFileParsingErrors = true;
111257         }
111258         function onSourceFileChange(fileName, eventKind, path) {
111259             updateCachedSystemWithFile(fileName, path, eventKind);
111260             // Update the source file cache
111261             if (eventKind === ts.FileWatcherEventKind.Deleted && sourceFilesCache.has(path)) {
111262                 resolutionCache.invalidateResolutionOfFile(path);
111263             }
111264             resolutionCache.removeResolutionsFromProjectReferenceRedirects(path);
111265             nextSourceFileVersion(path);
111266             // Update the program
111267             scheduleProgramUpdate();
111268         }
111269         function updateCachedSystemWithFile(fileName, path, eventKind) {
111270             if (cachedDirectoryStructureHost) {
111271                 cachedDirectoryStructureHost.addOrDeleteFile(fileName, path, eventKind);
111272             }
111273         }
111274         function watchMissingFilePath(missingFilePath) {
111275             return watchFilePath(host, missingFilePath, onMissingFileChange, ts.PollingInterval.Medium, watchOptions, missingFilePath, ts.WatchType.MissingFile);
111276         }
111277         function onMissingFileChange(fileName, eventKind, missingFilePath) {
111278             updateCachedSystemWithFile(fileName, missingFilePath, eventKind);
111279             if (eventKind === ts.FileWatcherEventKind.Created && missingFilesMap.has(missingFilePath)) {
111280                 missingFilesMap.get(missingFilePath).close();
111281                 missingFilesMap.delete(missingFilePath);
111282                 // Delete the entry in the source files cache so that new source file is created
111283                 nextSourceFileVersion(missingFilePath);
111284                 // When a missing file is created, we should update the graph.
111285                 scheduleProgramUpdate();
111286             }
111287         }
111288         function watchConfigFileWildCardDirectories() {
111289             if (configFileSpecs) {
111290                 ts.updateWatchingWildcardDirectories(watchedWildcardDirectories || (watchedWildcardDirectories = new ts.Map()), new ts.Map(ts.getEntries(configFileSpecs.wildcardDirectories)), watchWildcardDirectory);
111291             }
111292             else if (watchedWildcardDirectories) {
111293                 ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf);
111294             }
111295         }
111296         function watchWildcardDirectory(directory, flags) {
111297             return watchDirectory(host, directory, function (fileOrDirectory) {
111298                 ts.Debug.assert(!!configFileName);
111299                 var fileOrDirectoryPath = toPath(fileOrDirectory);
111300                 // Since the file existence changed, update the sourceFiles cache
111301                 if (cachedDirectoryStructureHost) {
111302                     cachedDirectoryStructureHost.addOrDeleteFileOrDirectory(fileOrDirectory, fileOrDirectoryPath);
111303                 }
111304                 nextSourceFileVersion(fileOrDirectoryPath);
111305                 if (ts.isIgnoredFileFromWildCardWatching({
111306                     watchedDirPath: toPath(directory),
111307                     fileOrDirectory: fileOrDirectory,
111308                     fileOrDirectoryPath: fileOrDirectoryPath,
111309                     configFileName: configFileName,
111310                     configFileSpecs: configFileSpecs,
111311                     extraFileExtensions: extraFileExtensions,
111312                     options: compilerOptions,
111313                     program: getCurrentBuilderProgram(),
111314                     currentDirectory: currentDirectory,
111315                     useCaseSensitiveFileNames: useCaseSensitiveFileNames,
111316                     writeLog: writeLog
111317                 }))
111318                     return;
111319                 // Reload is pending, do the reload
111320                 if (reloadLevel !== ts.ConfigFileProgramReloadLevel.Full) {
111321                     reloadLevel = ts.ConfigFileProgramReloadLevel.Partial;
111322                     // Schedule Update the program
111323                     scheduleProgramUpdate();
111324                 }
111325             }, flags, watchOptions, ts.WatchType.WildcardDirectory);
111326         }
111327     }
111328     ts.createWatchProgram = createWatchProgram;
111329 })(ts || (ts = {}));
111330 /*@internal*/
111331 var ts;
111332 (function (ts) {
111333     var UpToDateStatusType;
111334     (function (UpToDateStatusType) {
111335         UpToDateStatusType[UpToDateStatusType["Unbuildable"] = 0] = "Unbuildable";
111336         UpToDateStatusType[UpToDateStatusType["UpToDate"] = 1] = "UpToDate";
111337         /**
111338          * The project appears out of date because its upstream inputs are newer than its outputs,
111339          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
111340          * This means we can Pseudo-build (just touch timestamps), as if we had actually built this project.
111341          */
111342         UpToDateStatusType[UpToDateStatusType["UpToDateWithUpstreamTypes"] = 2] = "UpToDateWithUpstreamTypes";
111343         /**
111344          * The project appears out of date because its upstream inputs are newer than its outputs,
111345          * but all of its outputs are actually newer than the previous identical outputs of its (.d.ts) inputs.
111346          * This means we can Pseudo-build (just manipulate outputs), as if we had actually built this project.
111347          */
111348         UpToDateStatusType[UpToDateStatusType["OutOfDateWithPrepend"] = 3] = "OutOfDateWithPrepend";
111349         UpToDateStatusType[UpToDateStatusType["OutputMissing"] = 4] = "OutputMissing";
111350         UpToDateStatusType[UpToDateStatusType["OutOfDateWithSelf"] = 5] = "OutOfDateWithSelf";
111351         UpToDateStatusType[UpToDateStatusType["OutOfDateWithUpstream"] = 6] = "OutOfDateWithUpstream";
111352         UpToDateStatusType[UpToDateStatusType["UpstreamOutOfDate"] = 7] = "UpstreamOutOfDate";
111353         UpToDateStatusType[UpToDateStatusType["UpstreamBlocked"] = 8] = "UpstreamBlocked";
111354         UpToDateStatusType[UpToDateStatusType["ComputingUpstream"] = 9] = "ComputingUpstream";
111355         UpToDateStatusType[UpToDateStatusType["TsVersionOutputOfDate"] = 10] = "TsVersionOutputOfDate";
111356         /**
111357          * Projects with no outputs (i.e. "solution" files)
111358          */
111359         UpToDateStatusType[UpToDateStatusType["ContainerOnly"] = 11] = "ContainerOnly";
111360     })(UpToDateStatusType = ts.UpToDateStatusType || (ts.UpToDateStatusType = {}));
111361     function resolveConfigFileProjectName(project) {
111362         if (ts.fileExtensionIs(project, ".json" /* Json */)) {
111363             return project;
111364         }
111365         return ts.combinePaths(project, "tsconfig.json");
111366     }
111367     ts.resolveConfigFileProjectName = resolveConfigFileProjectName;
111368 })(ts || (ts = {}));
111369 var ts;
111370 (function (ts) {
111371     var minimumDate = new Date(-8640000000000000);
111372     var maximumDate = new Date(8640000000000000);
111373     var BuildResultFlags;
111374     (function (BuildResultFlags) {
111375         BuildResultFlags[BuildResultFlags["None"] = 0] = "None";
111376         /**
111377          * No errors of any kind occurred during build
111378          */
111379         BuildResultFlags[BuildResultFlags["Success"] = 1] = "Success";
111380         /**
111381          * None of the .d.ts files emitted by this build were
111382          * different from the existing files on disk
111383          */
111384         BuildResultFlags[BuildResultFlags["DeclarationOutputUnchanged"] = 2] = "DeclarationOutputUnchanged";
111385         BuildResultFlags[BuildResultFlags["ConfigFileErrors"] = 4] = "ConfigFileErrors";
111386         BuildResultFlags[BuildResultFlags["SyntaxErrors"] = 8] = "SyntaxErrors";
111387         BuildResultFlags[BuildResultFlags["TypeErrors"] = 16] = "TypeErrors";
111388         BuildResultFlags[BuildResultFlags["DeclarationEmitErrors"] = 32] = "DeclarationEmitErrors";
111389         BuildResultFlags[BuildResultFlags["EmitErrors"] = 64] = "EmitErrors";
111390         BuildResultFlags[BuildResultFlags["AnyErrors"] = 124] = "AnyErrors";
111391     })(BuildResultFlags || (BuildResultFlags = {}));
111392     function getOrCreateValueFromConfigFileMap(configFileMap, resolved, createT) {
111393         var existingValue = configFileMap.get(resolved);
111394         var newValue;
111395         if (!existingValue) {
111396             newValue = createT();
111397             configFileMap.set(resolved, newValue);
111398         }
111399         return existingValue || newValue;
111400     }
111401     function getOrCreateValueMapFromConfigFileMap(configFileMap, resolved) {
111402         return getOrCreateValueFromConfigFileMap(configFileMap, resolved, function () { return new ts.Map(); });
111403     }
111404     function newer(date1, date2) {
111405         return date2 > date1 ? date2 : date1;
111406     }
111407     function isDeclarationFile(fileName) {
111408         return ts.fileExtensionIs(fileName, ".d.ts" /* Dts */);
111409     }
111410     /*@internal*/
111411     function isCircularBuildOrder(buildOrder) {
111412         return !!buildOrder && !!buildOrder.buildOrder;
111413     }
111414     ts.isCircularBuildOrder = isCircularBuildOrder;
111415     /*@internal*/
111416     function getBuildOrderFromAnyBuildOrder(anyBuildOrder) {
111417         return isCircularBuildOrder(anyBuildOrder) ? anyBuildOrder.buildOrder : anyBuildOrder;
111418     }
111419     ts.getBuildOrderFromAnyBuildOrder = getBuildOrderFromAnyBuildOrder;
111420     /**
111421      * Create a function that reports watch status by writing to the system and handles the formating of the diagnostic
111422      */
111423     function createBuilderStatusReporter(system, pretty) {
111424         return function (diagnostic) {
111425             var output = pretty ? "[" + ts.formatColorAndReset(ts.getLocaleTimeString(system), ts.ForegroundColorEscapeSequences.Grey) + "] " : ts.getLocaleTimeString(system) + " - ";
111426             output += "" + ts.flattenDiagnosticMessageText(diagnostic.messageText, system.newLine) + (system.newLine + system.newLine);
111427             system.write(output);
111428         };
111429     }
111430     ts.createBuilderStatusReporter = createBuilderStatusReporter;
111431     function createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus) {
111432         var host = ts.createProgramHost(system, createProgram);
111433         host.getModifiedTime = system.getModifiedTime ? function (path) { return system.getModifiedTime(path); } : ts.returnUndefined;
111434         host.setModifiedTime = system.setModifiedTime ? function (path, date) { return system.setModifiedTime(path, date); } : ts.noop;
111435         host.deleteFile = system.deleteFile ? function (path) { return system.deleteFile(path); } : ts.noop;
111436         host.reportDiagnostic = reportDiagnostic || ts.createDiagnosticReporter(system);
111437         host.reportSolutionBuilderStatus = reportSolutionBuilderStatus || createBuilderStatusReporter(system);
111438         host.now = ts.maybeBind(system, system.now); // For testing
111439         return host;
111440     }
111441     function createSolutionBuilderHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportErrorSummary) {
111442         if (system === void 0) { system = ts.sys; }
111443         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
111444         host.reportErrorSummary = reportErrorSummary;
111445         return host;
111446     }
111447     ts.createSolutionBuilderHost = createSolutionBuilderHost;
111448     function createSolutionBuilderWithWatchHost(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus, reportWatchStatus) {
111449         if (system === void 0) { system = ts.sys; }
111450         var host = createSolutionBuilderHostBase(system, createProgram, reportDiagnostic, reportSolutionBuilderStatus);
111451         var watchHost = ts.createWatchHost(system, reportWatchStatus);
111452         ts.copyProperties(host, watchHost);
111453         return host;
111454     }
111455     ts.createSolutionBuilderWithWatchHost = createSolutionBuilderWithWatchHost;
111456     function getCompilerOptionsOfBuildOptions(buildOptions) {
111457         var result = {};
111458         ts.commonOptionsWithBuild.forEach(function (option) {
111459             if (ts.hasProperty(buildOptions, option.name))
111460                 result[option.name] = buildOptions[option.name];
111461         });
111462         return result;
111463     }
111464     function createSolutionBuilder(host, rootNames, defaultOptions) {
111465         return createSolutionBuilderWorker(/*watch*/ false, host, rootNames, defaultOptions);
111466     }
111467     ts.createSolutionBuilder = createSolutionBuilder;
111468     function createSolutionBuilderWithWatch(host, rootNames, defaultOptions, baseWatchOptions) {
111469         return createSolutionBuilderWorker(/*watch*/ true, host, rootNames, defaultOptions, baseWatchOptions);
111470     }
111471     ts.createSolutionBuilderWithWatch = createSolutionBuilderWithWatch;
111472     function createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
111473         var host = hostOrHostWithWatch;
111474         var hostWithWatch = hostOrHostWithWatch;
111475         var currentDirectory = host.getCurrentDirectory();
111476         var getCanonicalFileName = ts.createGetCanonicalFileName(host.useCaseSensitiveFileNames());
111477         // State of the solution
111478         var baseCompilerOptions = getCompilerOptionsOfBuildOptions(options);
111479         var compilerHost = ts.createCompilerHostFromProgramHost(host, function () { return state.projectCompilerOptions; });
111480         ts.setGetSourceFileAsHashVersioned(compilerHost, host);
111481         compilerHost.getParsedCommandLine = function (fileName) { return parseConfigFile(state, fileName, toResolvedConfigFilePath(state, fileName)); };
111482         compilerHost.resolveModuleNames = ts.maybeBind(host, host.resolveModuleNames);
111483         compilerHost.resolveTypeReferenceDirectives = ts.maybeBind(host, host.resolveTypeReferenceDirectives);
111484         var moduleResolutionCache = !compilerHost.resolveModuleNames ? ts.createModuleResolutionCache(currentDirectory, getCanonicalFileName) : undefined;
111485         if (!compilerHost.resolveModuleNames) {
111486             var loader_3 = function (moduleName, containingFile, redirectedReference) { return ts.resolveModuleName(moduleName, containingFile, state.projectCompilerOptions, compilerHost, moduleResolutionCache, redirectedReference).resolvedModule; };
111487             compilerHost.resolveModuleNames = function (moduleNames, containingFile, _reusedNames, redirectedReference) {
111488                 return ts.loadWithLocalCache(ts.Debug.checkEachDefined(moduleNames), containingFile, redirectedReference, loader_3);
111489             };
111490         }
111491         var _a = ts.createWatchFactory(hostWithWatch, options), watchFile = _a.watchFile, watchFilePath = _a.watchFilePath, watchDirectory = _a.watchDirectory, writeLog = _a.writeLog;
111492         var state = {
111493             host: host,
111494             hostWithWatch: hostWithWatch,
111495             currentDirectory: currentDirectory,
111496             getCanonicalFileName: getCanonicalFileName,
111497             parseConfigFileHost: ts.parseConfigHostFromCompilerHostLike(host),
111498             writeFileName: host.trace ? function (s) { return host.trace(s); } : undefined,
111499             // State of solution
111500             options: options,
111501             baseCompilerOptions: baseCompilerOptions,
111502             rootNames: rootNames,
111503             baseWatchOptions: baseWatchOptions,
111504             resolvedConfigFilePaths: new ts.Map(),
111505             configFileCache: new ts.Map(),
111506             projectStatus: new ts.Map(),
111507             buildInfoChecked: new ts.Map(),
111508             extendedConfigCache: new ts.Map(),
111509             builderPrograms: new ts.Map(),
111510             diagnostics: new ts.Map(),
111511             projectPendingBuild: new ts.Map(),
111512             projectErrorsReported: new ts.Map(),
111513             compilerHost: compilerHost,
111514             moduleResolutionCache: moduleResolutionCache,
111515             // Mutable state
111516             buildOrder: undefined,
111517             readFileWithCache: function (f) { return host.readFile(f); },
111518             projectCompilerOptions: baseCompilerOptions,
111519             cache: undefined,
111520             allProjectBuildPending: true,
111521             needsSummary: true,
111522             watchAllProjectsPending: watch,
111523             currentInvalidatedProject: undefined,
111524             // Watch state
111525             watch: watch,
111526             allWatchedWildcardDirectories: new ts.Map(),
111527             allWatchedInputFiles: new ts.Map(),
111528             allWatchedConfigFiles: new ts.Map(),
111529             timerToBuildInvalidatedProject: undefined,
111530             reportFileChangeDetected: false,
111531             watchFile: watchFile,
111532             watchFilePath: watchFilePath,
111533             watchDirectory: watchDirectory,
111534             writeLog: writeLog,
111535         };
111536         return state;
111537     }
111538     function toPath(state, fileName) {
111539         return ts.toPath(fileName, state.currentDirectory, state.getCanonicalFileName);
111540     }
111541     function toResolvedConfigFilePath(state, fileName) {
111542         var resolvedConfigFilePaths = state.resolvedConfigFilePaths;
111543         var path = resolvedConfigFilePaths.get(fileName);
111544         if (path !== undefined)
111545             return path;
111546         var resolvedPath = toPath(state, fileName);
111547         resolvedConfigFilePaths.set(fileName, resolvedPath);
111548         return resolvedPath;
111549     }
111550     function isParsedCommandLine(entry) {
111551         return !!entry.options;
111552     }
111553     function parseConfigFile(state, configFileName, configFilePath) {
111554         var configFileCache = state.configFileCache;
111555         var value = configFileCache.get(configFilePath);
111556         if (value) {
111557             return isParsedCommandLine(value) ? value : undefined;
111558         }
111559         var diagnostic;
111560         var parseConfigFileHost = state.parseConfigFileHost, baseCompilerOptions = state.baseCompilerOptions, baseWatchOptions = state.baseWatchOptions, extendedConfigCache = state.extendedConfigCache, host = state.host;
111561         var parsed;
111562         if (host.getParsedCommandLine) {
111563             parsed = host.getParsedCommandLine(configFileName);
111564             if (!parsed)
111565                 diagnostic = ts.createCompilerDiagnostic(ts.Diagnostics.File_0_not_found, configFileName);
111566         }
111567         else {
111568             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = function (d) { return diagnostic = d; };
111569             parsed = ts.getParsedCommandLineOfConfigFile(configFileName, baseCompilerOptions, parseConfigFileHost, extendedConfigCache, baseWatchOptions);
111570             parseConfigFileHost.onUnRecoverableConfigFileDiagnostic = ts.noop;
111571         }
111572         configFileCache.set(configFilePath, parsed || diagnostic);
111573         return parsed;
111574     }
111575     function resolveProjectName(state, name) {
111576         return ts.resolveConfigFileProjectName(ts.resolvePath(state.currentDirectory, name));
111577     }
111578     function createBuildOrder(state, roots) {
111579         var temporaryMarks = new ts.Map();
111580         var permanentMarks = new ts.Map();
111581         var circularityReportStack = [];
111582         var buildOrder;
111583         var circularDiagnostics;
111584         for (var _i = 0, roots_1 = roots; _i < roots_1.length; _i++) {
111585             var root = roots_1[_i];
111586             visit(root);
111587         }
111588         return circularDiagnostics ?
111589             { buildOrder: buildOrder || ts.emptyArray, circularDiagnostics: circularDiagnostics } :
111590             buildOrder || ts.emptyArray;
111591         function visit(configFileName, inCircularContext) {
111592             var projPath = toResolvedConfigFilePath(state, configFileName);
111593             // Already visited
111594             if (permanentMarks.has(projPath))
111595                 return;
111596             // Circular
111597             if (temporaryMarks.has(projPath)) {
111598                 if (!inCircularContext) {
111599                     (circularDiagnostics || (circularDiagnostics = [])).push(ts.createCompilerDiagnostic(ts.Diagnostics.Project_references_may_not_form_a_circular_graph_Cycle_detected_Colon_0, circularityReportStack.join("\r\n")));
111600                 }
111601                 return;
111602             }
111603             temporaryMarks.set(projPath, true);
111604             circularityReportStack.push(configFileName);
111605             var parsed = parseConfigFile(state, configFileName, projPath);
111606             if (parsed && parsed.projectReferences) {
111607                 for (var _i = 0, _a = parsed.projectReferences; _i < _a.length; _i++) {
111608                     var ref = _a[_i];
111609                     var resolvedRefPath = resolveProjectName(state, ref.path);
111610                     visit(resolvedRefPath, inCircularContext || ref.circular);
111611                 }
111612             }
111613             circularityReportStack.pop();
111614             permanentMarks.set(projPath, true);
111615             (buildOrder || (buildOrder = [])).push(configFileName);
111616         }
111617     }
111618     function getBuildOrder(state) {
111619         return state.buildOrder || createStateBuildOrder(state);
111620     }
111621     function createStateBuildOrder(state) {
111622         var buildOrder = createBuildOrder(state, state.rootNames.map(function (f) { return resolveProjectName(state, f); }));
111623         // Clear all to ResolvedConfigFilePaths cache to start fresh
111624         state.resolvedConfigFilePaths.clear();
111625         // TODO(rbuckton): Should be a `Set`, but that requires changing the code below that uses `mutateMapSkippingNewValues`
111626         var currentProjects = new ts.Map(getBuildOrderFromAnyBuildOrder(buildOrder).map(function (resolved) { return [toResolvedConfigFilePath(state, resolved), true]; }));
111627         var noopOnDelete = { onDeleteValue: ts.noop };
111628         // Config file cache
111629         ts.mutateMapSkippingNewValues(state.configFileCache, currentProjects, noopOnDelete);
111630         ts.mutateMapSkippingNewValues(state.projectStatus, currentProjects, noopOnDelete);
111631         ts.mutateMapSkippingNewValues(state.buildInfoChecked, currentProjects, noopOnDelete);
111632         ts.mutateMapSkippingNewValues(state.builderPrograms, currentProjects, noopOnDelete);
111633         ts.mutateMapSkippingNewValues(state.diagnostics, currentProjects, noopOnDelete);
111634         ts.mutateMapSkippingNewValues(state.projectPendingBuild, currentProjects, noopOnDelete);
111635         ts.mutateMapSkippingNewValues(state.projectErrorsReported, currentProjects, noopOnDelete);
111636         // Remove watches for the program no longer in the solution
111637         if (state.watch) {
111638             ts.mutateMapSkippingNewValues(state.allWatchedConfigFiles, currentProjects, { onDeleteValue: ts.closeFileWatcher });
111639             ts.mutateMapSkippingNewValues(state.allWatchedWildcardDirectories, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcherOf); } });
111640             ts.mutateMapSkippingNewValues(state.allWatchedInputFiles, currentProjects, { onDeleteValue: function (existingMap) { return existingMap.forEach(ts.closeFileWatcher); } });
111641         }
111642         return state.buildOrder = buildOrder;
111643     }
111644     function getBuildOrderFor(state, project, onlyReferences) {
111645         var resolvedProject = project && resolveProjectName(state, project);
111646         var buildOrderFromState = getBuildOrder(state);
111647         if (isCircularBuildOrder(buildOrderFromState))
111648             return buildOrderFromState;
111649         if (resolvedProject) {
111650             var projectPath_1 = toResolvedConfigFilePath(state, resolvedProject);
111651             var projectIndex = ts.findIndex(buildOrderFromState, function (configFileName) { return toResolvedConfigFilePath(state, configFileName) === projectPath_1; });
111652             if (projectIndex === -1)
111653                 return undefined;
111654         }
111655         var buildOrder = resolvedProject ? createBuildOrder(state, [resolvedProject]) : buildOrderFromState;
111656         ts.Debug.assert(!isCircularBuildOrder(buildOrder));
111657         ts.Debug.assert(!onlyReferences || resolvedProject !== undefined);
111658         ts.Debug.assert(!onlyReferences || buildOrder[buildOrder.length - 1] === resolvedProject);
111659         return onlyReferences ? buildOrder.slice(0, buildOrder.length - 1) : buildOrder;
111660     }
111661     function enableCache(state) {
111662         if (state.cache) {
111663             disableCache(state);
111664         }
111665         var compilerHost = state.compilerHost, host = state.host;
111666         var originalReadFileWithCache = state.readFileWithCache;
111667         var originalGetSourceFile = compilerHost.getSourceFile;
111668         var _a = ts.changeCompilerHostLikeToUseCache(host, function (fileName) { return toPath(state, fileName); }, function () {
111669             var args = [];
111670             for (var _i = 0; _i < arguments.length; _i++) {
111671                 args[_i] = arguments[_i];
111672             }
111673             return originalGetSourceFile.call.apply(originalGetSourceFile, __spreadArrays([compilerHost], args));
111674         }), originalReadFile = _a.originalReadFile, originalFileExists = _a.originalFileExists, originalDirectoryExists = _a.originalDirectoryExists, originalCreateDirectory = _a.originalCreateDirectory, originalWriteFile = _a.originalWriteFile, getSourceFileWithCache = _a.getSourceFileWithCache, readFileWithCache = _a.readFileWithCache;
111675         state.readFileWithCache = readFileWithCache;
111676         compilerHost.getSourceFile = getSourceFileWithCache;
111677         state.cache = {
111678             originalReadFile: originalReadFile,
111679             originalFileExists: originalFileExists,
111680             originalDirectoryExists: originalDirectoryExists,
111681             originalCreateDirectory: originalCreateDirectory,
111682             originalWriteFile: originalWriteFile,
111683             originalReadFileWithCache: originalReadFileWithCache,
111684             originalGetSourceFile: originalGetSourceFile,
111685         };
111686     }
111687     function disableCache(state) {
111688         if (!state.cache)
111689             return;
111690         var cache = state.cache, host = state.host, compilerHost = state.compilerHost, extendedConfigCache = state.extendedConfigCache, moduleResolutionCache = state.moduleResolutionCache;
111691         host.readFile = cache.originalReadFile;
111692         host.fileExists = cache.originalFileExists;
111693         host.directoryExists = cache.originalDirectoryExists;
111694         host.createDirectory = cache.originalCreateDirectory;
111695         host.writeFile = cache.originalWriteFile;
111696         compilerHost.getSourceFile = cache.originalGetSourceFile;
111697         state.readFileWithCache = cache.originalReadFileWithCache;
111698         extendedConfigCache.clear();
111699         if (moduleResolutionCache) {
111700             moduleResolutionCache.directoryToModuleNameMap.clear();
111701             moduleResolutionCache.moduleNameToDirectoryMap.clear();
111702         }
111703         state.cache = undefined;
111704     }
111705     function clearProjectStatus(state, resolved) {
111706         state.projectStatus.delete(resolved);
111707         state.diagnostics.delete(resolved);
111708     }
111709     function addProjToQueue(_a, proj, reloadLevel) {
111710         var projectPendingBuild = _a.projectPendingBuild;
111711         var value = projectPendingBuild.get(proj);
111712         if (value === undefined) {
111713             projectPendingBuild.set(proj, reloadLevel);
111714         }
111715         else if (value < reloadLevel) {
111716             projectPendingBuild.set(proj, reloadLevel);
111717         }
111718     }
111719     function setupInitialBuild(state, cancellationToken) {
111720         // Set initial build if not already built
111721         if (!state.allProjectBuildPending)
111722             return;
111723         state.allProjectBuildPending = false;
111724         if (state.options.watch) {
111725             reportWatchStatus(state, ts.Diagnostics.Starting_compilation_in_watch_mode);
111726         }
111727         enableCache(state);
111728         var buildOrder = getBuildOrderFromAnyBuildOrder(getBuildOrder(state));
111729         buildOrder.forEach(function (configFileName) {
111730             return state.projectPendingBuild.set(toResolvedConfigFilePath(state, configFileName), ts.ConfigFileProgramReloadLevel.None);
111731         });
111732         if (cancellationToken) {
111733             cancellationToken.throwIfCancellationRequested();
111734         }
111735     }
111736     var InvalidatedProjectKind;
111737     (function (InvalidatedProjectKind) {
111738         InvalidatedProjectKind[InvalidatedProjectKind["Build"] = 0] = "Build";
111739         InvalidatedProjectKind[InvalidatedProjectKind["UpdateBundle"] = 1] = "UpdateBundle";
111740         InvalidatedProjectKind[InvalidatedProjectKind["UpdateOutputFileStamps"] = 2] = "UpdateOutputFileStamps";
111741     })(InvalidatedProjectKind = ts.InvalidatedProjectKind || (ts.InvalidatedProjectKind = {}));
111742     function doneInvalidatedProject(state, projectPath) {
111743         state.projectPendingBuild.delete(projectPath);
111744         state.currentInvalidatedProject = undefined;
111745         return state.diagnostics.has(projectPath) ?
111746             ts.ExitStatus.DiagnosticsPresent_OutputsSkipped :
111747             ts.ExitStatus.Success;
111748     }
111749     function createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder) {
111750         var updateOutputFileStampsPending = true;
111751         return {
111752             kind: InvalidatedProjectKind.UpdateOutputFileStamps,
111753             project: project,
111754             projectPath: projectPath,
111755             buildOrder: buildOrder,
111756             getCompilerOptions: function () { return config.options; },
111757             getCurrentDirectory: function () { return state.currentDirectory; },
111758             updateOutputFileStatmps: function () {
111759                 updateOutputTimestamps(state, config, projectPath);
111760                 updateOutputFileStampsPending = false;
111761             },
111762             done: function () {
111763                 if (updateOutputFileStampsPending) {
111764                     updateOutputTimestamps(state, config, projectPath);
111765                 }
111766                 return doneInvalidatedProject(state, projectPath);
111767             }
111768         };
111769     }
111770     var BuildStep;
111771     (function (BuildStep) {
111772         BuildStep[BuildStep["CreateProgram"] = 0] = "CreateProgram";
111773         BuildStep[BuildStep["SyntaxDiagnostics"] = 1] = "SyntaxDiagnostics";
111774         BuildStep[BuildStep["SemanticDiagnostics"] = 2] = "SemanticDiagnostics";
111775         BuildStep[BuildStep["Emit"] = 3] = "Emit";
111776         BuildStep[BuildStep["EmitBundle"] = 4] = "EmitBundle";
111777         BuildStep[BuildStep["EmitBuildInfo"] = 5] = "EmitBuildInfo";
111778         BuildStep[BuildStep["BuildInvalidatedProjectOfBundle"] = 6] = "BuildInvalidatedProjectOfBundle";
111779         BuildStep[BuildStep["QueueReferencingProjects"] = 7] = "QueueReferencingProjects";
111780         BuildStep[BuildStep["Done"] = 8] = "Done";
111781     })(BuildStep || (BuildStep = {}));
111782     function createBuildOrUpdateInvalidedProject(kind, state, project, projectPath, projectIndex, config, buildOrder) {
111783         var step = kind === InvalidatedProjectKind.Build ? BuildStep.CreateProgram : BuildStep.EmitBundle;
111784         var program;
111785         var buildResult;
111786         var invalidatedProjectOfBundle;
111787         return kind === InvalidatedProjectKind.Build ?
111788             {
111789                 kind: kind,
111790                 project: project,
111791                 projectPath: projectPath,
111792                 buildOrder: buildOrder,
111793                 getCompilerOptions: function () { return config.options; },
111794                 getCurrentDirectory: function () { return state.currentDirectory; },
111795                 getBuilderProgram: function () { return withProgramOrUndefined(ts.identity); },
111796                 getProgram: function () {
111797                     return withProgramOrUndefined(function (program) { return program.getProgramOrUndefined(); });
111798                 },
111799                 getSourceFile: function (fileName) {
111800                     return withProgramOrUndefined(function (program) { return program.getSourceFile(fileName); });
111801                 },
111802                 getSourceFiles: function () {
111803                     return withProgramOrEmptyArray(function (program) { return program.getSourceFiles(); });
111804                 },
111805                 getOptionsDiagnostics: function (cancellationToken) {
111806                     return withProgramOrEmptyArray(function (program) { return program.getOptionsDiagnostics(cancellationToken); });
111807                 },
111808                 getGlobalDiagnostics: function (cancellationToken) {
111809                     return withProgramOrEmptyArray(function (program) { return program.getGlobalDiagnostics(cancellationToken); });
111810                 },
111811                 getConfigFileParsingDiagnostics: function () {
111812                     return withProgramOrEmptyArray(function (program) { return program.getConfigFileParsingDiagnostics(); });
111813                 },
111814                 getSyntacticDiagnostics: function (sourceFile, cancellationToken) {
111815                     return withProgramOrEmptyArray(function (program) { return program.getSyntacticDiagnostics(sourceFile, cancellationToken); });
111816                 },
111817                 getAllDependencies: function (sourceFile) {
111818                     return withProgramOrEmptyArray(function (program) { return program.getAllDependencies(sourceFile); });
111819                 },
111820                 getSemanticDiagnostics: function (sourceFile, cancellationToken) {
111821                     return withProgramOrEmptyArray(function (program) { return program.getSemanticDiagnostics(sourceFile, cancellationToken); });
111822                 },
111823                 getSemanticDiagnosticsOfNextAffectedFile: function (cancellationToken, ignoreSourceFile) {
111824                     return withProgramOrUndefined(function (program) {
111825                         return (program.getSemanticDiagnosticsOfNextAffectedFile) &&
111826                             program.getSemanticDiagnosticsOfNextAffectedFile(cancellationToken, ignoreSourceFile);
111827                     });
111828                 },
111829                 emit: function (targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers) {
111830                     if (targetSourceFile || emitOnlyDtsFiles) {
111831                         return withProgramOrUndefined(function (program) { return program.emit(targetSourceFile, writeFile, cancellationToken, emitOnlyDtsFiles, customTransformers); });
111832                     }
111833                     executeSteps(BuildStep.SemanticDiagnostics, cancellationToken);
111834                     if (step === BuildStep.EmitBuildInfo) {
111835                         return emitBuildInfo(writeFile, cancellationToken);
111836                     }
111837                     if (step !== BuildStep.Emit)
111838                         return undefined;
111839                     return emit(writeFile, cancellationToken, customTransformers);
111840                 },
111841                 done: done
111842             } :
111843             {
111844                 kind: kind,
111845                 project: project,
111846                 projectPath: projectPath,
111847                 buildOrder: buildOrder,
111848                 getCompilerOptions: function () { return config.options; },
111849                 getCurrentDirectory: function () { return state.currentDirectory; },
111850                 emit: function (writeFile, customTransformers) {
111851                     if (step !== BuildStep.EmitBundle)
111852                         return invalidatedProjectOfBundle;
111853                     return emitBundle(writeFile, customTransformers);
111854                 },
111855                 done: done,
111856             };
111857         function done(cancellationToken, writeFile, customTransformers) {
111858             executeSteps(BuildStep.Done, cancellationToken, writeFile, customTransformers);
111859             return doneInvalidatedProject(state, projectPath);
111860         }
111861         function withProgramOrUndefined(action) {
111862             executeSteps(BuildStep.CreateProgram);
111863             return program && action(program);
111864         }
111865         function withProgramOrEmptyArray(action) {
111866             return withProgramOrUndefined(action) || ts.emptyArray;
111867         }
111868         function createProgram() {
111869             ts.Debug.assert(program === undefined);
111870             if (state.options.dry) {
111871                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_build_project_0, project);
111872                 buildResult = BuildResultFlags.Success;
111873                 step = BuildStep.QueueReferencingProjects;
111874                 return;
111875             }
111876             if (state.options.verbose)
111877                 reportStatus(state, ts.Diagnostics.Building_project_0, project);
111878             if (config.fileNames.length === 0) {
111879                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
111880                 // Nothing to build - must be a solution file, basically
111881                 buildResult = BuildResultFlags.None;
111882                 step = BuildStep.QueueReferencingProjects;
111883                 return;
111884             }
111885             var host = state.host, compilerHost = state.compilerHost;
111886             state.projectCompilerOptions = config.options;
111887             // Update module resolution cache if needed
111888             updateModuleResolutionCache(state, project, config);
111889             // Create program
111890             program = host.createProgram(config.fileNames, config.options, compilerHost, getOldProgram(state, projectPath, config), ts.getConfigFileParsingDiagnostics(config), config.projectReferences);
111891             if (state.watch) {
111892                 state.builderPrograms.set(projectPath, program);
111893             }
111894             step++;
111895         }
111896         function handleDiagnostics(diagnostics, errorFlags, errorType) {
111897             var _a;
111898             if (diagnostics.length) {
111899                 (_a = buildErrors(state, projectPath, program, config, diagnostics, errorFlags, errorType), buildResult = _a.buildResult, step = _a.step);
111900             }
111901             else {
111902                 step++;
111903             }
111904         }
111905         function getSyntaxDiagnostics(cancellationToken) {
111906             ts.Debug.assertIsDefined(program);
111907             handleDiagnostics(__spreadArrays(program.getConfigFileParsingDiagnostics(), program.getOptionsDiagnostics(cancellationToken), program.getGlobalDiagnostics(cancellationToken), program.getSyntacticDiagnostics(/*sourceFile*/ undefined, cancellationToken)), BuildResultFlags.SyntaxErrors, "Syntactic");
111908         }
111909         function getSemanticDiagnostics(cancellationToken) {
111910             handleDiagnostics(ts.Debug.checkDefined(program).getSemanticDiagnostics(/*sourceFile*/ undefined, cancellationToken), BuildResultFlags.TypeErrors, "Semantic");
111911         }
111912         function emit(writeFileCallback, cancellationToken, customTransformers) {
111913             var _a;
111914             ts.Debug.assertIsDefined(program);
111915             ts.Debug.assert(step === BuildStep.Emit);
111916             // Before emitting lets backup state, so we can revert it back if there are declaration errors to handle emit and declaration errors correctly
111917             program.backupState();
111918             var declDiagnostics;
111919             var reportDeclarationDiagnostics = function (d) { return (declDiagnostics || (declDiagnostics = [])).push(d); };
111920             var outputFiles = [];
111921             var emitResult = ts.emitFilesAndReportErrors(program, reportDeclarationDiagnostics, 
111922             /*writeFileName*/ undefined, 
111923             /*reportSummary*/ undefined, function (name, text, writeByteOrderMark) { return outputFiles.push({ name: name, text: text, writeByteOrderMark: writeByteOrderMark }); }, cancellationToken, 
111924             /*emitOnlyDts*/ false, customTransformers).emitResult;
111925             // Don't emit .d.ts if there are decl file errors
111926             if (declDiagnostics) {
111927                 program.restoreState();
111928                 (_a = buildErrors(state, projectPath, program, config, declDiagnostics, BuildResultFlags.DeclarationEmitErrors, "Declaration file"), buildResult = _a.buildResult, step = _a.step);
111929                 return {
111930                     emitSkipped: true,
111931                     diagnostics: emitResult.diagnostics
111932                 };
111933             }
111934             // Actual Emit
111935             var host = state.host, compilerHost = state.compilerHost;
111936             var resultFlags = BuildResultFlags.DeclarationOutputUnchanged;
111937             var newestDeclarationFileContentChangedTime = minimumDate;
111938             var anyDtsChanged = false;
111939             var emitterDiagnostics = ts.createDiagnosticCollection();
111940             var emittedOutputs = new ts.Map();
111941             outputFiles.forEach(function (_a) {
111942                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
111943                 var priorChangeTime;
111944                 if (!anyDtsChanged && isDeclarationFile(name)) {
111945                     // Check for unchanged .d.ts files
111946                     if (host.fileExists(name) && state.readFileWithCache(name) === text) {
111947                         priorChangeTime = host.getModifiedTime(name);
111948                     }
111949                     else {
111950                         resultFlags &= ~BuildResultFlags.DeclarationOutputUnchanged;
111951                         anyDtsChanged = true;
111952                     }
111953                 }
111954                 emittedOutputs.set(toPath(state, name), name);
111955                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
111956                 if (priorChangeTime !== undefined) {
111957                     newestDeclarationFileContentChangedTime = newer(priorChangeTime, newestDeclarationFileContentChangedTime);
111958                 }
111959             });
111960             finishEmit(emitterDiagnostics, emittedOutputs, newestDeclarationFileContentChangedTime, 
111961             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ anyDtsChanged, outputFiles.length ? outputFiles[0].name : ts.getFirstProjectOutput(config, !host.useCaseSensitiveFileNames()), resultFlags);
111962             return emitResult;
111963         }
111964         function emitBuildInfo(writeFileCallback, cancellationToken) {
111965             ts.Debug.assertIsDefined(program);
111966             ts.Debug.assert(step === BuildStep.EmitBuildInfo);
111967             var emitResult = program.emitBuildInfo(writeFileCallback, cancellationToken);
111968             if (emitResult.diagnostics.length) {
111969                 reportErrors(state, emitResult.diagnostics);
111970                 state.diagnostics.set(projectPath, __spreadArrays(state.diagnostics.get(projectPath), emitResult.diagnostics));
111971                 buildResult = BuildResultFlags.EmitErrors & buildResult;
111972             }
111973             if (emitResult.emittedFiles && state.writeFileName) {
111974                 emitResult.emittedFiles.forEach(function (name) { return listEmittedFile(state, config, name); });
111975             }
111976             afterProgramDone(state, program, config);
111977             step = BuildStep.QueueReferencingProjects;
111978             return emitResult;
111979         }
111980         function finishEmit(emitterDiagnostics, emittedOutputs, priorNewestUpdateTime, newestDeclarationFileContentChangedTimeIsMaximumDate, oldestOutputFileName, resultFlags) {
111981             var _a;
111982             var emitDiagnostics = emitterDiagnostics.getDiagnostics();
111983             if (emitDiagnostics.length) {
111984                 (_a = buildErrors(state, projectPath, program, config, emitDiagnostics, BuildResultFlags.EmitErrors, "Emit"), buildResult = _a.buildResult, step = _a.step);
111985                 return emitDiagnostics;
111986             }
111987             if (state.writeFileName) {
111988                 emittedOutputs.forEach(function (name) { return listEmittedFile(state, config, name); });
111989             }
111990             // Update time stamps for rest of the outputs
111991             var newestDeclarationFileContentChangedTime = updateOutputTimestampsWorker(state, config, priorNewestUpdateTime, ts.Diagnostics.Updating_unchanged_output_timestamps_of_project_0, emittedOutputs);
111992             state.diagnostics.delete(projectPath);
111993             state.projectStatus.set(projectPath, {
111994                 type: ts.UpToDateStatusType.UpToDate,
111995                 newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTimeIsMaximumDate ?
111996                     maximumDate :
111997                     newestDeclarationFileContentChangedTime,
111998                 oldestOutputFileName: oldestOutputFileName
111999             });
112000             afterProgramDone(state, program, config);
112001             step = BuildStep.QueueReferencingProjects;
112002             buildResult = resultFlags;
112003             return emitDiagnostics;
112004         }
112005         function emitBundle(writeFileCallback, customTransformers) {
112006             ts.Debug.assert(kind === InvalidatedProjectKind.UpdateBundle);
112007             if (state.options.dry) {
112008                 reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_output_of_project_0, project);
112009                 buildResult = BuildResultFlags.Success;
112010                 step = BuildStep.QueueReferencingProjects;
112011                 return undefined;
112012             }
112013             if (state.options.verbose)
112014                 reportStatus(state, ts.Diagnostics.Updating_output_of_project_0, project);
112015             // Update js, and source map
112016             var compilerHost = state.compilerHost;
112017             state.projectCompilerOptions = config.options;
112018             var outputFiles = ts.emitUsingBuildInfo(config, compilerHost, function (ref) {
112019                 var refName = resolveProjectName(state, ref.path);
112020                 return parseConfigFile(state, refName, toResolvedConfigFilePath(state, refName));
112021             }, customTransformers);
112022             if (ts.isString(outputFiles)) {
112023                 reportStatus(state, ts.Diagnostics.Cannot_update_output_of_project_0_because_there_was_error_reading_file_1, project, relName(state, outputFiles));
112024                 step = BuildStep.BuildInvalidatedProjectOfBundle;
112025                 return invalidatedProjectOfBundle = createBuildOrUpdateInvalidedProject(InvalidatedProjectKind.Build, state, project, projectPath, projectIndex, config, buildOrder);
112026             }
112027             // Actual Emit
112028             ts.Debug.assert(!!outputFiles.length);
112029             var emitterDiagnostics = ts.createDiagnosticCollection();
112030             var emittedOutputs = new ts.Map();
112031             outputFiles.forEach(function (_a) {
112032                 var name = _a.name, text = _a.text, writeByteOrderMark = _a.writeByteOrderMark;
112033                 emittedOutputs.set(toPath(state, name), name);
112034                 ts.writeFile(writeFileCallback ? { writeFile: writeFileCallback } : compilerHost, emitterDiagnostics, name, text, writeByteOrderMark);
112035             });
112036             var emitDiagnostics = finishEmit(emitterDiagnostics, emittedOutputs, minimumDate, 
112037             /*newestDeclarationFileContentChangedTimeIsMaximumDate*/ false, outputFiles[0].name, BuildResultFlags.DeclarationOutputUnchanged);
112038             return { emitSkipped: false, diagnostics: emitDiagnostics };
112039         }
112040         function executeSteps(till, cancellationToken, writeFile, customTransformers) {
112041             while (step <= till && step < BuildStep.Done) {
112042                 var currentStep = step;
112043                 switch (step) {
112044                     case BuildStep.CreateProgram:
112045                         createProgram();
112046                         break;
112047                     case BuildStep.SyntaxDiagnostics:
112048                         getSyntaxDiagnostics(cancellationToken);
112049                         break;
112050                     case BuildStep.SemanticDiagnostics:
112051                         getSemanticDiagnostics(cancellationToken);
112052                         break;
112053                     case BuildStep.Emit:
112054                         emit(writeFile, cancellationToken, customTransformers);
112055                         break;
112056                     case BuildStep.EmitBuildInfo:
112057                         emitBuildInfo(writeFile, cancellationToken);
112058                         break;
112059                     case BuildStep.EmitBundle:
112060                         emitBundle(writeFile, customTransformers);
112061                         break;
112062                     case BuildStep.BuildInvalidatedProjectOfBundle:
112063                         ts.Debug.checkDefined(invalidatedProjectOfBundle).done(cancellationToken);
112064                         step = BuildStep.Done;
112065                         break;
112066                     case BuildStep.QueueReferencingProjects:
112067                         queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, ts.Debug.checkDefined(buildResult));
112068                         step++;
112069                         break;
112070                     // Should never be done
112071                     case BuildStep.Done:
112072                     default:
112073                         ts.assertType(step);
112074                 }
112075                 ts.Debug.assert(step > currentStep);
112076             }
112077         }
112078     }
112079     function needsBuild(_a, status, config) {
112080         var options = _a.options;
112081         if (status.type !== ts.UpToDateStatusType.OutOfDateWithPrepend || options.force)
112082             return true;
112083         return config.fileNames.length === 0 ||
112084             !!ts.getConfigFileParsingDiagnostics(config).length ||
112085             !ts.isIncrementalCompilation(config.options);
112086     }
112087     function getNextInvalidatedProject(state, buildOrder, reportQueue) {
112088         if (!state.projectPendingBuild.size)
112089             return undefined;
112090         if (isCircularBuildOrder(buildOrder))
112091             return undefined;
112092         if (state.currentInvalidatedProject) {
112093             // Only if same buildOrder the currentInvalidated project can be sent again
112094             return ts.arrayIsEqualTo(state.currentInvalidatedProject.buildOrder, buildOrder) ?
112095                 state.currentInvalidatedProject :
112096                 undefined;
112097         }
112098         var options = state.options, projectPendingBuild = state.projectPendingBuild;
112099         for (var projectIndex = 0; projectIndex < buildOrder.length; projectIndex++) {
112100             var project = buildOrder[projectIndex];
112101             var projectPath = toResolvedConfigFilePath(state, project);
112102             var reloadLevel = state.projectPendingBuild.get(projectPath);
112103             if (reloadLevel === undefined)
112104                 continue;
112105             if (reportQueue) {
112106                 reportQueue = false;
112107                 reportBuildQueue(state, buildOrder);
112108             }
112109             var config = parseConfigFile(state, project, projectPath);
112110             if (!config) {
112111                 reportParseConfigFileDiagnostic(state, projectPath);
112112                 projectPendingBuild.delete(projectPath);
112113                 continue;
112114             }
112115             if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
112116                 watchConfigFile(state, project, projectPath, config);
112117                 watchWildCardDirectories(state, project, projectPath, config);
112118                 watchInputFiles(state, project, projectPath, config);
112119             }
112120             else if (reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
112121                 // Update file names
112122                 var result = ts.getFileNamesFromConfigSpecs(config.configFileSpecs, ts.getDirectoryPath(project), config.options, state.parseConfigFileHost);
112123                 ts.updateErrorForNoInputFiles(result, project, config.configFileSpecs, config.errors, ts.canJsonReportNoInputFiles(config.raw));
112124                 config.fileNames = result.fileNames;
112125                 watchInputFiles(state, project, projectPath, config);
112126             }
112127             var status = getUpToDateStatus(state, config, projectPath);
112128             verboseReportProjectStatus(state, project, status);
112129             if (!options.force) {
112130                 if (status.type === ts.UpToDateStatusType.UpToDate) {
112131                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
112132                     projectPendingBuild.delete(projectPath);
112133                     // Up to date, skip
112134                     if (options.dry) {
112135                         // In a dry build, inform the user of this fact
112136                         reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date, project);
112137                     }
112138                     continue;
112139                 }
112140                 if (status.type === ts.UpToDateStatusType.UpToDateWithUpstreamTypes) {
112141                     reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
112142                     return createUpdateOutputFileStampsProject(state, project, projectPath, config, buildOrder);
112143                 }
112144             }
112145             if (status.type === ts.UpToDateStatusType.UpstreamBlocked) {
112146                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
112147                 projectPendingBuild.delete(projectPath);
112148                 if (options.verbose) {
112149                     reportStatus(state, status.upstreamProjectBlocked ?
112150                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_was_not_built :
112151                         ts.Diagnostics.Skipping_build_of_project_0_because_its_dependency_1_has_errors, project, status.upstreamProjectName);
112152                 }
112153                 continue;
112154             }
112155             if (status.type === ts.UpToDateStatusType.ContainerOnly) {
112156                 reportAndStoreErrors(state, projectPath, ts.getConfigFileParsingDiagnostics(config));
112157                 projectPendingBuild.delete(projectPath);
112158                 // Do nothing
112159                 continue;
112160             }
112161             return createBuildOrUpdateInvalidedProject(needsBuild(state, status, config) ?
112162                 InvalidatedProjectKind.Build :
112163                 InvalidatedProjectKind.UpdateBundle, state, project, projectPath, projectIndex, config, buildOrder);
112164         }
112165         return undefined;
112166     }
112167     function listEmittedFile(_a, proj, file) {
112168         var writeFileName = _a.writeFileName;
112169         if (writeFileName && proj.options.listEmittedFiles) {
112170             writeFileName("TSFILE: " + file);
112171         }
112172     }
112173     function getOldProgram(_a, proj, parsed) {
112174         var options = _a.options, builderPrograms = _a.builderPrograms, compilerHost = _a.compilerHost;
112175         if (options.force)
112176             return undefined;
112177         var value = builderPrograms.get(proj);
112178         if (value)
112179             return value;
112180         return ts.readBuilderProgram(parsed.options, compilerHost);
112181     }
112182     function afterProgramDone(state, program, config) {
112183         if (program) {
112184             if (program && state.writeFileName)
112185                 ts.listFiles(program, state.writeFileName);
112186             if (state.host.afterProgramEmitAndDiagnostics) {
112187                 state.host.afterProgramEmitAndDiagnostics(program);
112188             }
112189             program.releaseProgram();
112190         }
112191         else if (state.host.afterEmitBundle) {
112192             state.host.afterEmitBundle(config);
112193         }
112194         state.projectCompilerOptions = state.baseCompilerOptions;
112195     }
112196     function buildErrors(state, resolvedPath, program, config, diagnostics, buildResult, errorType) {
112197         var canEmitBuildInfo = !(buildResult & BuildResultFlags.SyntaxErrors) && program && !ts.outFile(program.getCompilerOptions());
112198         reportAndStoreErrors(state, resolvedPath, diagnostics);
112199         // List files if any other build error using program (emit errors already report files)
112200         state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.Unbuildable, reason: errorType + " errors" });
112201         if (canEmitBuildInfo)
112202             return { buildResult: buildResult, step: BuildStep.EmitBuildInfo };
112203         afterProgramDone(state, program, config);
112204         return { buildResult: buildResult, step: BuildStep.QueueReferencingProjects };
112205     }
112206     function updateModuleResolutionCache(state, proj, config) {
112207         if (!state.moduleResolutionCache)
112208             return;
112209         // Update module resolution cache if needed
112210         var moduleResolutionCache = state.moduleResolutionCache;
112211         var projPath = toPath(state, proj);
112212         if (moduleResolutionCache.directoryToModuleNameMap.redirectsMap.size === 0) {
112213             // The own map will be for projectCompilerOptions
112214             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size === 0);
112215             moduleResolutionCache.directoryToModuleNameMap.redirectsMap.set(projPath, moduleResolutionCache.directoryToModuleNameMap.ownMap);
112216             moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.set(projPath, moduleResolutionCache.moduleNameToDirectoryMap.ownMap);
112217         }
112218         else {
112219             // Set correct own map
112220             ts.Debug.assert(moduleResolutionCache.moduleNameToDirectoryMap.redirectsMap.size > 0);
112221             var ref = {
112222                 sourceFile: config.options.configFile,
112223                 commandLine: config
112224             };
112225             moduleResolutionCache.directoryToModuleNameMap.setOwnMap(moduleResolutionCache.directoryToModuleNameMap.getOrCreateMapOfCacheRedirects(ref));
112226             moduleResolutionCache.moduleNameToDirectoryMap.setOwnMap(moduleResolutionCache.moduleNameToDirectoryMap.getOrCreateMapOfCacheRedirects(ref));
112227         }
112228         moduleResolutionCache.directoryToModuleNameMap.setOwnOptions(config.options);
112229         moduleResolutionCache.moduleNameToDirectoryMap.setOwnOptions(config.options);
112230     }
112231     function checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName) {
112232         // Check tsconfig time
112233         var tsconfigTime = state.host.getModifiedTime(configFile) || ts.missingFileModifiedTime;
112234         if (oldestOutputFileTime < tsconfigTime) {
112235             return {
112236                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
112237                 outOfDateOutputFileName: oldestOutputFileName,
112238                 newerInputFileName: configFile
112239             };
112240         }
112241     }
112242     function getUpToDateStatusWorker(state, project, resolvedPath) {
112243         var newestInputFileName = undefined;
112244         var newestInputFileTime = minimumDate;
112245         var host = state.host;
112246         // Get timestamps of input files
112247         for (var _i = 0, _a = project.fileNames; _i < _a.length; _i++) {
112248             var inputFile = _a[_i];
112249             if (!host.fileExists(inputFile)) {
112250                 return {
112251                     type: ts.UpToDateStatusType.Unbuildable,
112252                     reason: inputFile + " does not exist"
112253                 };
112254             }
112255             var inputTime = host.getModifiedTime(inputFile) || ts.missingFileModifiedTime;
112256             if (inputTime > newestInputFileTime) {
112257                 newestInputFileName = inputFile;
112258                 newestInputFileTime = inputTime;
112259             }
112260         }
112261         // Container if no files are specified in the project
112262         if (!project.fileNames.length && !ts.canJsonReportNoInputFiles(project.raw)) {
112263             return {
112264                 type: ts.UpToDateStatusType.ContainerOnly
112265             };
112266         }
112267         // Collect the expected outputs of this project
112268         var outputs = ts.getAllProjectOutputs(project, !host.useCaseSensitiveFileNames());
112269         // Now see if all outputs are newer than the newest input
112270         var oldestOutputFileName = "(none)";
112271         var oldestOutputFileTime = maximumDate;
112272         var newestOutputFileName = "(none)";
112273         var newestOutputFileTime = minimumDate;
112274         var missingOutputFileName;
112275         var newestDeclarationFileContentChangedTime = minimumDate;
112276         var isOutOfDateWithInputs = false;
112277         for (var _b = 0, outputs_1 = outputs; _b < outputs_1.length; _b++) {
112278             var output = outputs_1[_b];
112279             // Output is missing; can stop checking
112280             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
112281             if (!host.fileExists(output)) {
112282                 missingOutputFileName = output;
112283                 break;
112284             }
112285             var outputTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
112286             if (outputTime < oldestOutputFileTime) {
112287                 oldestOutputFileTime = outputTime;
112288                 oldestOutputFileName = output;
112289             }
112290             // If an output is older than the newest input, we can stop checking
112291             // Don't immediately return because we can still be upstream-blocked, which is a higher-priority status
112292             if (outputTime < newestInputFileTime) {
112293                 isOutOfDateWithInputs = true;
112294                 break;
112295             }
112296             if (outputTime > newestOutputFileTime) {
112297                 newestOutputFileTime = outputTime;
112298                 newestOutputFileName = output;
112299             }
112300             // Keep track of when the most recent time a .d.ts file was changed.
112301             // In addition to file timestamps, we also keep track of when a .d.ts file
112302             // had its file touched but not had its contents changed - this allows us
112303             // to skip a downstream typecheck
112304             if (isDeclarationFile(output)) {
112305                 var outputModifiedTime = host.getModifiedTime(output) || ts.missingFileModifiedTime;
112306                 newestDeclarationFileContentChangedTime = newer(newestDeclarationFileContentChangedTime, outputModifiedTime);
112307             }
112308         }
112309         var pseudoUpToDate = false;
112310         var usesPrepend = false;
112311         var upstreamChangedProject;
112312         if (project.projectReferences) {
112313             state.projectStatus.set(resolvedPath, { type: ts.UpToDateStatusType.ComputingUpstream });
112314             for (var _c = 0, _d = project.projectReferences; _c < _d.length; _c++) {
112315                 var ref = _d[_c];
112316                 usesPrepend = usesPrepend || !!(ref.prepend);
112317                 var resolvedRef = ts.resolveProjectReferencePath(ref);
112318                 var resolvedRefPath = toResolvedConfigFilePath(state, resolvedRef);
112319                 var refStatus = getUpToDateStatus(state, parseConfigFile(state, resolvedRef, resolvedRefPath), resolvedRefPath);
112320                 // Its a circular reference ignore the status of this project
112321                 if (refStatus.type === ts.UpToDateStatusType.ComputingUpstream ||
112322                     refStatus.type === ts.UpToDateStatusType.ContainerOnly) { // Container only ignore this project
112323                     continue;
112324                 }
112325                 // An upstream project is blocked
112326                 if (refStatus.type === ts.UpToDateStatusType.Unbuildable ||
112327                     refStatus.type === ts.UpToDateStatusType.UpstreamBlocked) {
112328                     return {
112329                         type: ts.UpToDateStatusType.UpstreamBlocked,
112330                         upstreamProjectName: ref.path,
112331                         upstreamProjectBlocked: refStatus.type === ts.UpToDateStatusType.UpstreamBlocked
112332                     };
112333                 }
112334                 // If the upstream project is out of date, then so are we (someone shouldn't have asked, though?)
112335                 if (refStatus.type !== ts.UpToDateStatusType.UpToDate) {
112336                     return {
112337                         type: ts.UpToDateStatusType.UpstreamOutOfDate,
112338                         upstreamProjectName: ref.path
112339                     };
112340                 }
112341                 // Check oldest output file name only if there is no missing output file name
112342                 if (!missingOutputFileName) {
112343                     // If the upstream project's newest file is older than our oldest output, we
112344                     // can't be out of date because of it
112345                     if (refStatus.newestInputFileTime && refStatus.newestInputFileTime <= oldestOutputFileTime) {
112346                         continue;
112347                     }
112348                     // If the upstream project has only change .d.ts files, and we've built
112349                     // *after* those files, then we're "psuedo up to date" and eligible for a fast rebuild
112350                     if (refStatus.newestDeclarationFileContentChangedTime && refStatus.newestDeclarationFileContentChangedTime <= oldestOutputFileTime) {
112351                         pseudoUpToDate = true;
112352                         upstreamChangedProject = ref.path;
112353                         continue;
112354                     }
112355                     // We have an output older than an upstream output - we are out of date
112356                     ts.Debug.assert(oldestOutputFileName !== undefined, "Should have an oldest output filename here");
112357                     return {
112358                         type: ts.UpToDateStatusType.OutOfDateWithUpstream,
112359                         outOfDateOutputFileName: oldestOutputFileName,
112360                         newerProjectName: ref.path
112361                     };
112362                 }
112363             }
112364         }
112365         if (missingOutputFileName !== undefined) {
112366             return {
112367                 type: ts.UpToDateStatusType.OutputMissing,
112368                 missingOutputFileName: missingOutputFileName
112369             };
112370         }
112371         if (isOutOfDateWithInputs) {
112372             return {
112373                 type: ts.UpToDateStatusType.OutOfDateWithSelf,
112374                 outOfDateOutputFileName: oldestOutputFileName,
112375                 newerInputFileName: newestInputFileName
112376             };
112377         }
112378         else {
112379             // Check tsconfig time
112380             var configStatus = checkConfigFileUpToDateStatus(state, project.options.configFilePath, oldestOutputFileTime, oldestOutputFileName);
112381             if (configStatus)
112382                 return configStatus;
112383             // Check extended config time
112384             var extendedConfigStatus = ts.forEach(project.options.configFile.extendedSourceFiles || ts.emptyArray, function (configFile) { return checkConfigFileUpToDateStatus(state, configFile, oldestOutputFileTime, oldestOutputFileName); });
112385             if (extendedConfigStatus)
112386                 return extendedConfigStatus;
112387         }
112388         if (!state.buildInfoChecked.has(resolvedPath)) {
112389             state.buildInfoChecked.set(resolvedPath, true);
112390             var buildInfoPath = ts.getTsBuildInfoEmitOutputFilePath(project.options);
112391             if (buildInfoPath) {
112392                 var value = state.readFileWithCache(buildInfoPath);
112393                 var buildInfo = value && ts.getBuildInfo(value);
112394                 if (buildInfo && (buildInfo.bundle || buildInfo.program) && buildInfo.version !== ts.version) {
112395                     return {
112396                         type: ts.UpToDateStatusType.TsVersionOutputOfDate,
112397                         version: buildInfo.version
112398                     };
112399                 }
112400             }
112401         }
112402         if (usesPrepend && pseudoUpToDate) {
112403             return {
112404                 type: ts.UpToDateStatusType.OutOfDateWithPrepend,
112405                 outOfDateOutputFileName: oldestOutputFileName,
112406                 newerProjectName: upstreamChangedProject
112407             };
112408         }
112409         // Up to date
112410         return {
112411             type: pseudoUpToDate ? ts.UpToDateStatusType.UpToDateWithUpstreamTypes : ts.UpToDateStatusType.UpToDate,
112412             newestDeclarationFileContentChangedTime: newestDeclarationFileContentChangedTime,
112413             newestInputFileTime: newestInputFileTime,
112414             newestOutputFileTime: newestOutputFileTime,
112415             newestInputFileName: newestInputFileName,
112416             newestOutputFileName: newestOutputFileName,
112417             oldestOutputFileName: oldestOutputFileName
112418         };
112419     }
112420     function getUpToDateStatus(state, project, resolvedPath) {
112421         if (project === undefined) {
112422             return { type: ts.UpToDateStatusType.Unbuildable, reason: "File deleted mid-build" };
112423         }
112424         var prior = state.projectStatus.get(resolvedPath);
112425         if (prior !== undefined) {
112426             return prior;
112427         }
112428         var actual = getUpToDateStatusWorker(state, project, resolvedPath);
112429         state.projectStatus.set(resolvedPath, actual);
112430         return actual;
112431     }
112432     function updateOutputTimestampsWorker(state, proj, priorNewestUpdateTime, verboseMessage, skipOutputs) {
112433         var host = state.host;
112434         var outputs = ts.getAllProjectOutputs(proj, !host.useCaseSensitiveFileNames());
112435         if (!skipOutputs || outputs.length !== skipOutputs.size) {
112436             var reportVerbose = !!state.options.verbose;
112437             var now = host.now ? host.now() : new Date();
112438             for (var _i = 0, outputs_2 = outputs; _i < outputs_2.length; _i++) {
112439                 var file = outputs_2[_i];
112440                 if (skipOutputs && skipOutputs.has(toPath(state, file))) {
112441                     continue;
112442                 }
112443                 if (reportVerbose) {
112444                     reportVerbose = false;
112445                     reportStatus(state, verboseMessage, proj.options.configFilePath);
112446                 }
112447                 if (isDeclarationFile(file)) {
112448                     priorNewestUpdateTime = newer(priorNewestUpdateTime, host.getModifiedTime(file) || ts.missingFileModifiedTime);
112449                 }
112450                 host.setModifiedTime(file, now);
112451             }
112452         }
112453         return priorNewestUpdateTime;
112454     }
112455     function updateOutputTimestamps(state, proj, resolvedPath) {
112456         if (state.options.dry) {
112457             return reportStatus(state, ts.Diagnostics.A_non_dry_build_would_update_timestamps_for_output_of_project_0, proj.options.configFilePath);
112458         }
112459         var priorNewestUpdateTime = updateOutputTimestampsWorker(state, proj, minimumDate, ts.Diagnostics.Updating_output_timestamps_of_project_0);
112460         state.projectStatus.set(resolvedPath, {
112461             type: ts.UpToDateStatusType.UpToDate,
112462             newestDeclarationFileContentChangedTime: priorNewestUpdateTime,
112463             oldestOutputFileName: ts.getFirstProjectOutput(proj, !state.host.useCaseSensitiveFileNames())
112464         });
112465     }
112466     function queueReferencingProjects(state, project, projectPath, projectIndex, config, buildOrder, buildResult) {
112467         // Queue only if there are no errors
112468         if (buildResult & BuildResultFlags.AnyErrors)
112469             return;
112470         // Only composite projects can be referenced by other projects
112471         if (!config.options.composite)
112472             return;
112473         // Always use build order to queue projects
112474         for (var index = projectIndex + 1; index < buildOrder.length; index++) {
112475             var nextProject = buildOrder[index];
112476             var nextProjectPath = toResolvedConfigFilePath(state, nextProject);
112477             if (state.projectPendingBuild.has(nextProjectPath))
112478                 continue;
112479             var nextProjectConfig = parseConfigFile(state, nextProject, nextProjectPath);
112480             if (!nextProjectConfig || !nextProjectConfig.projectReferences)
112481                 continue;
112482             for (var _i = 0, _a = nextProjectConfig.projectReferences; _i < _a.length; _i++) {
112483                 var ref = _a[_i];
112484                 var resolvedRefPath = resolveProjectName(state, ref.path);
112485                 if (toResolvedConfigFilePath(state, resolvedRefPath) !== projectPath)
112486                     continue;
112487                 // If the project is referenced with prepend, always build downstream projects,
112488                 // If declaration output is changed, build the project
112489                 // otherwise mark the project UpToDateWithUpstreamTypes so it updates output time stamps
112490                 var status = state.projectStatus.get(nextProjectPath);
112491                 if (status) {
112492                     switch (status.type) {
112493                         case ts.UpToDateStatusType.UpToDate:
112494                             if (buildResult & BuildResultFlags.DeclarationOutputUnchanged) {
112495                                 if (ref.prepend) {
112496                                     state.projectStatus.set(nextProjectPath, {
112497                                         type: ts.UpToDateStatusType.OutOfDateWithPrepend,
112498                                         outOfDateOutputFileName: status.oldestOutputFileName,
112499                                         newerProjectName: project
112500                                     });
112501                                 }
112502                                 else {
112503                                     status.type = ts.UpToDateStatusType.UpToDateWithUpstreamTypes;
112504                                 }
112505                                 break;
112506                             }
112507                         // falls through
112508                         case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
112509                         case ts.UpToDateStatusType.OutOfDateWithPrepend:
112510                             if (!(buildResult & BuildResultFlags.DeclarationOutputUnchanged)) {
112511                                 state.projectStatus.set(nextProjectPath, {
112512                                     type: ts.UpToDateStatusType.OutOfDateWithUpstream,
112513                                     outOfDateOutputFileName: status.type === ts.UpToDateStatusType.OutOfDateWithPrepend ? status.outOfDateOutputFileName : status.oldestOutputFileName,
112514                                     newerProjectName: project
112515                                 });
112516                             }
112517                             break;
112518                         case ts.UpToDateStatusType.UpstreamBlocked:
112519                             if (toResolvedConfigFilePath(state, resolveProjectName(state, status.upstreamProjectName)) === projectPath) {
112520                                 clearProjectStatus(state, nextProjectPath);
112521                             }
112522                             break;
112523                     }
112524                 }
112525                 addProjToQueue(state, nextProjectPath, ts.ConfigFileProgramReloadLevel.None);
112526                 break;
112527             }
112528         }
112529     }
112530     function build(state, project, cancellationToken, onlyReferences) {
112531         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
112532         if (!buildOrder)
112533             return ts.ExitStatus.InvalidProject_OutputsSkipped;
112534         setupInitialBuild(state, cancellationToken);
112535         var reportQueue = true;
112536         var successfulProjects = 0;
112537         while (true) {
112538             var invalidatedProject = getNextInvalidatedProject(state, buildOrder, reportQueue);
112539             if (!invalidatedProject)
112540                 break;
112541             reportQueue = false;
112542             invalidatedProject.done(cancellationToken);
112543             if (!state.diagnostics.has(invalidatedProject.projectPath))
112544                 successfulProjects++;
112545         }
112546         disableCache(state);
112547         reportErrorSummary(state, buildOrder);
112548         startWatching(state, buildOrder);
112549         return isCircularBuildOrder(buildOrder)
112550             ? ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped
112551             : !buildOrder.some(function (p) { return state.diagnostics.has(toResolvedConfigFilePath(state, p)); })
112552                 ? ts.ExitStatus.Success
112553                 : successfulProjects
112554                     ? ts.ExitStatus.DiagnosticsPresent_OutputsGenerated
112555                     : ts.ExitStatus.DiagnosticsPresent_OutputsSkipped;
112556     }
112557     function clean(state, project, onlyReferences) {
112558         var buildOrder = getBuildOrderFor(state, project, onlyReferences);
112559         if (!buildOrder)
112560             return ts.ExitStatus.InvalidProject_OutputsSkipped;
112561         if (isCircularBuildOrder(buildOrder)) {
112562             reportErrors(state, buildOrder.circularDiagnostics);
112563             return ts.ExitStatus.ProjectReferenceCycle_OutputsSkipped;
112564         }
112565         var options = state.options, host = state.host;
112566         var filesToDelete = options.dry ? [] : undefined;
112567         for (var _i = 0, buildOrder_1 = buildOrder; _i < buildOrder_1.length; _i++) {
112568             var proj = buildOrder_1[_i];
112569             var resolvedPath = toResolvedConfigFilePath(state, proj);
112570             var parsed = parseConfigFile(state, proj, resolvedPath);
112571             if (parsed === undefined) {
112572                 // File has gone missing; fine to ignore here
112573                 reportParseConfigFileDiagnostic(state, resolvedPath);
112574                 continue;
112575             }
112576             var outputs = ts.getAllProjectOutputs(parsed, !host.useCaseSensitiveFileNames());
112577             for (var _a = 0, outputs_3 = outputs; _a < outputs_3.length; _a++) {
112578                 var output = outputs_3[_a];
112579                 if (host.fileExists(output)) {
112580                     if (filesToDelete) {
112581                         filesToDelete.push(output);
112582                     }
112583                     else {
112584                         host.deleteFile(output);
112585                         invalidateProject(state, resolvedPath, ts.ConfigFileProgramReloadLevel.None);
112586                     }
112587                 }
112588             }
112589         }
112590         if (filesToDelete) {
112591             reportStatus(state, ts.Diagnostics.A_non_dry_build_would_delete_the_following_files_Colon_0, filesToDelete.map(function (f) { return "\r\n * " + f; }).join(""));
112592         }
112593         return ts.ExitStatus.Success;
112594     }
112595     function invalidateProject(state, resolved, reloadLevel) {
112596         // If host implements getParsedCommandLine, we cant get list of files from parseConfigFileHost
112597         if (state.host.getParsedCommandLine && reloadLevel === ts.ConfigFileProgramReloadLevel.Partial) {
112598             reloadLevel = ts.ConfigFileProgramReloadLevel.Full;
112599         }
112600         if (reloadLevel === ts.ConfigFileProgramReloadLevel.Full) {
112601             state.configFileCache.delete(resolved);
112602             state.buildOrder = undefined;
112603         }
112604         state.needsSummary = true;
112605         clearProjectStatus(state, resolved);
112606         addProjToQueue(state, resolved, reloadLevel);
112607         enableCache(state);
112608     }
112609     function invalidateProjectAndScheduleBuilds(state, resolvedPath, reloadLevel) {
112610         state.reportFileChangeDetected = true;
112611         invalidateProject(state, resolvedPath, reloadLevel);
112612         scheduleBuildInvalidatedProject(state);
112613     }
112614     function scheduleBuildInvalidatedProject(state) {
112615         var hostWithWatch = state.hostWithWatch;
112616         if (!hostWithWatch.setTimeout || !hostWithWatch.clearTimeout) {
112617             return;
112618         }
112619         if (state.timerToBuildInvalidatedProject) {
112620             hostWithWatch.clearTimeout(state.timerToBuildInvalidatedProject);
112621         }
112622         state.timerToBuildInvalidatedProject = hostWithWatch.setTimeout(buildNextInvalidatedProject, 250, state);
112623     }
112624     function buildNextInvalidatedProject(state) {
112625         state.timerToBuildInvalidatedProject = undefined;
112626         if (state.reportFileChangeDetected) {
112627             state.reportFileChangeDetected = false;
112628             state.projectErrorsReported.clear();
112629             reportWatchStatus(state, ts.Diagnostics.File_change_detected_Starting_incremental_compilation);
112630         }
112631         var buildOrder = getBuildOrder(state);
112632         var invalidatedProject = getNextInvalidatedProject(state, buildOrder, /*reportQueue*/ false);
112633         if (invalidatedProject) {
112634             invalidatedProject.done();
112635             if (state.projectPendingBuild.size) {
112636                 // Schedule next project for build
112637                 if (state.watch && !state.timerToBuildInvalidatedProject) {
112638                     scheduleBuildInvalidatedProject(state);
112639                 }
112640                 return;
112641             }
112642         }
112643         disableCache(state);
112644         reportErrorSummary(state, buildOrder);
112645     }
112646     function watchConfigFile(state, resolved, resolvedPath, parsed) {
112647         if (!state.watch || state.allWatchedConfigFiles.has(resolvedPath))
112648             return;
112649         state.allWatchedConfigFiles.set(resolvedPath, state.watchFile(state.hostWithWatch, resolved, function () {
112650             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Full);
112651         }, ts.PollingInterval.High, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.ConfigFile, resolved));
112652     }
112653     function watchWildCardDirectories(state, resolved, resolvedPath, parsed) {
112654         if (!state.watch)
112655             return;
112656         ts.updateWatchingWildcardDirectories(getOrCreateValueMapFromConfigFileMap(state.allWatchedWildcardDirectories, resolvedPath), new ts.Map(ts.getEntries(parsed.configFileSpecs.wildcardDirectories)), function (dir, flags) { return state.watchDirectory(state.hostWithWatch, dir, function (fileOrDirectory) {
112657             if (ts.isIgnoredFileFromWildCardWatching({
112658                 watchedDirPath: toPath(state, dir),
112659                 fileOrDirectory: fileOrDirectory,
112660                 fileOrDirectoryPath: toPath(state, fileOrDirectory),
112661                 configFileName: resolved,
112662                 configFileSpecs: parsed.configFileSpecs,
112663                 currentDirectory: state.currentDirectory,
112664                 options: parsed.options,
112665                 program: state.builderPrograms.get(resolvedPath),
112666                 useCaseSensitiveFileNames: state.parseConfigFileHost.useCaseSensitiveFileNames,
112667                 writeLog: function (s) { return state.writeLog(s); }
112668             }))
112669                 return;
112670             invalidateProjectAndScheduleBuilds(state, resolvedPath, ts.ConfigFileProgramReloadLevel.Partial);
112671         }, flags, parsed === null || parsed === void 0 ? void 0 : parsed.watchOptions, ts.WatchType.WildcardDirectory, resolved); });
112672     }
112673     function watchInputFiles(state, resolved, resolvedPath, parsed) {
112674         if (!state.watch)
112675             return;
112676         ts.mutateMap(getOrCreateValueMapFromConfigFileMap(state.allWatchedInputFiles, resolvedPath), ts.arrayToMap(parsed.fileNames, function (fileName) { return toPath(state, fileName); }), {
112677             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); },
112678             onDeleteValue: ts.closeFileWatcher,
112679         });
112680     }
112681     function startWatching(state, buildOrder) {
112682         if (!state.watchAllProjectsPending)
112683             return;
112684         state.watchAllProjectsPending = false;
112685         for (var _i = 0, _a = getBuildOrderFromAnyBuildOrder(buildOrder); _i < _a.length; _i++) {
112686             var resolved = _a[_i];
112687             var resolvedPath = toResolvedConfigFilePath(state, resolved);
112688             var cfg = parseConfigFile(state, resolved, resolvedPath);
112689             // Watch this file
112690             watchConfigFile(state, resolved, resolvedPath, cfg);
112691             if (cfg) {
112692                 // Update watchers for wildcard directories
112693                 watchWildCardDirectories(state, resolved, resolvedPath, cfg);
112694                 // Watch input files
112695                 watchInputFiles(state, resolved, resolvedPath, cfg);
112696             }
112697         }
112698     }
112699     function stopWatching(state) {
112700         ts.clearMap(state.allWatchedConfigFiles, ts.closeFileWatcher);
112701         ts.clearMap(state.allWatchedWildcardDirectories, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcherOf); });
112702         ts.clearMap(state.allWatchedInputFiles, function (watchedWildcardDirectories) { return ts.clearMap(watchedWildcardDirectories, ts.closeFileWatcher); });
112703     }
112704     function createSolutionBuilderWorker(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions) {
112705         var state = createSolutionBuilderState(watch, hostOrHostWithWatch, rootNames, options, baseWatchOptions);
112706         return {
112707             build: function (project, cancellationToken) { return build(state, project, cancellationToken); },
112708             clean: function (project) { return clean(state, project); },
112709             buildReferences: function (project, cancellationToken) { return build(state, project, cancellationToken, /*onlyReferences*/ true); },
112710             cleanReferences: function (project) { return clean(state, project, /*onlyReferences*/ true); },
112711             getNextInvalidatedProject: function (cancellationToken) {
112712                 setupInitialBuild(state, cancellationToken);
112713                 return getNextInvalidatedProject(state, getBuildOrder(state), /*reportQueue*/ false);
112714             },
112715             getBuildOrder: function () { return getBuildOrder(state); },
112716             getUpToDateStatusOfProject: function (project) {
112717                 var configFileName = resolveProjectName(state, project);
112718                 var configFilePath = toResolvedConfigFilePath(state, configFileName);
112719                 return getUpToDateStatus(state, parseConfigFile(state, configFileName, configFilePath), configFilePath);
112720             },
112721             invalidateProject: function (configFilePath, reloadLevel) { return invalidateProject(state, configFilePath, reloadLevel || ts.ConfigFileProgramReloadLevel.None); },
112722             buildNextInvalidatedProject: function () { return buildNextInvalidatedProject(state); },
112723             getAllParsedConfigs: function () { return ts.arrayFrom(ts.mapDefinedIterator(state.configFileCache.values(), function (config) { return isParsedCommandLine(config) ? config : undefined; })); },
112724             close: function () { return stopWatching(state); },
112725         };
112726     }
112727     function relName(state, path) {
112728         return ts.convertToRelativePath(path, state.currentDirectory, function (f) { return state.getCanonicalFileName(f); });
112729     }
112730     function reportStatus(state, message) {
112731         var args = [];
112732         for (var _i = 2; _i < arguments.length; _i++) {
112733             args[_i - 2] = arguments[_i];
112734         }
112735         state.host.reportSolutionBuilderStatus(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)));
112736     }
112737     function reportWatchStatus(state, message) {
112738         var args = [];
112739         for (var _i = 2; _i < arguments.length; _i++) {
112740             args[_i - 2] = arguments[_i];
112741         }
112742         if (state.hostWithWatch.onWatchStatusChange) {
112743             state.hostWithWatch.onWatchStatusChange(ts.createCompilerDiagnostic.apply(void 0, __spreadArrays([message], args)), state.host.getNewLine(), state.baseCompilerOptions);
112744         }
112745     }
112746     function reportErrors(_a, errors) {
112747         var host = _a.host;
112748         errors.forEach(function (err) { return host.reportDiagnostic(err); });
112749     }
112750     function reportAndStoreErrors(state, proj, errors) {
112751         reportErrors(state, errors);
112752         state.projectErrorsReported.set(proj, true);
112753         if (errors.length) {
112754             state.diagnostics.set(proj, errors);
112755         }
112756     }
112757     function reportParseConfigFileDiagnostic(state, proj) {
112758         reportAndStoreErrors(state, proj, [state.configFileCache.get(proj)]);
112759     }
112760     function reportErrorSummary(state, buildOrder) {
112761         if (!state.needsSummary)
112762             return;
112763         state.needsSummary = false;
112764         var canReportSummary = state.watch || !!state.host.reportErrorSummary;
112765         var diagnostics = state.diagnostics;
112766         var totalErrors = 0;
112767         if (isCircularBuildOrder(buildOrder)) {
112768             reportBuildQueue(state, buildOrder.buildOrder);
112769             reportErrors(state, buildOrder.circularDiagnostics);
112770             if (canReportSummary)
112771                 totalErrors += ts.getErrorCountForSummary(buildOrder.circularDiagnostics);
112772         }
112773         else {
112774             // Report errors from the other projects
112775             buildOrder.forEach(function (project) {
112776                 var projectPath = toResolvedConfigFilePath(state, project);
112777                 if (!state.projectErrorsReported.has(projectPath)) {
112778                     reportErrors(state, diagnostics.get(projectPath) || ts.emptyArray);
112779                 }
112780             });
112781             if (canReportSummary)
112782                 diagnostics.forEach(function (singleProjectErrors) { return totalErrors += ts.getErrorCountForSummary(singleProjectErrors); });
112783         }
112784         if (state.watch) {
112785             reportWatchStatus(state, ts.getWatchErrorSummaryDiagnosticMessage(totalErrors), totalErrors);
112786         }
112787         else if (state.host.reportErrorSummary) {
112788             state.host.reportErrorSummary(totalErrors);
112789         }
112790     }
112791     /**
112792      * Report the build ordering inferred from the current project graph if we're in verbose mode
112793      */
112794     function reportBuildQueue(state, buildQueue) {
112795         if (state.options.verbose) {
112796             reportStatus(state, ts.Diagnostics.Projects_in_this_build_Colon_0, buildQueue.map(function (s) { return "\r\n    * " + relName(state, s); }).join(""));
112797         }
112798     }
112799     function reportUpToDateStatus(state, configFileName, status) {
112800         switch (status.type) {
112801             case ts.UpToDateStatusType.OutOfDateWithSelf:
112802                 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));
112803             case ts.UpToDateStatusType.OutOfDateWithUpstream:
112804                 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));
112805             case ts.UpToDateStatusType.OutputMissing:
112806                 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));
112807             case ts.UpToDateStatusType.UpToDate:
112808                 if (status.newestInputFileTime !== undefined) {
112809                     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 || ""));
112810                 }
112811                 // Don't report anything for "up to date because it was already built" -- too verbose
112812                 break;
112813             case ts.UpToDateStatusType.OutOfDateWithPrepend:
112814                 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));
112815             case ts.UpToDateStatusType.UpToDateWithUpstreamTypes:
112816                 return reportStatus(state, ts.Diagnostics.Project_0_is_up_to_date_with_d_ts_files_from_its_dependencies, relName(state, configFileName));
112817             case ts.UpToDateStatusType.UpstreamOutOfDate:
112818                 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));
112819             case ts.UpToDateStatusType.UpstreamBlocked:
112820                 return reportStatus(state, status.upstreamProjectBlocked ?
112821                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_was_not_built :
112822                     ts.Diagnostics.Project_0_can_t_be_built_because_its_dependency_1_has_errors, relName(state, configFileName), relName(state, status.upstreamProjectName));
112823             case ts.UpToDateStatusType.Unbuildable:
112824                 return reportStatus(state, ts.Diagnostics.Failed_to_parse_file_0_Colon_1, relName(state, configFileName), status.reason);
112825             case ts.UpToDateStatusType.TsVersionOutputOfDate:
112826                 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);
112827             case ts.UpToDateStatusType.ContainerOnly:
112828             // Don't report status on "solution" projects
112829             // falls through
112830             case ts.UpToDateStatusType.ComputingUpstream:
112831                 // Should never leak from getUptoDateStatusWorker
112832                 break;
112833             default:
112834                 ts.assertType(status);
112835         }
112836     }
112837     /**
112838      * Report the up-to-date status of a project if we're in verbose mode
112839      */
112840     function verboseReportProjectStatus(state, configFileName, status) {
112841         if (state.options.verbose) {
112842             reportUpToDateStatus(state, configFileName, status);
112843         }
112844     }
112845 })(ts || (ts = {}));
112846 var ts;
112847 (function (ts) {
112848     var server;
112849     (function (server) {
112850         /* @internal */
112851         server.ActionSet = "action::set";
112852         /* @internal */
112853         server.ActionInvalidate = "action::invalidate";
112854         /* @internal */
112855         server.ActionPackageInstalled = "action::packageInstalled";
112856         /* @internal */
112857         server.EventTypesRegistry = "event::typesRegistry";
112858         /* @internal */
112859         server.EventBeginInstallTypes = "event::beginInstallTypes";
112860         /* @internal */
112861         server.EventEndInstallTypes = "event::endInstallTypes";
112862         /* @internal */
112863         server.EventInitializationFailed = "event::initializationFailed";
112864         /* @internal */
112865         var Arguments;
112866         (function (Arguments) {
112867             Arguments.GlobalCacheLocation = "--globalTypingsCacheLocation";
112868             Arguments.LogFile = "--logFile";
112869             Arguments.EnableTelemetry = "--enableTelemetry";
112870             Arguments.TypingSafeListLocation = "--typingSafeListLocation";
112871             Arguments.TypesMapLocation = "--typesMapLocation";
112872             /**
112873              * This argument specifies the location of the NPM executable.
112874              * typingsInstaller will run the command with `${npmLocation} install ...`.
112875              */
112876             Arguments.NpmLocation = "--npmLocation";
112877             /**
112878              * Flag indicating that the typings installer should try to validate the default npm location.
112879              * If the default npm is not found when this flag is enabled, fallback to `npm install`
112880              */
112881             Arguments.ValidateDefaultNpmLocation = "--validateDefaultNpmLocation";
112882         })(Arguments = server.Arguments || (server.Arguments = {}));
112883         /* @internal */
112884         function hasArgument(argumentName) {
112885             return ts.sys.args.indexOf(argumentName) >= 0;
112886         }
112887         server.hasArgument = hasArgument;
112888         /* @internal */
112889         function findArgument(argumentName) {
112890             var index = ts.sys.args.indexOf(argumentName);
112891             return index >= 0 && index < ts.sys.args.length - 1
112892                 ? ts.sys.args[index + 1]
112893                 : undefined;
112894         }
112895         server.findArgument = findArgument;
112896         /* @internal */
112897         function nowString() {
112898             // E.g. "12:34:56.789"
112899             var d = new Date();
112900             return ts.padLeft(d.getHours().toString(), 2, "0") + ":" + ts.padLeft(d.getMinutes().toString(), 2, "0") + ":" + ts.padLeft(d.getSeconds().toString(), 2, "0") + "." + ts.padLeft(d.getMilliseconds().toString(), 3, "0");
112901         }
112902         server.nowString = nowString;
112903     })(server = ts.server || (ts.server = {}));
112904 })(ts || (ts = {}));
112905 /* @internal */
112906 var ts;
112907 (function (ts) {
112908     var JsTyping;
112909     (function (JsTyping) {
112910         function isTypingUpToDate(cachedTyping, availableTypingVersions) {
112911             var availableVersion = new ts.Version(ts.getProperty(availableTypingVersions, "ts" + ts.versionMajorMinor) || ts.getProperty(availableTypingVersions, "latest"));
112912             return availableVersion.compareTo(cachedTyping.version) <= 0;
112913         }
112914         JsTyping.isTypingUpToDate = isTypingUpToDate;
112915         JsTyping.nodeCoreModuleList = [
112916             "assert",
112917             "async_hooks",
112918             "buffer",
112919             "child_process",
112920             "cluster",
112921             "console",
112922             "constants",
112923             "crypto",
112924             "dgram",
112925             "dns",
112926             "domain",
112927             "events",
112928             "fs",
112929             "http",
112930             "https",
112931             "http2",
112932             "inspector",
112933             "net",
112934             "os",
112935             "path",
112936             "perf_hooks",
112937             "process",
112938             "punycode",
112939             "querystring",
112940             "readline",
112941             "repl",
112942             "stream",
112943             "string_decoder",
112944             "timers",
112945             "tls",
112946             "tty",
112947             "url",
112948             "util",
112949             "v8",
112950             "vm",
112951             "zlib"
112952         ];
112953         JsTyping.nodeCoreModules = new ts.Set(JsTyping.nodeCoreModuleList);
112954         function nonRelativeModuleNameForTypingCache(moduleName) {
112955             return JsTyping.nodeCoreModules.has(moduleName) ? "node" : moduleName;
112956         }
112957         JsTyping.nonRelativeModuleNameForTypingCache = nonRelativeModuleNameForTypingCache;
112958         function loadSafeList(host, safeListPath) {
112959             var result = ts.readConfigFile(safeListPath, function (path) { return host.readFile(path); });
112960             return new ts.Map(ts.getEntries(result.config));
112961         }
112962         JsTyping.loadSafeList = loadSafeList;
112963         function loadTypesMap(host, typesMapPath) {
112964             var result = ts.readConfigFile(typesMapPath, function (path) { return host.readFile(path); });
112965             if (result.config) {
112966                 return new ts.Map(ts.getEntries(result.config.simpleMap));
112967             }
112968             return undefined;
112969         }
112970         JsTyping.loadTypesMap = loadTypesMap;
112971         /**
112972          * @param host is the object providing I/O related operations.
112973          * @param fileNames are the file names that belong to the same project
112974          * @param projectRootPath is the path to the project root directory
112975          * @param safeListPath is the path used to retrieve the safe list
112976          * @param packageNameToTypingLocation is the map of package names to their cached typing locations and installed versions
112977          * @param typeAcquisition is used to customize the typing acquisition process
112978          * @param compilerOptions are used as a source for typing inference
112979          */
112980         function discoverTypings(host, log, fileNames, projectRootPath, safeList, packageNameToTypingLocation, typeAcquisition, unresolvedImports, typesRegistry) {
112981             if (!typeAcquisition || !typeAcquisition.enable) {
112982                 return { cachedTypingPaths: [], newTypingNames: [], filesToWatch: [] };
112983             }
112984             // A typing name to typing file path mapping
112985             var inferredTypings = new ts.Map();
112986             // Only infer typings for .js and .jsx files
112987             fileNames = ts.mapDefined(fileNames, function (fileName) {
112988                 var path = ts.normalizePath(fileName);
112989                 if (ts.hasJSFileExtension(path)) {
112990                     return path;
112991                 }
112992             });
112993             var filesToWatch = [];
112994             if (typeAcquisition.include)
112995                 addInferredTypings(typeAcquisition.include, "Explicitly included types");
112996             var exclude = typeAcquisition.exclude || [];
112997             // Directories to search for package.json, bower.json and other typing information
112998             var possibleSearchDirs = new ts.Set(fileNames.map(ts.getDirectoryPath));
112999             possibleSearchDirs.add(projectRootPath);
113000             possibleSearchDirs.forEach(function (searchDir) {
113001                 var packageJsonPath = ts.combinePaths(searchDir, "package.json");
113002                 getTypingNamesFromJson(packageJsonPath, filesToWatch);
113003                 var bowerJsonPath = ts.combinePaths(searchDir, "bower.json");
113004                 getTypingNamesFromJson(bowerJsonPath, filesToWatch);
113005                 var bowerComponentsPath = ts.combinePaths(searchDir, "bower_components");
113006                 getTypingNamesFromPackagesFolder(bowerComponentsPath, filesToWatch);
113007                 var nodeModulesPath = ts.combinePaths(searchDir, "node_modules");
113008                 getTypingNamesFromPackagesFolder(nodeModulesPath, filesToWatch);
113009             });
113010             if (!typeAcquisition.disableFilenameBasedTypeAcquisition) {
113011                 getTypingNamesFromSourceFileNames(fileNames);
113012             }
113013             // add typings for unresolved imports
113014             if (unresolvedImports) {
113015                 var module_1 = ts.deduplicate(unresolvedImports.map(nonRelativeModuleNameForTypingCache), ts.equateStringsCaseSensitive, ts.compareStringsCaseSensitive);
113016                 addInferredTypings(module_1, "Inferred typings from unresolved imports");
113017             }
113018             // Add the cached typing locations for inferred typings that are already installed
113019             packageNameToTypingLocation.forEach(function (typing, name) {
113020                 var registryEntry = typesRegistry.get(name);
113021                 if (inferredTypings.has(name) && inferredTypings.get(name) === undefined && registryEntry !== undefined && isTypingUpToDate(typing, registryEntry)) {
113022                     inferredTypings.set(name, typing.typingLocation);
113023                 }
113024             });
113025             // Remove typings that the user has added to the exclude list
113026             for (var _i = 0, exclude_1 = exclude; _i < exclude_1.length; _i++) {
113027                 var excludeTypingName = exclude_1[_i];
113028                 var didDelete = inferredTypings.delete(excludeTypingName);
113029                 if (didDelete && log)
113030                     log("Typing for " + excludeTypingName + " is in exclude list, will be ignored.");
113031             }
113032             var newTypingNames = [];
113033             var cachedTypingPaths = [];
113034             inferredTypings.forEach(function (inferred, typing) {
113035                 if (inferred !== undefined) {
113036                     cachedTypingPaths.push(inferred);
113037                 }
113038                 else {
113039                     newTypingNames.push(typing);
113040                 }
113041             });
113042             var result = { cachedTypingPaths: cachedTypingPaths, newTypingNames: newTypingNames, filesToWatch: filesToWatch };
113043             if (log)
113044                 log("Result: " + JSON.stringify(result));
113045             return result;
113046             function addInferredTyping(typingName) {
113047                 if (!inferredTypings.has(typingName)) {
113048                     inferredTypings.set(typingName, undefined); // TODO: GH#18217
113049                 }
113050             }
113051             function addInferredTypings(typingNames, message) {
113052                 if (log)
113053                     log(message + ": " + JSON.stringify(typingNames));
113054                 ts.forEach(typingNames, addInferredTyping);
113055             }
113056             /**
113057              * Get the typing info from common package manager json files like package.json or bower.json
113058              */
113059             function getTypingNamesFromJson(jsonPath, filesToWatch) {
113060                 if (!host.fileExists(jsonPath)) {
113061                     return;
113062                 }
113063                 filesToWatch.push(jsonPath);
113064                 var jsonConfig = ts.readConfigFile(jsonPath, function (path) { return host.readFile(path); }).config;
113065                 var jsonTypingNames = ts.flatMap([jsonConfig.dependencies, jsonConfig.devDependencies, jsonConfig.optionalDependencies, jsonConfig.peerDependencies], ts.getOwnKeys);
113066                 addInferredTypings(jsonTypingNames, "Typing names in '" + jsonPath + "' dependencies");
113067             }
113068             /**
113069              * Infer typing names from given file names. For example, the file name "jquery-min.2.3.4.js"
113070              * should be inferred to the 'jquery' typing name; and "angular-route.1.2.3.js" should be inferred
113071              * to the 'angular-route' typing name.
113072              * @param fileNames are the names for source files in the project
113073              */
113074             function getTypingNamesFromSourceFileNames(fileNames) {
113075                 var fromFileNames = ts.mapDefined(fileNames, function (j) {
113076                     if (!ts.hasJSFileExtension(j))
113077                         return undefined;
113078                     var inferredTypingName = ts.removeFileExtension(ts.getBaseFileName(j.toLowerCase()));
113079                     var cleanedTypingName = ts.removeMinAndVersionNumbers(inferredTypingName);
113080                     return safeList.get(cleanedTypingName);
113081                 });
113082                 if (fromFileNames.length) {
113083                     addInferredTypings(fromFileNames, "Inferred typings from file names");
113084                 }
113085                 var hasJsxFile = ts.some(fileNames, function (f) { return ts.fileExtensionIs(f, ".jsx" /* Jsx */); });
113086                 if (hasJsxFile) {
113087                     if (log)
113088                         log("Inferred 'react' typings due to presence of '.jsx' extension");
113089                     addInferredTyping("react");
113090                 }
113091             }
113092             /**
113093              * Infer typing names from packages folder (ex: node_module, bower_components)
113094              * @param packagesFolderPath is the path to the packages folder
113095              */
113096             function getTypingNamesFromPackagesFolder(packagesFolderPath, filesToWatch) {
113097                 filesToWatch.push(packagesFolderPath);
113098                 // Todo: add support for ModuleResolutionHost too
113099                 if (!host.directoryExists(packagesFolderPath)) {
113100                     return;
113101                 }
113102                 // depth of 2, so we access `node_modules/foo` but not `node_modules/foo/bar`
113103                 var fileNames = host.readDirectory(packagesFolderPath, [".json" /* Json */], /*excludes*/ undefined, /*includes*/ undefined, /*depth*/ 2);
113104                 if (log)
113105                     log("Searching for typing names in " + packagesFolderPath + "; all files: " + JSON.stringify(fileNames));
113106                 var packageNames = [];
113107                 for (var _i = 0, fileNames_1 = fileNames; _i < fileNames_1.length; _i++) {
113108                     var fileName = fileNames_1[_i];
113109                     var normalizedFileName = ts.normalizePath(fileName);
113110                     var baseFileName = ts.getBaseFileName(normalizedFileName);
113111                     if (baseFileName !== "package.json" && baseFileName !== "bower.json") {
113112                         continue;
113113                     }
113114                     var result_1 = ts.readConfigFile(normalizedFileName, function (path) { return host.readFile(path); });
113115                     var packageJson = result_1.config;
113116                     // npm 3's package.json contains a "_requiredBy" field
113117                     // we should include all the top level module names for npm 2, and only module names whose
113118                     // "_requiredBy" field starts with "#" or equals "/" for npm 3.
113119                     if (baseFileName === "package.json" && packageJson._requiredBy &&
113120                         ts.filter(packageJson._requiredBy, function (r) { return r[0] === "#" || r === "/"; }).length === 0) {
113121                         continue;
113122                     }
113123                     // If the package has its own d.ts typings, those will take precedence. Otherwise the package name will be used
113124                     // to download d.ts files from DefinitelyTyped
113125                     if (!packageJson.name) {
113126                         continue;
113127                     }
113128                     var ownTypes = packageJson.types || packageJson.typings;
113129                     if (ownTypes) {
113130                         var absolutePath = ts.getNormalizedAbsolutePath(ownTypes, ts.getDirectoryPath(normalizedFileName));
113131                         if (log)
113132                             log("    Package '" + packageJson.name + "' provides its own types.");
113133                         inferredTypings.set(packageJson.name, absolutePath);
113134                     }
113135                     else {
113136                         packageNames.push(packageJson.name);
113137                     }
113138                 }
113139                 addInferredTypings(packageNames, "    Found package names");
113140             }
113141         }
113142         JsTyping.discoverTypings = discoverTypings;
113143         var NameValidationResult;
113144         (function (NameValidationResult) {
113145             NameValidationResult[NameValidationResult["Ok"] = 0] = "Ok";
113146             NameValidationResult[NameValidationResult["EmptyName"] = 1] = "EmptyName";
113147             NameValidationResult[NameValidationResult["NameTooLong"] = 2] = "NameTooLong";
113148             NameValidationResult[NameValidationResult["NameStartsWithDot"] = 3] = "NameStartsWithDot";
113149             NameValidationResult[NameValidationResult["NameStartsWithUnderscore"] = 4] = "NameStartsWithUnderscore";
113150             NameValidationResult[NameValidationResult["NameContainsNonURISafeCharacters"] = 5] = "NameContainsNonURISafeCharacters";
113151         })(NameValidationResult = JsTyping.NameValidationResult || (JsTyping.NameValidationResult = {}));
113152         var maxPackageNameLength = 214;
113153         /**
113154          * Validates package name using rules defined at https://docs.npmjs.com/files/package.json
113155          */
113156         function validatePackageName(packageName) {
113157             return validatePackageNameWorker(packageName, /*supportScopedPackage*/ true);
113158         }
113159         JsTyping.validatePackageName = validatePackageName;
113160         function validatePackageNameWorker(packageName, supportScopedPackage) {
113161             if (!packageName) {
113162                 return 1 /* EmptyName */;
113163             }
113164             if (packageName.length > maxPackageNameLength) {
113165                 return 2 /* NameTooLong */;
113166             }
113167             if (packageName.charCodeAt(0) === 46 /* dot */) {
113168                 return 3 /* NameStartsWithDot */;
113169             }
113170             if (packageName.charCodeAt(0) === 95 /* _ */) {
113171                 return 4 /* NameStartsWithUnderscore */;
113172             }
113173             // check if name is scope package like: starts with @ and has one '/' in the middle
113174             // scoped packages are not currently supported
113175             if (supportScopedPackage) {
113176                 var matches = /^@([^/]+)\/([^/]+)$/.exec(packageName);
113177                 if (matches) {
113178                     var scopeResult = validatePackageNameWorker(matches[1], /*supportScopedPackage*/ false);
113179                     if (scopeResult !== 0 /* Ok */) {
113180                         return { name: matches[1], isScopeName: true, result: scopeResult };
113181                     }
113182                     var packageResult = validatePackageNameWorker(matches[2], /*supportScopedPackage*/ false);
113183                     if (packageResult !== 0 /* Ok */) {
113184                         return { name: matches[2], isScopeName: false, result: packageResult };
113185                     }
113186                     return 0 /* Ok */;
113187                 }
113188             }
113189             if (encodeURIComponent(packageName) !== packageName) {
113190                 return 5 /* NameContainsNonURISafeCharacters */;
113191             }
113192             return 0 /* Ok */;
113193         }
113194         function renderPackageNameValidationFailure(result, typing) {
113195             return typeof result === "object" ?
113196                 renderPackageNameValidationFailureWorker(typing, result.result, result.name, result.isScopeName) :
113197                 renderPackageNameValidationFailureWorker(typing, result, typing, /*isScopeName*/ false);
113198         }
113199         JsTyping.renderPackageNameValidationFailure = renderPackageNameValidationFailure;
113200         function renderPackageNameValidationFailureWorker(typing, result, name, isScopeName) {
113201             var kind = isScopeName ? "Scope" : "Package";
113202             switch (result) {
113203                 case 1 /* EmptyName */:
113204                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot be empty";
113205                 case 2 /* NameTooLong */:
113206                     return "'" + typing + "':: " + kind + " name '" + name + "' should be less than " + maxPackageNameLength + " characters";
113207                 case 3 /* NameStartsWithDot */:
113208                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '.'";
113209                 case 4 /* NameStartsWithUnderscore */:
113210                     return "'" + typing + "':: " + kind + " name '" + name + "' cannot start with '_'";
113211                 case 5 /* NameContainsNonURISafeCharacters */:
113212                     return "'" + typing + "':: " + kind + " name '" + name + "' contains non URI safe characters";
113213                 case 0 /* Ok */:
113214                     return ts.Debug.fail(); // Shouldn't have called this.
113215                 default:
113216                     throw ts.Debug.assertNever(result);
113217             }
113218         }
113219     })(JsTyping = ts.JsTyping || (ts.JsTyping = {}));
113220 })(ts || (ts = {}));
113221 var ts;
113222 (function (ts) {
113223     var server;
113224     (function (server) {
113225         var typingsInstaller;
113226         (function (typingsInstaller) {
113227             var nullLog = {
113228                 isEnabled: function () { return false; },
113229                 writeLine: ts.noop
113230             };
113231             function typingToFileName(cachePath, packageName, installTypingHost, log) {
113232                 try {
113233                     var result = ts.resolveModuleName(packageName, ts.combinePaths(cachePath, "index.d.ts"), { moduleResolution: ts.ModuleResolutionKind.NodeJs }, installTypingHost);
113234                     return result.resolvedModule && result.resolvedModule.resolvedFileName;
113235                 }
113236                 catch (e) {
113237                     if (log.isEnabled()) {
113238                         log.writeLine("Failed to resolve " + packageName + " in folder '" + cachePath + "': " + e.message);
113239                     }
113240                     return undefined;
113241                 }
113242             }
113243             /*@internal*/
113244             function installNpmPackages(npmPath, tsVersion, packageNames, install) {
113245                 var hasError = false;
113246                 for (var remaining = packageNames.length; remaining > 0;) {
113247                     var result = getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining);
113248                     remaining = result.remaining;
113249                     hasError = install(result.command) || hasError;
113250                 }
113251                 return hasError;
113252             }
113253             typingsInstaller.installNpmPackages = installNpmPackages;
113254             /*@internal*/
113255             function getNpmCommandForInstallation(npmPath, tsVersion, packageNames, remaining) {
113256                 var sliceStart = packageNames.length - remaining;
113257                 var command, toSlice = remaining;
113258                 while (true) {
113259                     command = npmPath + " install --ignore-scripts " + (toSlice === packageNames.length ? packageNames : packageNames.slice(sliceStart, sliceStart + toSlice)).join(" ") + " --save-dev --user-agent=\"typesInstaller/" + tsVersion + "\"";
113260                     if (command.length < 8000) {
113261                         break;
113262                     }
113263                     toSlice = toSlice - Math.floor(toSlice / 2);
113264                 }
113265                 return { command: command, remaining: remaining - toSlice };
113266             }
113267             typingsInstaller.getNpmCommandForInstallation = getNpmCommandForInstallation;
113268             function endsWith(str, suffix, caseSensitive) {
113269                 var expectedPos = str.length - suffix.length;
113270                 return expectedPos >= 0 &&
113271                     (str.indexOf(suffix, expectedPos) === expectedPos ||
113272                         (!caseSensitive && ts.compareStringsCaseInsensitive(str.substr(expectedPos), suffix) === 0 /* EqualTo */));
113273             }
113274             function isPackageOrBowerJson(fileName, caseSensitive) {
113275                 return endsWith(fileName, "/package.json", caseSensitive) || endsWith(fileName, "/bower.json", caseSensitive);
113276             }
113277             function sameFiles(a, b, caseSensitive) {
113278                 return a === b || (!caseSensitive && ts.compareStringsCaseInsensitive(a, b) === 0 /* EqualTo */);
113279             }
113280             var ProjectWatcherType;
113281             (function (ProjectWatcherType) {
113282                 ProjectWatcherType["FileWatcher"] = "FileWatcher";
113283                 ProjectWatcherType["DirectoryWatcher"] = "DirectoryWatcher";
113284             })(ProjectWatcherType || (ProjectWatcherType = {}));
113285             var TypingsInstaller = /** @class */ (function () {
113286                 function TypingsInstaller(installTypingHost, globalCachePath, safeListPath, typesMapLocation, throttleLimit, log) {
113287                     if (log === void 0) { log = nullLog; }
113288                     this.installTypingHost = installTypingHost;
113289                     this.globalCachePath = globalCachePath;
113290                     this.safeListPath = safeListPath;
113291                     this.typesMapLocation = typesMapLocation;
113292                     this.throttleLimit = throttleLimit;
113293                     this.log = log;
113294                     this.packageNameToTypingLocation = new ts.Map();
113295                     this.missingTypingsSet = new ts.Set();
113296                     this.knownCachesSet = new ts.Set();
113297                     this.projectWatchers = new ts.Map();
113298                     this.pendingRunRequests = [];
113299                     this.installRunCount = 1;
113300                     this.inFlightRequestCount = 0;
113301                     this.latestDistTag = "latest";
113302                     this.toCanonicalFileName = ts.createGetCanonicalFileName(installTypingHost.useCaseSensitiveFileNames);
113303                     this.globalCachePackageJsonPath = ts.combinePaths(globalCachePath, "package.json");
113304                     if (this.log.isEnabled()) {
113305                         this.log.writeLine("Global cache location '" + globalCachePath + "', safe file path '" + safeListPath + "', types map path " + typesMapLocation);
113306                     }
113307                     this.processCacheLocation(this.globalCachePath);
113308                 }
113309                 TypingsInstaller.prototype.closeProject = function (req) {
113310                     this.closeWatchers(req.projectName);
113311                 };
113312                 TypingsInstaller.prototype.closeWatchers = function (projectName) {
113313                     if (this.log.isEnabled()) {
113314                         this.log.writeLine("Closing file watchers for project '" + projectName + "'");
113315                     }
113316                     var watchers = this.projectWatchers.get(projectName);
113317                     if (!watchers) {
113318                         if (this.log.isEnabled()) {
113319                             this.log.writeLine("No watchers are registered for project '" + projectName + "'");
113320                         }
113321                         return;
113322                     }
113323                     ts.clearMap(watchers, ts.closeFileWatcher);
113324                     this.projectWatchers.delete(projectName);
113325                     if (this.log.isEnabled()) {
113326                         this.log.writeLine("Closing file watchers for project '" + projectName + "' - done.");
113327                     }
113328                 };
113329                 TypingsInstaller.prototype.install = function (req) {
113330                     var _this = this;
113331                     if (this.log.isEnabled()) {
113332                         this.log.writeLine("Got install request " + JSON.stringify(req));
113333                     }
113334                     // load existing typing information from the cache
113335                     if (req.cachePath) {
113336                         if (this.log.isEnabled()) {
113337                             this.log.writeLine("Request specifies cache path '" + req.cachePath + "', loading cached information...");
113338                         }
113339                         this.processCacheLocation(req.cachePath);
113340                     }
113341                     if (this.safeList === undefined) {
113342                         this.initializeSafeList();
113343                     }
113344                     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);
113345                     if (this.log.isEnabled()) {
113346                         this.log.writeLine("Finished typings discovery: " + JSON.stringify(discoverTypingsResult));
113347                     }
113348                     // start watching files
113349                     this.watchFiles(req.projectName, discoverTypingsResult.filesToWatch, req.projectRootPath, req.watchOptions);
113350                     // install typings
113351                     if (discoverTypingsResult.newTypingNames.length) {
113352                         this.installTypings(req, req.cachePath || this.globalCachePath, discoverTypingsResult.cachedTypingPaths, discoverTypingsResult.newTypingNames);
113353                     }
113354                     else {
113355                         this.sendResponse(this.createSetTypings(req, discoverTypingsResult.cachedTypingPaths));
113356                         if (this.log.isEnabled()) {
113357                             this.log.writeLine("No new typings were requested as a result of typings discovery");
113358                         }
113359                     }
113360                 };
113361                 TypingsInstaller.prototype.initializeSafeList = function () {
113362                     // Prefer the safe list from the types map if it exists
113363                     if (this.typesMapLocation) {
113364                         var safeListFromMap = ts.JsTyping.loadTypesMap(this.installTypingHost, this.typesMapLocation);
113365                         if (safeListFromMap) {
113366                             this.log.writeLine("Loaded safelist from types map file '" + this.typesMapLocation + "'");
113367                             this.safeList = safeListFromMap;
113368                             return;
113369                         }
113370                         this.log.writeLine("Failed to load safelist from types map file '" + this.typesMapLocation + "'");
113371                     }
113372                     this.safeList = ts.JsTyping.loadSafeList(this.installTypingHost, this.safeListPath);
113373                 };
113374                 TypingsInstaller.prototype.processCacheLocation = function (cacheLocation) {
113375                     if (this.log.isEnabled()) {
113376                         this.log.writeLine("Processing cache location '" + cacheLocation + "'");
113377                     }
113378                     if (this.knownCachesSet.has(cacheLocation)) {
113379                         if (this.log.isEnabled()) {
113380                             this.log.writeLine("Cache location was already processed...");
113381                         }
113382                         return;
113383                     }
113384                     var packageJson = ts.combinePaths(cacheLocation, "package.json");
113385                     var packageLockJson = ts.combinePaths(cacheLocation, "package-lock.json");
113386                     if (this.log.isEnabled()) {
113387                         this.log.writeLine("Trying to find '" + packageJson + "'...");
113388                     }
113389                     if (this.installTypingHost.fileExists(packageJson) && this.installTypingHost.fileExists(packageLockJson)) {
113390                         var npmConfig = JSON.parse(this.installTypingHost.readFile(packageJson)); // TODO: GH#18217
113391                         var npmLock = JSON.parse(this.installTypingHost.readFile(packageLockJson)); // TODO: GH#18217
113392                         if (this.log.isEnabled()) {
113393                             this.log.writeLine("Loaded content of '" + packageJson + "': " + JSON.stringify(npmConfig));
113394                             this.log.writeLine("Loaded content of '" + packageLockJson + "'");
113395                         }
113396                         if (npmConfig.devDependencies && npmLock.dependencies) {
113397                             for (var key in npmConfig.devDependencies) {
113398                                 if (!ts.hasProperty(npmLock.dependencies, key)) {
113399                                     // if package in package.json but not package-lock.json, skip adding to cache so it is reinstalled on next use
113400                                     continue;
113401                                 }
113402                                 // key is @types/<package name>
113403                                 var packageName = ts.getBaseFileName(key);
113404                                 if (!packageName) {
113405                                     continue;
113406                                 }
113407                                 var typingFile = typingToFileName(cacheLocation, packageName, this.installTypingHost, this.log);
113408                                 if (!typingFile) {
113409                                     this.missingTypingsSet.add(packageName);
113410                                     continue;
113411                                 }
113412                                 var existingTypingFile = this.packageNameToTypingLocation.get(packageName);
113413                                 if (existingTypingFile) {
113414                                     if (existingTypingFile.typingLocation === typingFile) {
113415                                         continue;
113416                                     }
113417                                     if (this.log.isEnabled()) {
113418                                         this.log.writeLine("New typing for package " + packageName + " from '" + typingFile + "' conflicts with existing typing file '" + existingTypingFile + "'");
113419                                     }
113420                                 }
113421                                 if (this.log.isEnabled()) {
113422                                     this.log.writeLine("Adding entry into typings cache: '" + packageName + "' => '" + typingFile + "'");
113423                                 }
113424                                 var info = ts.getProperty(npmLock.dependencies, key);
113425                                 var version_1 = info && info.version;
113426                                 if (!version_1) {
113427                                     continue;
113428                                 }
113429                                 var newTyping = { typingLocation: typingFile, version: new ts.Version(version_1) };
113430                                 this.packageNameToTypingLocation.set(packageName, newTyping);
113431                             }
113432                         }
113433                     }
113434                     if (this.log.isEnabled()) {
113435                         this.log.writeLine("Finished processing cache location '" + cacheLocation + "'");
113436                     }
113437                     this.knownCachesSet.add(cacheLocation);
113438                 };
113439                 TypingsInstaller.prototype.filterTypings = function (typingsToInstall) {
113440                     var _this = this;
113441                     return ts.mapDefined(typingsToInstall, function (typing) {
113442                         var typingKey = ts.mangleScopedPackageName(typing);
113443                         if (_this.missingTypingsSet.has(typingKey)) {
113444                             if (_this.log.isEnabled())
113445                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' is in missingTypingsSet - skipping...");
113446                             return undefined;
113447                         }
113448                         var validationResult = ts.JsTyping.validatePackageName(typing);
113449                         if (validationResult !== 0 /* Ok */) {
113450                             // add typing name to missing set so we won't process it again
113451                             _this.missingTypingsSet.add(typingKey);
113452                             if (_this.log.isEnabled())
113453                                 _this.log.writeLine(ts.JsTyping.renderPackageNameValidationFailure(validationResult, typing));
113454                             return undefined;
113455                         }
113456                         if (!_this.typesRegistry.has(typingKey)) {
113457                             if (_this.log.isEnabled())
113458                                 _this.log.writeLine("'" + typing + "':: Entry for package '" + typingKey + "' does not exist in local types registry - skipping...");
113459                             return undefined;
113460                         }
113461                         if (_this.packageNameToTypingLocation.get(typingKey) && ts.JsTyping.isTypingUpToDate(_this.packageNameToTypingLocation.get(typingKey), _this.typesRegistry.get(typingKey))) {
113462                             if (_this.log.isEnabled())
113463                                 _this.log.writeLine("'" + typing + "':: '" + typingKey + "' already has an up-to-date typing - skipping...");
113464                             return undefined;
113465                         }
113466                         return typingKey;
113467                     });
113468                 };
113469                 TypingsInstaller.prototype.ensurePackageDirectoryExists = function (directory) {
113470                     var npmConfigPath = ts.combinePaths(directory, "package.json");
113471                     if (this.log.isEnabled()) {
113472                         this.log.writeLine("Npm config file: " + npmConfigPath);
113473                     }
113474                     if (!this.installTypingHost.fileExists(npmConfigPath)) {
113475                         if (this.log.isEnabled()) {
113476                             this.log.writeLine("Npm config file: '" + npmConfigPath + "' is missing, creating new one...");
113477                         }
113478                         this.ensureDirectoryExists(directory, this.installTypingHost);
113479                         this.installTypingHost.writeFile(npmConfigPath, '{ "private": true }');
113480                     }
113481                 };
113482                 TypingsInstaller.prototype.installTypings = function (req, cachePath, currentlyCachedTypings, typingsToInstall) {
113483                     var _this = this;
113484                     if (this.log.isEnabled()) {
113485                         this.log.writeLine("Installing typings " + JSON.stringify(typingsToInstall));
113486                     }
113487                     var filteredTypings = this.filterTypings(typingsToInstall);
113488                     if (filteredTypings.length === 0) {
113489                         if (this.log.isEnabled()) {
113490                             this.log.writeLine("All typings are known to be missing or invalid - no need to install more typings");
113491                         }
113492                         this.sendResponse(this.createSetTypings(req, currentlyCachedTypings));
113493                         return;
113494                     }
113495                     this.ensurePackageDirectoryExists(cachePath);
113496                     var requestId = this.installRunCount;
113497                     this.installRunCount++;
113498                     // send progress event
113499                     this.sendResponse({
113500                         kind: server.EventBeginInstallTypes,
113501                         eventId: requestId,
113502                         // qualified explicitly to prevent occasional shadowing
113503                         // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
113504                         typingsInstallerVersion: ts.version,
113505                         projectName: req.projectName
113506                     });
113507                     var scopedTypings = filteredTypings.map(typingsName);
113508                     this.installTypingsAsync(requestId, scopedTypings, cachePath, function (ok) {
113509                         try {
113510                             if (!ok) {
113511                                 if (_this.log.isEnabled()) {
113512                                     _this.log.writeLine("install request failed, marking packages as missing to prevent repeated requests: " + JSON.stringify(filteredTypings));
113513                                 }
113514                                 for (var _i = 0, filteredTypings_1 = filteredTypings; _i < filteredTypings_1.length; _i++) {
113515                                     var typing = filteredTypings_1[_i];
113516                                     _this.missingTypingsSet.add(typing);
113517                                 }
113518                                 return;
113519                             }
113520                             // TODO: watch project directory
113521                             if (_this.log.isEnabled()) {
113522                                 _this.log.writeLine("Installed typings " + JSON.stringify(scopedTypings));
113523                             }
113524                             var installedTypingFiles = [];
113525                             for (var _a = 0, filteredTypings_2 = filteredTypings; _a < filteredTypings_2.length; _a++) {
113526                                 var packageName = filteredTypings_2[_a];
113527                                 var typingFile = typingToFileName(cachePath, packageName, _this.installTypingHost, _this.log);
113528                                 if (!typingFile) {
113529                                     _this.missingTypingsSet.add(packageName);
113530                                     continue;
113531                                 }
113532                                 // packageName is guaranteed to exist in typesRegistry by filterTypings
113533                                 var distTags = _this.typesRegistry.get(packageName);
113534                                 var newVersion = new ts.Version(distTags["ts" + ts.versionMajorMinor] || distTags[_this.latestDistTag]);
113535                                 var newTyping = { typingLocation: typingFile, version: newVersion };
113536                                 _this.packageNameToTypingLocation.set(packageName, newTyping);
113537                                 installedTypingFiles.push(typingFile);
113538                             }
113539                             if (_this.log.isEnabled()) {
113540                                 _this.log.writeLine("Installed typing files " + JSON.stringify(installedTypingFiles));
113541                             }
113542                             _this.sendResponse(_this.createSetTypings(req, currentlyCachedTypings.concat(installedTypingFiles)));
113543                         }
113544                         finally {
113545                             var response = {
113546                                 kind: server.EventEndInstallTypes,
113547                                 eventId: requestId,
113548                                 projectName: req.projectName,
113549                                 packagesToInstall: scopedTypings,
113550                                 installSuccess: ok,
113551                                 // qualified explicitly to prevent occasional shadowing
113552                                 // eslint-disable-next-line @typescript-eslint/no-unnecessary-qualifier
113553                                 typingsInstallerVersion: ts.version
113554                             };
113555                             _this.sendResponse(response);
113556                         }
113557                     });
113558                 };
113559                 TypingsInstaller.prototype.ensureDirectoryExists = function (directory, host) {
113560                     var directoryName = ts.getDirectoryPath(directory);
113561                     if (!host.directoryExists(directoryName)) {
113562                         this.ensureDirectoryExists(directoryName, host);
113563                     }
113564                     if (!host.directoryExists(directory)) {
113565                         host.createDirectory(directory);
113566                     }
113567                 };
113568                 TypingsInstaller.prototype.watchFiles = function (projectName, files, projectRootPath, options) {
113569                     var _this = this;
113570                     if (!files.length) {
113571                         // shut down existing watchers
113572                         this.closeWatchers(projectName);
113573                         return;
113574                     }
113575                     var watchers = this.projectWatchers.get(projectName);
113576                     var toRemove = new ts.Map();
113577                     if (!watchers) {
113578                         watchers = new ts.Map();
113579                         this.projectWatchers.set(projectName, watchers);
113580                     }
113581                     else {
113582                         ts.copyEntries(watchers, toRemove);
113583                     }
113584                     // handler should be invoked once for the entire set of files since it will trigger full rediscovery of typings
113585                     watchers.isInvoked = false;
113586                     var isLoggingEnabled = this.log.isEnabled();
113587                     var createProjectWatcher = function (path, projectWatcherType) {
113588                         var canonicalPath = _this.toCanonicalFileName(path);
113589                         toRemove.delete(canonicalPath);
113590                         if (watchers.has(canonicalPath)) {
113591                             return;
113592                         }
113593                         if (isLoggingEnabled) {
113594                             _this.log.writeLine(projectWatcherType + ":: Added:: WatchInfo: " + path);
113595                         }
113596                         var watcher = projectWatcherType === "FileWatcher" /* FileWatcher */ ?
113597                             _this.installTypingHost.watchFile(path, function (f, eventKind) {
113598                                 if (isLoggingEnabled) {
113599                                     _this.log.writeLine("FileWatcher:: Triggered with " + f + " eventKind: " + ts.FileWatcherEventKind[eventKind] + ":: WatchInfo: " + path + ":: handler is already invoked '" + watchers.isInvoked + "'");
113600                                 }
113601                                 if (!watchers.isInvoked) {
113602                                     watchers.isInvoked = true;
113603                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
113604                                 }
113605                             }, /*pollingInterval*/ 2000, options) :
113606                             _this.installTypingHost.watchDirectory(path, function (f) {
113607                                 if (isLoggingEnabled) {
113608                                     _this.log.writeLine("DirectoryWatcher:: Triggered with " + f + " :: WatchInfo: " + path + " recursive :: handler is already invoked '" + watchers.isInvoked + "'");
113609                                 }
113610                                 if (watchers.isInvoked || !ts.fileExtensionIs(f, ".json" /* Json */)) {
113611                                     return;
113612                                 }
113613                                 if (isPackageOrBowerJson(f, _this.installTypingHost.useCaseSensitiveFileNames) &&
113614                                     !sameFiles(f, _this.globalCachePackageJsonPath, _this.installTypingHost.useCaseSensitiveFileNames)) {
113615                                     watchers.isInvoked = true;
113616                                     _this.sendResponse({ projectName: projectName, kind: server.ActionInvalidate });
113617                                 }
113618                             }, /*recursive*/ true, options);
113619                         watchers.set(canonicalPath, isLoggingEnabled ? {
113620                             close: function () {
113621                                 _this.log.writeLine(projectWatcherType + ":: Closed:: WatchInfo: " + path);
113622                                 watcher.close();
113623                             }
113624                         } : watcher);
113625                     };
113626                     // Create watches from list of files
113627                     for (var _i = 0, files_1 = files; _i < files_1.length; _i++) {
113628                         var file = files_1[_i];
113629                         if (file.endsWith("/package.json") || file.endsWith("/bower.json")) {
113630                             // package.json or bower.json exists, watch the file to detect changes and update typings
113631                             createProjectWatcher(file, "FileWatcher" /* FileWatcher */);
113632                             continue;
113633                         }
113634                         // path in projectRoot, watch project root
113635                         if (ts.containsPath(projectRootPath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
113636                             var subDirectory = file.indexOf(ts.directorySeparator, projectRootPath.length + 1);
113637                             if (subDirectory !== -1) {
113638                                 // Watch subDirectory
113639                                 createProjectWatcher(file.substr(0, subDirectory), "DirectoryWatcher" /* DirectoryWatcher */);
113640                             }
113641                             else {
113642                                 // Watch the directory itself
113643                                 createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
113644                             }
113645                             continue;
113646                         }
113647                         // path in global cache, watch global cache
113648                         if (ts.containsPath(this.globalCachePath, file, projectRootPath, !this.installTypingHost.useCaseSensitiveFileNames)) {
113649                             createProjectWatcher(this.globalCachePath, "DirectoryWatcher" /* DirectoryWatcher */);
113650                             continue;
113651                         }
113652                         // watch node_modules or bower_components
113653                         createProjectWatcher(file, "DirectoryWatcher" /* DirectoryWatcher */);
113654                     }
113655                     // Remove unused watches
113656                     toRemove.forEach(function (watch, path) {
113657                         watch.close();
113658                         watchers.delete(path);
113659                     });
113660                 };
113661                 TypingsInstaller.prototype.createSetTypings = function (request, typings) {
113662                     return {
113663                         projectName: request.projectName,
113664                         typeAcquisition: request.typeAcquisition,
113665                         compilerOptions: request.compilerOptions,
113666                         typings: typings,
113667                         unresolvedImports: request.unresolvedImports,
113668                         kind: server.ActionSet
113669                     };
113670                 };
113671                 TypingsInstaller.prototype.installTypingsAsync = function (requestId, packageNames, cwd, onRequestCompleted) {
113672                     this.pendingRunRequests.unshift({ requestId: requestId, packageNames: packageNames, cwd: cwd, onRequestCompleted: onRequestCompleted });
113673                     this.executeWithThrottling();
113674                 };
113675                 TypingsInstaller.prototype.executeWithThrottling = function () {
113676                     var _this = this;
113677                     var _loop_1 = function () {
113678                         this_1.inFlightRequestCount++;
113679                         var request = this_1.pendingRunRequests.pop();
113680                         this_1.installWorker(request.requestId, request.packageNames, request.cwd, function (ok) {
113681                             _this.inFlightRequestCount--;
113682                             request.onRequestCompleted(ok);
113683                             _this.executeWithThrottling();
113684                         });
113685                     };
113686                     var this_1 = this;
113687                     while (this.inFlightRequestCount < this.throttleLimit && this.pendingRunRequests.length) {
113688                         _loop_1();
113689                     }
113690                 };
113691                 return TypingsInstaller;
113692             }());
113693             typingsInstaller.TypingsInstaller = TypingsInstaller;
113694             /* @internal */
113695             function typingsName(packageName) {
113696                 return "@types/" + packageName + "@ts" + ts.versionMajorMinor;
113697             }
113698             typingsInstaller.typingsName = typingsName;
113699         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
113700     })(server = ts.server || (ts.server = {}));
113701 })(ts || (ts = {}));
113702 var ts;
113703 (function (ts) {
113704     var server;
113705     (function (server) {
113706         var typingsInstaller;
113707         (function (typingsInstaller) {
113708             var fs = require("fs");
113709             var path = require("path");
113710             var FileLog = (function () {
113711                 function FileLog(logFile) {
113712                     var _this = this;
113713                     this.logFile = logFile;
113714                     this.isEnabled = function () {
113715                         return typeof _this.logFile === "string";
113716                     };
113717                     this.writeLine = function (text) {
113718                         if (typeof _this.logFile !== "string")
113719                             return;
113720                         try {
113721                             fs.appendFileSync(_this.logFile, "[" + server.nowString() + "] " + text + ts.sys.newLine);
113722                         }
113723                         catch (e) {
113724                             _this.logFile = undefined;
113725                         }
113726                     };
113727                 }
113728                 return FileLog;
113729             }());
113730             function getDefaultNPMLocation(processName, validateDefaultNpmLocation, host) {
113731                 if (path.basename(processName).indexOf("node") === 0) {
113732                     var npmPath = path.join(path.dirname(process.argv[0]), "npm");
113733                     if (!validateDefaultNpmLocation) {
113734                         return npmPath;
113735                     }
113736                     if (host.fileExists(npmPath)) {
113737                         return "\"" + npmPath + "\"";
113738                     }
113739                 }
113740                 return "npm";
113741             }
113742             function loadTypesRegistryFile(typesRegistryFilePath, host, log) {
113743                 if (!host.fileExists(typesRegistryFilePath)) {
113744                     if (log.isEnabled()) {
113745                         log.writeLine("Types registry file '" + typesRegistryFilePath + "' does not exist");
113746                     }
113747                     return new ts.Map();
113748                 }
113749                 try {
113750                     var content = JSON.parse(host.readFile(typesRegistryFilePath));
113751                     return new ts.Map(ts.getEntries(content.entries));
113752                 }
113753                 catch (e) {
113754                     if (log.isEnabled()) {
113755                         log.writeLine("Error when loading types registry file '" + typesRegistryFilePath + "': " + e.message + ", " + e.stack);
113756                     }
113757                     return new ts.Map();
113758                 }
113759             }
113760             var typesRegistryPackageName = "types-registry";
113761             function getTypesRegistryFileLocation(globalTypingsCacheLocation) {
113762                 return ts.combinePaths(ts.normalizeSlashes(globalTypingsCacheLocation), "node_modules/" + typesRegistryPackageName + "/index.json");
113763             }
113764             var NodeTypingsInstaller = (function (_super) {
113765                 __extends(NodeTypingsInstaller, _super);
113766                 function NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, throttleLimit, log) {
113767                     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;
113768                     _this.npmPath = npmLocation !== undefined ? npmLocation : getDefaultNPMLocation(process.argv[0], validateDefaultNpmLocation, _this.installTypingHost);
113769                     if (ts.stringContains(_this.npmPath, " ") && _this.npmPath[0] !== "\"") {
113770                         _this.npmPath = "\"" + _this.npmPath + "\"";
113771                     }
113772                     if (_this.log.isEnabled()) {
113773                         _this.log.writeLine("Process id: " + process.pid);
113774                         _this.log.writeLine("NPM location: " + _this.npmPath + " (explicit '" + server.Arguments.NpmLocation + "' " + (npmLocation === undefined ? "not " : "") + " provided)");
113775                         _this.log.writeLine("validateDefaultNpmLocation: " + validateDefaultNpmLocation);
113776                     }
113777                     (_this.nodeExecSync = require("child_process").execSync);
113778                     _this.ensurePackageDirectoryExists(globalTypingsCacheLocation);
113779                     try {
113780                         if (_this.log.isEnabled()) {
113781                             _this.log.writeLine("Updating " + typesRegistryPackageName + " npm package...");
113782                         }
113783                         _this.execSyncAndLog(_this.npmPath + " install --ignore-scripts " + typesRegistryPackageName + "@" + _this.latestDistTag, { cwd: globalTypingsCacheLocation });
113784                         if (_this.log.isEnabled()) {
113785                             _this.log.writeLine("Updated " + typesRegistryPackageName + " npm package");
113786                         }
113787                     }
113788                     catch (e) {
113789                         if (_this.log.isEnabled()) {
113790                             _this.log.writeLine("Error updating " + typesRegistryPackageName + " package: " + e.message);
113791                         }
113792                         _this.delayedInitializationError = {
113793                             kind: "event::initializationFailed",
113794                             message: e.message,
113795                             stack: e.stack,
113796                         };
113797                     }
113798                     _this.typesRegistry = loadTypesRegistryFile(getTypesRegistryFileLocation(globalTypingsCacheLocation), _this.installTypingHost, _this.log);
113799                     return _this;
113800                 }
113801                 NodeTypingsInstaller.prototype.listen = function () {
113802                     var _this = this;
113803                     process.on("message", function (req) {
113804                         if (_this.delayedInitializationError) {
113805                             _this.sendResponse(_this.delayedInitializationError);
113806                             _this.delayedInitializationError = undefined;
113807                         }
113808                         switch (req.kind) {
113809                             case "discover":
113810                                 _this.install(req);
113811                                 break;
113812                             case "closeProject":
113813                                 _this.closeProject(req);
113814                                 break;
113815                             case "typesRegistry": {
113816                                 var typesRegistry_1 = {};
113817                                 _this.typesRegistry.forEach(function (value, key) {
113818                                     typesRegistry_1[key] = value;
113819                                 });
113820                                 var response = { kind: server.EventTypesRegistry, typesRegistry: typesRegistry_1 };
113821                                 _this.sendResponse(response);
113822                                 break;
113823                             }
113824                             case "installPackage": {
113825                                 var fileName = req.fileName, packageName_1 = req.packageName, projectName_1 = req.projectName, projectRootPath = req.projectRootPath;
113826                                 var cwd = getDirectoryOfPackageJson(fileName, _this.installTypingHost) || projectRootPath;
113827                                 if (cwd) {
113828                                     _this.installWorker(-1, [packageName_1], cwd, function (success) {
113829                                         var message = success ? "Package " + packageName_1 + " installed." : "There was an error installing " + packageName_1 + ".";
113830                                         var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: success, message: message };
113831                                         _this.sendResponse(response);
113832                                     });
113833                                 }
113834                                 else {
113835                                     var response = { kind: server.ActionPackageInstalled, projectName: projectName_1, success: false, message: "Could not determine a project root path." };
113836                                     _this.sendResponse(response);
113837                                 }
113838                                 break;
113839                             }
113840                             default:
113841                                 ts.Debug.assertNever(req);
113842                         }
113843                     });
113844                 };
113845                 NodeTypingsInstaller.prototype.sendResponse = function (response) {
113846                     if (this.log.isEnabled()) {
113847                         this.log.writeLine("Sending response:\n    " + JSON.stringify(response));
113848                     }
113849                     process.send(response);
113850                     if (this.log.isEnabled()) {
113851                         this.log.writeLine("Response has been sent.");
113852                     }
113853                 };
113854                 NodeTypingsInstaller.prototype.installWorker = function (requestId, packageNames, cwd, onRequestCompleted) {
113855                     var _this = this;
113856                     if (this.log.isEnabled()) {
113857                         this.log.writeLine("#" + requestId + " with arguments'" + JSON.stringify(packageNames) + "'.");
113858                     }
113859                     var start = Date.now();
113860                     var hasError = typingsInstaller.installNpmPackages(this.npmPath, ts.version, packageNames, function (command) { return _this.execSyncAndLog(command, { cwd: cwd }); });
113861                     if (this.log.isEnabled()) {
113862                         this.log.writeLine("npm install #" + requestId + " took: " + (Date.now() - start) + " ms");
113863                     }
113864                     onRequestCompleted(!hasError);
113865                 };
113866                 NodeTypingsInstaller.prototype.execSyncAndLog = function (command, options) {
113867                     if (this.log.isEnabled()) {
113868                         this.log.writeLine("Exec: " + command);
113869                     }
113870                     try {
113871                         var stdout = this.nodeExecSync(command, __assign(__assign({}, options), { encoding: "utf-8" }));
113872                         if (this.log.isEnabled()) {
113873                             this.log.writeLine("    Succeeded. stdout:" + indent(ts.sys.newLine, stdout));
113874                         }
113875                         return false;
113876                     }
113877                     catch (error) {
113878                         var stdout = error.stdout, stderr = error.stderr;
113879                         this.log.writeLine("    Failed. stdout:" + indent(ts.sys.newLine, stdout) + ts.sys.newLine + "    stderr:" + indent(ts.sys.newLine, stderr));
113880                         return true;
113881                     }
113882                 };
113883                 return NodeTypingsInstaller;
113884             }(typingsInstaller.TypingsInstaller));
113885             typingsInstaller.NodeTypingsInstaller = NodeTypingsInstaller;
113886             function getDirectoryOfPackageJson(fileName, host) {
113887                 return ts.forEachAncestorDirectory(ts.getDirectoryPath(fileName), function (directory) {
113888                     if (host.fileExists(ts.combinePaths(directory, "package.json"))) {
113889                         return directory;
113890                     }
113891                 });
113892             }
113893             var logFilePath = server.findArgument(server.Arguments.LogFile);
113894             var globalTypingsCacheLocation = server.findArgument(server.Arguments.GlobalCacheLocation);
113895             var typingSafeListLocation = server.findArgument(server.Arguments.TypingSafeListLocation);
113896             var typesMapLocation = server.findArgument(server.Arguments.TypesMapLocation);
113897             var npmLocation = server.findArgument(server.Arguments.NpmLocation);
113898             var validateDefaultNpmLocation = server.hasArgument(server.Arguments.ValidateDefaultNpmLocation);
113899             var log = new FileLog(logFilePath);
113900             if (log.isEnabled()) {
113901                 process.on("uncaughtException", function (e) {
113902                     log.writeLine("Unhandled exception: " + e + " at " + e.stack);
113903                 });
113904             }
113905             process.on("disconnect", function () {
113906                 if (log.isEnabled()) {
113907                     log.writeLine("Parent process has exited, shutting down...");
113908                 }
113909                 process.exit(0);
113910             });
113911             var installer = new NodeTypingsInstaller(globalTypingsCacheLocation, typingSafeListLocation, typesMapLocation, npmLocation, validateDefaultNpmLocation, 5, log);
113912             installer.listen();
113913             function indent(newline, str) {
113914                 return str && str.length
113915                     ? newline + "    " + str.replace(/\r?\n/, newline + "    ")
113916                     : "";
113917             }
113918         })(typingsInstaller = server.typingsInstaller || (server.typingsInstaller = {}));
113919     })(server = ts.server || (ts.server = {}));
113920 })(ts || (ts = {}));
113921 //# sourceMappingURL=typingsInstaller.js.map